xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 87e2751cf07cc570200d8d356d7f35fee2807779)
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<bool>
139     InsertAssertAlign("insert-assert-align", cl::init(true),
140                       cl::desc("Insert the experimental `assertalign` node."),
141                       cl::ReallyHidden);
142 
143 static cl::opt<unsigned, true>
144     LimitFPPrecision("limit-float-precision",
145                      cl::desc("Generate low-precision inline sequences "
146                               "for some float libcalls"),
147                      cl::location(LimitFloatPrecision), cl::Hidden,
148                      cl::init(0));
149 
150 static cl::opt<unsigned> SwitchPeelThreshold(
151     "switch-peel-threshold", cl::Hidden, cl::init(66),
152     cl::desc("Set the case probability threshold for peeling the case from a "
153              "switch statement. A value greater than 100 will void this "
154              "optimization"));
155 
156 // Limit the width of DAG chains. This is important in general to prevent
157 // DAG-based analysis from blowing up. For example, alias analysis and
158 // load clustering may not complete in reasonable time. It is difficult to
159 // recognize and avoid this situation within each individual analysis, and
160 // future analyses are likely to have the same behavior. Limiting DAG width is
161 // the safe approach and will be especially important with global DAGs.
162 //
163 // MaxParallelChains default is arbitrarily high to avoid affecting
164 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
165 // sequence over this should have been converted to llvm.memcpy by the
166 // frontend. It is easy to induce this behavior with .ll code such as:
167 // %buffer = alloca [4096 x i8]
168 // %data = load [4096 x i8]* %argPtr
169 // store [4096 x i8] %data, [4096 x i8]* %buffer
170 static const unsigned MaxParallelChains = 64;
171 
172 // Return the calling convention if the Value passed requires ABI mangling as it
173 // is a parameter to a function or a return value from a function which is not
174 // an intrinsic.
175 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
176   if (auto *R = dyn_cast<ReturnInst>(V))
177     return R->getParent()->getParent()->getCallingConv();
178 
179   if (auto *CI = dyn_cast<CallInst>(V)) {
180     const bool IsInlineAsm = CI->isInlineAsm();
181     const bool IsIndirectFunctionCall =
182         !IsInlineAsm && !CI->getCalledFunction();
183 
184     // It is possible that the call instruction is an inline asm statement or an
185     // indirect function call in which case the return value of
186     // getCalledFunction() would be nullptr.
187     const bool IsInstrinsicCall =
188         !IsInlineAsm && !IsIndirectFunctionCall &&
189         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
190 
191     if (!IsInlineAsm && !IsInstrinsicCall)
192       return CI->getCallingConv();
193   }
194 
195   return None;
196 }
197 
198 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
199                                       const SDValue *Parts, unsigned NumParts,
200                                       MVT PartVT, EVT ValueVT, const Value *V,
201                                       Optional<CallingConv::ID> CC);
202 
203 /// getCopyFromParts - Create a value that contains the specified legal parts
204 /// combined into the value they represent.  If the parts combine to a type
205 /// larger than ValueVT then AssertOp can be used to specify whether the extra
206 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
207 /// (ISD::AssertSext).
208 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
209                                 const SDValue *Parts, unsigned NumParts,
210                                 MVT PartVT, EVT ValueVT, const Value *V,
211                                 Optional<CallingConv::ID> CC = None,
212                                 Optional<ISD::NodeType> AssertOp = None) {
213   // Let the target assemble the parts if it wants to
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
216                                                    PartVT, ValueVT, CC))
217     return Val;
218 
219   if (ValueVT.isVector())
220     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
221                                   CC);
222 
223   assert(NumParts > 0 && "No parts to assemble!");
224   SDValue Val = Parts[0];
225 
226   if (NumParts > 1) {
227     // Assemble the value from multiple parts.
228     if (ValueVT.isInteger()) {
229       unsigned PartBits = PartVT.getSizeInBits();
230       unsigned ValueBits = ValueVT.getSizeInBits();
231 
232       // Assemble the power of 2 part.
233       unsigned RoundParts =
234           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
235       unsigned RoundBits = PartBits * RoundParts;
236       EVT RoundVT = RoundBits == ValueBits ?
237         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
238       SDValue Lo, Hi;
239 
240       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
241 
242       if (RoundParts > 2) {
243         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
244                               PartVT, HalfVT, V);
245         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
246                               RoundParts / 2, PartVT, HalfVT, V);
247       } else {
248         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
249         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
250       }
251 
252       if (DAG.getDataLayout().isBigEndian())
253         std::swap(Lo, Hi);
254 
255       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
256 
257       if (RoundParts < NumParts) {
258         // Assemble the trailing non-power-of-2 part.
259         unsigned OddParts = NumParts - RoundParts;
260         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
261         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
262                               OddVT, V, CC);
263 
264         // Combine the round and odd parts.
265         Lo = Val;
266         if (DAG.getDataLayout().isBigEndian())
267           std::swap(Lo, Hi);
268         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
269         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
270         Hi =
271             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
272                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
273                                         TLI.getPointerTy(DAG.getDataLayout())));
274         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
275         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
276       }
277     } else if (PartVT.isFloatingPoint()) {
278       // FP split into multiple FP parts (for ppcf128)
279       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
280              "Unexpected split");
281       SDValue Lo, Hi;
282       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
283       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
284       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
285         std::swap(Lo, Hi);
286       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
287     } else {
288       // FP split into integer parts (soft fp)
289       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
290              !PartVT.isVector() && "Unexpected split");
291       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
292       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
293     }
294   }
295 
296   // There is now one part, held in Val.  Correct it to match ValueVT.
297   // PartEVT is the type of the register class that holds the value.
298   // ValueVT is the type of the inline asm operation.
299   EVT PartEVT = Val.getValueType();
300 
301   if (PartEVT == ValueVT)
302     return Val;
303 
304   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
305       ValueVT.bitsLT(PartEVT)) {
306     // For an FP value in an integer part, we need to truncate to the right
307     // width first.
308     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
309     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
310   }
311 
312   // Handle types that have the same size.
313   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
314     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
315 
316   // Handle types with different sizes.
317   if (PartEVT.isInteger() && ValueVT.isInteger()) {
318     if (ValueVT.bitsLT(PartEVT)) {
319       // For a truncate, see if we have any information to
320       // indicate whether the truncated bits will always be
321       // zero or sign-extension.
322       if (AssertOp.hasValue())
323         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
324                           DAG.getValueType(ValueVT));
325       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
326     }
327     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
328   }
329 
330   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
331     // FP_ROUND's are always exact here.
332     if (ValueVT.bitsLT(Val.getValueType()))
333       return DAG.getNode(
334           ISD::FP_ROUND, DL, ValueVT, Val,
335           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
336 
337     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
338   }
339 
340   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
341   // then truncating.
342   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
343       ValueVT.bitsLT(PartEVT)) {
344     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
345     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
346   }
347 
348   report_fatal_error("Unknown mismatch in getCopyFromParts!");
349 }
350 
351 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
352                                               const Twine &ErrMsg) {
353   const Instruction *I = dyn_cast_or_null<Instruction>(V);
354   if (!V)
355     return Ctx.emitError(ErrMsg);
356 
357   const char *AsmError = ", possible invalid constraint for vector type";
358   if (const CallInst *CI = dyn_cast<CallInst>(I))
359     if (CI->isInlineAsm())
360       return Ctx.emitError(I, ErrMsg + AsmError);
361 
362   return Ctx.emitError(I, ErrMsg);
363 }
364 
365 /// getCopyFromPartsVector - Create a value that contains the specified legal
366 /// parts combined into the value they represent.  If the parts combine to a
367 /// type larger than ValueVT then AssertOp can be used to specify whether the
368 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
369 /// ValueVT (ISD::AssertSext).
370 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
371                                       const SDValue *Parts, unsigned NumParts,
372                                       MVT PartVT, EVT ValueVT, const Value *V,
373                                       Optional<CallingConv::ID> CallConv) {
374   assert(ValueVT.isVector() && "Not a vector value");
375   assert(NumParts > 0 && "No parts to assemble!");
376   const bool IsABIRegCopy = CallConv.hasValue();
377 
378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
379   SDValue Val = Parts[0];
380 
381   // Handle a multi-element vector.
382   if (NumParts > 1) {
383     EVT IntermediateVT;
384     MVT RegisterVT;
385     unsigned NumIntermediates;
386     unsigned NumRegs;
387 
388     if (IsABIRegCopy) {
389       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
390           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
391           NumIntermediates, RegisterVT);
392     } else {
393       NumRegs =
394           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
395                                      NumIntermediates, RegisterVT);
396     }
397 
398     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
399     NumParts = NumRegs; // Silence a compiler warning.
400     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
401     assert(RegisterVT.getSizeInBits() ==
402            Parts[0].getSimpleValueType().getSizeInBits() &&
403            "Part type sizes don't match!");
404 
405     // Assemble the parts into intermediate operands.
406     SmallVector<SDValue, 8> Ops(NumIntermediates);
407     if (NumIntermediates == NumParts) {
408       // If the register was not expanded, truncate or copy the value,
409       // as appropriate.
410       for (unsigned i = 0; i != NumParts; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
412                                   PartVT, IntermediateVT, V);
413     } else if (NumParts > 0) {
414       // If the intermediate type was expanded, build the intermediate
415       // operands from the parts.
416       assert(NumParts % NumIntermediates == 0 &&
417              "Must expand into a divisible number of parts!");
418       unsigned Factor = NumParts / NumIntermediates;
419       for (unsigned i = 0; i != NumIntermediates; ++i)
420         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
421                                   PartVT, IntermediateVT, V);
422     }
423 
424     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
425     // intermediate operands.
426     EVT BuiltVectorTy =
427         IntermediateVT.isVector()
428             ? EVT::getVectorVT(
429                   *DAG.getContext(), IntermediateVT.getScalarType(),
430                   IntermediateVT.getVectorElementCount() * NumParts)
431             : EVT::getVectorVT(*DAG.getContext(),
432                                IntermediateVT.getScalarType(),
433                                NumIntermediates);
434     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
435                                                 : ISD::BUILD_VECTOR,
436                       DL, BuiltVectorTy, Ops);
437   }
438 
439   // There is now one part, held in Val.  Correct it to match ValueVT.
440   EVT PartEVT = Val.getValueType();
441 
442   if (PartEVT == ValueVT)
443     return Val;
444 
445   if (PartEVT.isVector()) {
446     // If the element type of the source/dest vectors are the same, but the
447     // parts vector has more elements than the value vector, then we have a
448     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
449     // elements we want.
450     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
451       assert((PartEVT.getVectorElementCount().Min >
452               ValueVT.getVectorElementCount().Min) &&
453              (PartEVT.getVectorElementCount().Scalable ==
454               ValueVT.getVectorElementCount().Scalable) &&
455              "Cannot narrow, it would be a lossy transformation");
456       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
457                          DAG.getVectorIdxConstant(0, DL));
458     }
459 
460     // Vector/Vector bitcast.
461     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
462       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
463 
464     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
465       "Cannot handle this kind of promotion");
466     // Promoted vector extract
467     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
468 
469   }
470 
471   // Trivial bitcast if the types are the same size and the destination
472   // vector type is legal.
473   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
474       TLI.isTypeLegal(ValueVT))
475     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
476 
477   if (ValueVT.getVectorNumElements() != 1) {
478      // Certain ABIs require that vectors are passed as integers. For vectors
479      // are the same size, this is an obvious bitcast.
480      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
481        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
482      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
483        // Bitcast Val back the original type and extract the corresponding
484        // vector we want.
485        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
486        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
487                                            ValueVT.getVectorElementType(), Elts);
488        Val = DAG.getBitcast(WiderVecType, Val);
489        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
490                           DAG.getVectorIdxConstant(0, DL));
491      }
492 
493      diagnosePossiblyInvalidConstraint(
494          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
495      return DAG.getUNDEF(ValueVT);
496   }
497 
498   // Handle cases such as i8 -> <1 x i1>
499   EVT ValueSVT = ValueVT.getVectorElementType();
500   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
501     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
502       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
503     else
504       Val = ValueVT.isFloatingPoint()
505                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
506                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
507   }
508 
509   return DAG.getBuildVector(ValueVT, DL, Val);
510 }
511 
512 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
513                                  SDValue Val, SDValue *Parts, unsigned NumParts,
514                                  MVT PartVT, const Value *V,
515                                  Optional<CallingConv::ID> CallConv);
516 
517 /// getCopyToParts - Create a series of nodes that contain the specified value
518 /// split into legal parts.  If the parts contain more bits than Val, then, for
519 /// integers, ExtendKind can be used to specify how to generate the extra bits.
520 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
521                            SDValue *Parts, unsigned NumParts, MVT PartVT,
522                            const Value *V,
523                            Optional<CallingConv::ID> CallConv = None,
524                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
525   // Let the target split the parts if it wants to
526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
527   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
528                                       CallConv))
529     return;
530   EVT ValueVT = Val.getValueType();
531 
532   // Handle the vector case separately.
533   if (ValueVT.isVector())
534     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
535                                 CallConv);
536 
537   unsigned PartBits = PartVT.getSizeInBits();
538   unsigned OrigNumParts = NumParts;
539   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
540          "Copying to an illegal type!");
541 
542   if (NumParts == 0)
543     return;
544 
545   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
546   EVT PartEVT = PartVT;
547   if (PartEVT == ValueVT) {
548     assert(NumParts == 1 && "No-op copy with multiple parts!");
549     Parts[0] = Val;
550     return;
551   }
552 
553   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
554     // If the parts cover more bits than the value has, promote the value.
555     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
556       assert(NumParts == 1 && "Do not know what to promote to!");
557       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
558     } else {
559       if (ValueVT.isFloatingPoint()) {
560         // FP values need to be bitcast, then extended if they are being put
561         // into a larger container.
562         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
563         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
564       }
565       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
566              ValueVT.isInteger() &&
567              "Unknown mismatch!");
568       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
569       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
570       if (PartVT == MVT::x86mmx)
571         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
572     }
573   } else if (PartBits == ValueVT.getSizeInBits()) {
574     // Different types of the same size.
575     assert(NumParts == 1 && PartEVT != ValueVT);
576     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
577   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
578     // If the parts cover less bits than value has, truncate the value.
579     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
580            ValueVT.isInteger() &&
581            "Unknown mismatch!");
582     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
583     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
584     if (PartVT == MVT::x86mmx)
585       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
586   }
587 
588   // The value may have changed - recompute ValueVT.
589   ValueVT = Val.getValueType();
590   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
591          "Failed to tile the value with PartVT!");
592 
593   if (NumParts == 1) {
594     if (PartEVT != ValueVT) {
595       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
596                                         "scalar-to-vector conversion failed");
597       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
598     }
599 
600     Parts[0] = Val;
601     return;
602   }
603 
604   // Expand the value into multiple parts.
605   if (NumParts & (NumParts - 1)) {
606     // The number of parts is not a power of 2.  Split off and copy the tail.
607     assert(PartVT.isInteger() && ValueVT.isInteger() &&
608            "Do not know what to expand to!");
609     unsigned RoundParts = 1 << Log2_32(NumParts);
610     unsigned RoundBits = RoundParts * PartBits;
611     unsigned OddParts = NumParts - RoundParts;
612     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
613       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
614 
615     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
616                    CallConv);
617 
618     if (DAG.getDataLayout().isBigEndian())
619       // The odd parts were reversed by getCopyToParts - unreverse them.
620       std::reverse(Parts + RoundParts, Parts + NumParts);
621 
622     NumParts = RoundParts;
623     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
624     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
625   }
626 
627   // The number of parts is a power of 2.  Repeatedly bisect the value using
628   // EXTRACT_ELEMENT.
629   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
630                          EVT::getIntegerVT(*DAG.getContext(),
631                                            ValueVT.getSizeInBits()),
632                          Val);
633 
634   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
635     for (unsigned i = 0; i < NumParts; i += StepSize) {
636       unsigned ThisBits = StepSize * PartBits / 2;
637       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
638       SDValue &Part0 = Parts[i];
639       SDValue &Part1 = Parts[i+StepSize/2];
640 
641       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
642                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
643       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
644                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
645 
646       if (ThisBits == PartBits && ThisVT != PartVT) {
647         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
648         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
649       }
650     }
651   }
652 
653   if (DAG.getDataLayout().isBigEndian())
654     std::reverse(Parts, Parts + OrigNumParts);
655 }
656 
657 static SDValue widenVectorToPartType(SelectionDAG &DAG,
658                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
659   if (!PartVT.isVector())
660     return SDValue();
661 
662   EVT ValueVT = Val.getValueType();
663   unsigned PartNumElts = PartVT.getVectorNumElements();
664   unsigned ValueNumElts = ValueVT.getVectorNumElements();
665   if (PartNumElts > ValueNumElts &&
666       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
667     EVT ElementVT = PartVT.getVectorElementType();
668     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
669     // undef elements.
670     SmallVector<SDValue, 16> Ops;
671     DAG.ExtractVectorElements(Val, Ops);
672     SDValue EltUndef = DAG.getUNDEF(ElementVT);
673     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
674       Ops.push_back(EltUndef);
675 
676     // FIXME: Use CONCAT for 2x -> 4x.
677     return DAG.getBuildVector(PartVT, DL, Ops);
678   }
679 
680   return SDValue();
681 }
682 
683 /// getCopyToPartsVector - Create a series of nodes that contain the specified
684 /// value split into legal parts.
685 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
686                                  SDValue Val, SDValue *Parts, unsigned NumParts,
687                                  MVT PartVT, const Value *V,
688                                  Optional<CallingConv::ID> CallConv) {
689   EVT ValueVT = Val.getValueType();
690   assert(ValueVT.isVector() && "Not a vector");
691   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
692   const bool IsABIRegCopy = CallConv.hasValue();
693 
694   if (NumParts == 1) {
695     EVT PartEVT = PartVT;
696     if (PartEVT == ValueVT) {
697       // Nothing to do.
698     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
699       // Bitconvert vector->vector case.
700       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
701     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
702       Val = Widened;
703     } else if (PartVT.isVector() &&
704                PartEVT.getVectorElementType().bitsGE(
705                  ValueVT.getVectorElementType()) &&
706                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
707 
708       // Promoted vector extract
709       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
710     } else {
711       if (ValueVT.getVectorNumElements() == 1) {
712         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
713                           DAG.getVectorIdxConstant(0, DL));
714       } else {
715         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
716                "lossy conversion of vector to scalar type");
717         EVT IntermediateType =
718             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
719         Val = DAG.getBitcast(IntermediateType, Val);
720         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
721       }
722     }
723 
724     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
725     Parts[0] = Val;
726     return;
727   }
728 
729   // Handle a multi-element vector.
730   EVT IntermediateVT;
731   MVT RegisterVT;
732   unsigned NumIntermediates;
733   unsigned NumRegs;
734   if (IsABIRegCopy) {
735     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
736         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
737         NumIntermediates, RegisterVT);
738   } else {
739     NumRegs =
740         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
741                                    NumIntermediates, RegisterVT);
742   }
743 
744   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
745   NumParts = NumRegs; // Silence a compiler warning.
746   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
747 
748   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
749          "Mixing scalable and fixed vectors when copying in parts");
750 
751   ElementCount DestEltCnt;
752 
753   if (IntermediateVT.isVector())
754     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
755   else
756     DestEltCnt = ElementCount(NumIntermediates, false);
757 
758   EVT BuiltVectorTy = EVT::getVectorVT(
759       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt);
760   if (ValueVT != BuiltVectorTy) {
761     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
762       Val = Widened;
763 
764     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
765   }
766 
767   // Split the vector into intermediate operands.
768   SmallVector<SDValue, 8> Ops(NumIntermediates);
769   for (unsigned i = 0; i != NumIntermediates; ++i) {
770     if (IntermediateVT.isVector()) {
771       // This does something sensible for scalable vectors - see the
772       // definition of EXTRACT_SUBVECTOR for further details.
773       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
774       Ops[i] =
775           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
776                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
777     } else {
778       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
779                            DAG.getVectorIdxConstant(i, DL));
780     }
781   }
782 
783   // Split the intermediate operands into legal parts.
784   if (NumParts == NumIntermediates) {
785     // If the register was not expanded, promote or copy the value,
786     // as appropriate.
787     for (unsigned i = 0; i != NumParts; ++i)
788       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
789   } else if (NumParts > 0) {
790     // If the intermediate type was expanded, split each the value into
791     // legal parts.
792     assert(NumIntermediates != 0 && "division by zero");
793     assert(NumParts % NumIntermediates == 0 &&
794            "Must expand into a divisible number of parts!");
795     unsigned Factor = NumParts / NumIntermediates;
796     for (unsigned i = 0; i != NumIntermediates; ++i)
797       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
798                      CallConv);
799   }
800 }
801 
802 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
803                            EVT valuevt, Optional<CallingConv::ID> CC)
804     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
805       RegCount(1, regs.size()), CallConv(CC) {}
806 
807 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
808                            const DataLayout &DL, unsigned Reg, Type *Ty,
809                            Optional<CallingConv::ID> CC) {
810   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
811 
812   CallConv = CC;
813 
814   for (EVT ValueVT : ValueVTs) {
815     unsigned NumRegs =
816         isABIMangled()
817             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
818             : TLI.getNumRegisters(Context, ValueVT);
819     MVT RegisterVT =
820         isABIMangled()
821             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
822             : TLI.getRegisterType(Context, ValueVT);
823     for (unsigned i = 0; i != NumRegs; ++i)
824       Regs.push_back(Reg + i);
825     RegVTs.push_back(RegisterVT);
826     RegCount.push_back(NumRegs);
827     Reg += NumRegs;
828   }
829 }
830 
831 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
832                                       FunctionLoweringInfo &FuncInfo,
833                                       const SDLoc &dl, SDValue &Chain,
834                                       SDValue *Flag, const Value *V) const {
835   // A Value with type {} or [0 x %t] needs no registers.
836   if (ValueVTs.empty())
837     return SDValue();
838 
839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
840 
841   // Assemble the legal parts into the final values.
842   SmallVector<SDValue, 4> Values(ValueVTs.size());
843   SmallVector<SDValue, 8> Parts;
844   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
845     // Copy the legal parts from the registers.
846     EVT ValueVT = ValueVTs[Value];
847     unsigned NumRegs = RegCount[Value];
848     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
849                                           *DAG.getContext(),
850                                           CallConv.getValue(), RegVTs[Value])
851                                     : RegVTs[Value];
852 
853     Parts.resize(NumRegs);
854     for (unsigned i = 0; i != NumRegs; ++i) {
855       SDValue P;
856       if (!Flag) {
857         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
858       } else {
859         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
860         *Flag = P.getValue(2);
861       }
862 
863       Chain = P.getValue(1);
864       Parts[i] = P;
865 
866       // If the source register was virtual and if we know something about it,
867       // add an assert node.
868       if (!Register::isVirtualRegister(Regs[Part + i]) ||
869           !RegisterVT.isInteger())
870         continue;
871 
872       const FunctionLoweringInfo::LiveOutInfo *LOI =
873         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
874       if (!LOI)
875         continue;
876 
877       unsigned RegSize = RegisterVT.getScalarSizeInBits();
878       unsigned NumSignBits = LOI->NumSignBits;
879       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
880 
881       if (NumZeroBits == RegSize) {
882         // The current value is a zero.
883         // Explicitly express that as it would be easier for
884         // optimizations to kick in.
885         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
886         continue;
887       }
888 
889       // FIXME: We capture more information than the dag can represent.  For
890       // now, just use the tightest assertzext/assertsext possible.
891       bool isSExt;
892       EVT FromVT(MVT::Other);
893       if (NumZeroBits) {
894         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
895         isSExt = false;
896       } else if (NumSignBits > 1) {
897         FromVT =
898             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
899         isSExt = true;
900       } else {
901         continue;
902       }
903       // Add an assertion node.
904       assert(FromVT != MVT::Other);
905       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
906                              RegisterVT, P, DAG.getValueType(FromVT));
907     }
908 
909     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
910                                      RegisterVT, ValueVT, V, CallConv);
911     Part += NumRegs;
912     Parts.clear();
913   }
914 
915   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
916 }
917 
918 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
919                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
920                                  const Value *V,
921                                  ISD::NodeType PreferredExtendType) const {
922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
923   ISD::NodeType ExtendKind = PreferredExtendType;
924 
925   // Get the list of the values's legal parts.
926   unsigned NumRegs = Regs.size();
927   SmallVector<SDValue, 8> Parts(NumRegs);
928   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
929     unsigned NumParts = RegCount[Value];
930 
931     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
932                                           *DAG.getContext(),
933                                           CallConv.getValue(), RegVTs[Value])
934                                     : RegVTs[Value];
935 
936     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
937       ExtendKind = ISD::ZERO_EXTEND;
938 
939     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
940                    NumParts, RegisterVT, V, CallConv, ExtendKind);
941     Part += NumParts;
942   }
943 
944   // Copy the parts into the registers.
945   SmallVector<SDValue, 8> Chains(NumRegs);
946   for (unsigned i = 0; i != NumRegs; ++i) {
947     SDValue Part;
948     if (!Flag) {
949       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
950     } else {
951       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
952       *Flag = Part.getValue(1);
953     }
954 
955     Chains[i] = Part.getValue(0);
956   }
957 
958   if (NumRegs == 1 || Flag)
959     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
960     // flagged to it. That is the CopyToReg nodes and the user are considered
961     // a single scheduling unit. If we create a TokenFactor and return it as
962     // chain, then the TokenFactor is both a predecessor (operand) of the
963     // user as well as a successor (the TF operands are flagged to the user).
964     // c1, f1 = CopyToReg
965     // c2, f2 = CopyToReg
966     // c3     = TokenFactor c1, c2
967     // ...
968     //        = op c3, ..., f2
969     Chain = Chains[NumRegs-1];
970   else
971     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
972 }
973 
974 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
975                                         unsigned MatchingIdx, const SDLoc &dl,
976                                         SelectionDAG &DAG,
977                                         std::vector<SDValue> &Ops) const {
978   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
979 
980   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
981   if (HasMatching)
982     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
983   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
984     // Put the register class of the virtual registers in the flag word.  That
985     // way, later passes can recompute register class constraints for inline
986     // assembly as well as normal instructions.
987     // Don't do this for tied operands that can use the regclass information
988     // from the def.
989     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
990     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
991     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
992   }
993 
994   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
995   Ops.push_back(Res);
996 
997   if (Code == InlineAsm::Kind_Clobber) {
998     // Clobbers should always have a 1:1 mapping with registers, and may
999     // reference registers that have illegal (e.g. vector) types. Hence, we
1000     // shouldn't try to apply any sort of splitting logic to them.
1001     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1002            "No 1:1 mapping from clobbers to regs?");
1003     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
1004     (void)SP;
1005     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1006       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1007       assert(
1008           (Regs[I] != SP ||
1009            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1010           "If we clobbered the stack pointer, MFI should know about it.");
1011     }
1012     return;
1013   }
1014 
1015   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1016     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
1017     MVT RegisterVT = RegVTs[Value];
1018     for (unsigned i = 0; i != NumRegs; ++i) {
1019       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1020       unsigned TheReg = Regs[Reg++];
1021       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1022     }
1023   }
1024 }
1025 
1026 SmallVector<std::pair<unsigned, unsigned>, 4>
1027 RegsForValue::getRegsAndSizes() const {
1028   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1029   unsigned I = 0;
1030   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1031     unsigned RegCount = std::get<0>(CountAndVT);
1032     MVT RegisterVT = std::get<1>(CountAndVT);
1033     unsigned RegisterSize = RegisterVT.getSizeInBits();
1034     for (unsigned E = I + RegCount; I != E; ++I)
1035       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1036   }
1037   return OutVec;
1038 }
1039 
1040 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1041                                const TargetLibraryInfo *li) {
1042   AA = aa;
1043   GFI = gfi;
1044   LibInfo = li;
1045   DL = &DAG.getDataLayout();
1046   Context = DAG.getContext();
1047   LPadToCallSiteMap.clear();
1048   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1049 }
1050 
1051 void SelectionDAGBuilder::clear() {
1052   NodeMap.clear();
1053   UnusedArgNodeMap.clear();
1054   PendingLoads.clear();
1055   PendingExports.clear();
1056   PendingConstrainedFP.clear();
1057   PendingConstrainedFPStrict.clear();
1058   CurInst = nullptr;
1059   HasTailCall = false;
1060   SDNodeOrder = LowestSDNodeOrder;
1061   StatepointLowering.clear();
1062 }
1063 
1064 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1065   DanglingDebugInfoMap.clear();
1066 }
1067 
1068 // Update DAG root to include dependencies on Pending chains.
1069 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1070   SDValue Root = DAG.getRoot();
1071 
1072   if (Pending.empty())
1073     return Root;
1074 
1075   // Add current root to PendingChains, unless we already indirectly
1076   // depend on it.
1077   if (Root.getOpcode() != ISD::EntryToken) {
1078     unsigned i = 0, e = Pending.size();
1079     for (; i != e; ++i) {
1080       assert(Pending[i].getNode()->getNumOperands() > 1);
1081       if (Pending[i].getNode()->getOperand(0) == Root)
1082         break;  // Don't add the root if we already indirectly depend on it.
1083     }
1084 
1085     if (i == e)
1086       Pending.push_back(Root);
1087   }
1088 
1089   if (Pending.size() == 1)
1090     Root = Pending[0];
1091   else
1092     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1093 
1094   DAG.setRoot(Root);
1095   Pending.clear();
1096   return Root;
1097 }
1098 
1099 SDValue SelectionDAGBuilder::getMemoryRoot() {
1100   return updateRoot(PendingLoads);
1101 }
1102 
1103 SDValue SelectionDAGBuilder::getRoot() {
1104   // Chain up all pending constrained intrinsics together with all
1105   // pending loads, by simply appending them to PendingLoads and
1106   // then calling getMemoryRoot().
1107   PendingLoads.reserve(PendingLoads.size() +
1108                        PendingConstrainedFP.size() +
1109                        PendingConstrainedFPStrict.size());
1110   PendingLoads.append(PendingConstrainedFP.begin(),
1111                       PendingConstrainedFP.end());
1112   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1113                       PendingConstrainedFPStrict.end());
1114   PendingConstrainedFP.clear();
1115   PendingConstrainedFPStrict.clear();
1116   return getMemoryRoot();
1117 }
1118 
1119 SDValue SelectionDAGBuilder::getControlRoot() {
1120   // We need to emit pending fpexcept.strict constrained intrinsics,
1121   // so append them to the PendingExports list.
1122   PendingExports.append(PendingConstrainedFPStrict.begin(),
1123                         PendingConstrainedFPStrict.end());
1124   PendingConstrainedFPStrict.clear();
1125   return updateRoot(PendingExports);
1126 }
1127 
1128 void SelectionDAGBuilder::visit(const Instruction &I) {
1129   // Set up outgoing PHI node register values before emitting the terminator.
1130   if (I.isTerminator()) {
1131     HandlePHINodesInSuccessorBlocks(I.getParent());
1132   }
1133 
1134   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1135   if (!isa<DbgInfoIntrinsic>(I))
1136     ++SDNodeOrder;
1137 
1138   CurInst = &I;
1139 
1140   visit(I.getOpcode(), I);
1141 
1142   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1143     // ConstrainedFPIntrinsics handle their own FMF.
1144     if (!isa<ConstrainedFPIntrinsic>(&I)) {
1145       // Propagate the fast-math-flags of this IR instruction to the DAG node that
1146       // maps to this instruction.
1147       // TODO: We could handle all flags (nsw, etc) here.
1148       // TODO: If an IR instruction maps to >1 node, only the final node will have
1149       //       flags set.
1150       if (SDNode *Node = getNodeForIRValue(&I)) {
1151         SDNodeFlags IncomingFlags;
1152         IncomingFlags.copyFMF(*FPMO);
1153         if (!Node->getFlags().isDefined())
1154           Node->setFlags(IncomingFlags);
1155         else
1156           Node->intersectFlagsWith(IncomingFlags);
1157       }
1158     }
1159   }
1160 
1161   if (!I.isTerminator() && !HasTailCall &&
1162       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1163     CopyToExportRegsIfNeeded(&I);
1164 
1165   CurInst = nullptr;
1166 }
1167 
1168 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1169   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1170 }
1171 
1172 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1173   // Note: this doesn't use InstVisitor, because it has to work with
1174   // ConstantExpr's in addition to instructions.
1175   switch (Opcode) {
1176   default: llvm_unreachable("Unknown instruction type encountered!");
1177     // Build the switch statement using the Instruction.def file.
1178 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1179     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1180 #include "llvm/IR/Instruction.def"
1181   }
1182 }
1183 
1184 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1185                                                 const DIExpression *Expr) {
1186   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1187     const DbgValueInst *DI = DDI.getDI();
1188     DIVariable *DanglingVariable = DI->getVariable();
1189     DIExpression *DanglingExpr = DI->getExpression();
1190     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1191       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1192       return true;
1193     }
1194     return false;
1195   };
1196 
1197   for (auto &DDIMI : DanglingDebugInfoMap) {
1198     DanglingDebugInfoVector &DDIV = DDIMI.second;
1199 
1200     // If debug info is to be dropped, run it through final checks to see
1201     // whether it can be salvaged.
1202     for (auto &DDI : DDIV)
1203       if (isMatchingDbgValue(DDI))
1204         salvageUnresolvedDbgValue(DDI);
1205 
1206     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1207   }
1208 }
1209 
1210 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1211 // generate the debug data structures now that we've seen its definition.
1212 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1213                                                    SDValue Val) {
1214   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1215   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1216     return;
1217 
1218   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1219   for (auto &DDI : DDIV) {
1220     const DbgValueInst *DI = DDI.getDI();
1221     assert(DI && "Ill-formed DanglingDebugInfo");
1222     DebugLoc dl = DDI.getdl();
1223     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1224     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1225     DILocalVariable *Variable = DI->getVariable();
1226     DIExpression *Expr = DI->getExpression();
1227     assert(Variable->isValidLocationForIntrinsic(dl) &&
1228            "Expected inlined-at fields to agree");
1229     SDDbgValue *SDV;
1230     if (Val.getNode()) {
1231       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1232       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1233       // we couldn't resolve it directly when examining the DbgValue intrinsic
1234       // in the first place we should not be more successful here). Unless we
1235       // have some test case that prove this to be correct we should avoid
1236       // calling EmitFuncArgumentDbgValue here.
1237       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1238         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1239                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1240         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1241         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1242         // inserted after the definition of Val when emitting the instructions
1243         // after ISel. An alternative could be to teach
1244         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1245         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1246                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1247                    << ValSDNodeOrder << "\n");
1248         SDV = getDbgValue(Val, Variable, Expr, dl,
1249                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1250         DAG.AddDbgValue(SDV, Val.getNode(), false);
1251       } else
1252         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1253                           << "in EmitFuncArgumentDbgValue\n");
1254     } else {
1255       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1256       auto Undef =
1257           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1258       auto SDV =
1259           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1260       DAG.AddDbgValue(SDV, nullptr, false);
1261     }
1262   }
1263   DDIV.clear();
1264 }
1265 
1266 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1267   Value *V = DDI.getDI()->getValue();
1268   DILocalVariable *Var = DDI.getDI()->getVariable();
1269   DIExpression *Expr = DDI.getDI()->getExpression();
1270   DebugLoc DL = DDI.getdl();
1271   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1272   unsigned SDOrder = DDI.getSDNodeOrder();
1273 
1274   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1275   // that DW_OP_stack_value is desired.
1276   assert(isa<DbgValueInst>(DDI.getDI()));
1277   bool StackValue = true;
1278 
1279   // Can this Value can be encoded without any further work?
1280   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1281     return;
1282 
1283   // Attempt to salvage back through as many instructions as possible. Bail if
1284   // a non-instruction is seen, such as a constant expression or global
1285   // variable. FIXME: Further work could recover those too.
1286   while (isa<Instruction>(V)) {
1287     Instruction &VAsInst = *cast<Instruction>(V);
1288     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1289 
1290     // If we cannot salvage any further, and haven't yet found a suitable debug
1291     // expression, bail out.
1292     if (!NewExpr)
1293       break;
1294 
1295     // New value and expr now represent this debuginfo.
1296     V = VAsInst.getOperand(0);
1297     Expr = NewExpr;
1298 
1299     // Some kind of simplification occurred: check whether the operand of the
1300     // salvaged debug expression can be encoded in this DAG.
1301     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1302       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1303                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1304       return;
1305     }
1306   }
1307 
1308   // This was the final opportunity to salvage this debug information, and it
1309   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1310   // any earlier variable location.
1311   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1312   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1313   DAG.AddDbgValue(SDV, nullptr, false);
1314 
1315   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1316                     << "\n");
1317   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1318                     << "\n");
1319 }
1320 
1321 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1322                                            DIExpression *Expr, DebugLoc dl,
1323                                            DebugLoc InstDL, unsigned Order) {
1324   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1325   SDDbgValue *SDV;
1326   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1327       isa<ConstantPointerNull>(V)) {
1328     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1329     DAG.AddDbgValue(SDV, nullptr, false);
1330     return true;
1331   }
1332 
1333   // If the Value is a frame index, we can create a FrameIndex debug value
1334   // without relying on the DAG at all.
1335   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1336     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1337     if (SI != FuncInfo.StaticAllocaMap.end()) {
1338       auto SDV =
1339           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1340                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1341       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1342       // is still available even if the SDNode gets optimized out.
1343       DAG.AddDbgValue(SDV, nullptr, false);
1344       return true;
1345     }
1346   }
1347 
1348   // Do not use getValue() in here; we don't want to generate code at
1349   // this point if it hasn't been done yet.
1350   SDValue N = NodeMap[V];
1351   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1352     N = UnusedArgNodeMap[V];
1353   if (N.getNode()) {
1354     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1355       return true;
1356     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1357     DAG.AddDbgValue(SDV, N.getNode(), false);
1358     return true;
1359   }
1360 
1361   // Special rules apply for the first dbg.values of parameter variables in a
1362   // function. Identify them by the fact they reference Argument Values, that
1363   // they're parameters, and they are parameters of the current function. We
1364   // need to let them dangle until they get an SDNode.
1365   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1366                        !InstDL.getInlinedAt();
1367   if (!IsParamOfFunc) {
1368     // The value is not used in this block yet (or it would have an SDNode).
1369     // We still want the value to appear for the user if possible -- if it has
1370     // an associated VReg, we can refer to that instead.
1371     auto VMI = FuncInfo.ValueMap.find(V);
1372     if (VMI != FuncInfo.ValueMap.end()) {
1373       unsigned Reg = VMI->second;
1374       // If this is a PHI node, it may be split up into several MI PHI nodes
1375       // (in FunctionLoweringInfo::set).
1376       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1377                        V->getType(), None);
1378       if (RFV.occupiesMultipleRegs()) {
1379         unsigned Offset = 0;
1380         unsigned BitsToDescribe = 0;
1381         if (auto VarSize = Var->getSizeInBits())
1382           BitsToDescribe = *VarSize;
1383         if (auto Fragment = Expr->getFragmentInfo())
1384           BitsToDescribe = Fragment->SizeInBits;
1385         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1386           unsigned RegisterSize = RegAndSize.second;
1387           // Bail out if all bits are described already.
1388           if (Offset >= BitsToDescribe)
1389             break;
1390           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1391               ? BitsToDescribe - Offset
1392               : RegisterSize;
1393           auto FragmentExpr = DIExpression::createFragmentExpression(
1394               Expr, Offset, FragmentSize);
1395           if (!FragmentExpr)
1396               continue;
1397           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1398                                     false, dl, SDNodeOrder);
1399           DAG.AddDbgValue(SDV, nullptr, false);
1400           Offset += RegisterSize;
1401         }
1402       } else {
1403         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1404         DAG.AddDbgValue(SDV, nullptr, false);
1405       }
1406       return true;
1407     }
1408   }
1409 
1410   return false;
1411 }
1412 
1413 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1414   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1415   for (auto &Pair : DanglingDebugInfoMap)
1416     for (auto &DDI : Pair.second)
1417       salvageUnresolvedDbgValue(DDI);
1418   clearDanglingDebugInfo();
1419 }
1420 
1421 /// getCopyFromRegs - If there was virtual register allocated for the value V
1422 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1423 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1424   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1425   SDValue Result;
1426 
1427   if (It != FuncInfo.ValueMap.end()) {
1428     Register InReg = It->second;
1429 
1430     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1431                      DAG.getDataLayout(), InReg, Ty,
1432                      None); // This is not an ABI copy.
1433     SDValue Chain = DAG.getEntryNode();
1434     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1435                                  V);
1436     resolveDanglingDebugInfo(V, Result);
1437   }
1438 
1439   return Result;
1440 }
1441 
1442 /// getValue - Return an SDValue for the given Value.
1443 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1444   // If we already have an SDValue for this value, use it. It's important
1445   // to do this first, so that we don't create a CopyFromReg if we already
1446   // have a regular SDValue.
1447   SDValue &N = NodeMap[V];
1448   if (N.getNode()) return N;
1449 
1450   // If there's a virtual register allocated and initialized for this
1451   // value, use it.
1452   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1453     return copyFromReg;
1454 
1455   // Otherwise create a new SDValue and remember it.
1456   SDValue Val = getValueImpl(V);
1457   NodeMap[V] = Val;
1458   resolveDanglingDebugInfo(V, Val);
1459   return Val;
1460 }
1461 
1462 /// getNonRegisterValue - Return an SDValue for the given Value, but
1463 /// don't look in FuncInfo.ValueMap for a virtual register.
1464 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1465   // If we already have an SDValue for this value, use it.
1466   SDValue &N = NodeMap[V];
1467   if (N.getNode()) {
1468     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1469       // Remove the debug location from the node as the node is about to be used
1470       // in a location which may differ from the original debug location.  This
1471       // is relevant to Constant and ConstantFP nodes because they can appear
1472       // as constant expressions inside PHI nodes.
1473       N->setDebugLoc(DebugLoc());
1474     }
1475     return N;
1476   }
1477 
1478   // Otherwise create a new SDValue and remember it.
1479   SDValue Val = getValueImpl(V);
1480   NodeMap[V] = Val;
1481   resolveDanglingDebugInfo(V, Val);
1482   return Val;
1483 }
1484 
1485 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1486 /// Create an SDValue for the given value.
1487 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1489 
1490   if (const Constant *C = dyn_cast<Constant>(V)) {
1491     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1492 
1493     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1494       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1495 
1496     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1497       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1498 
1499     if (isa<ConstantPointerNull>(C)) {
1500       unsigned AS = V->getType()->getPointerAddressSpace();
1501       return DAG.getConstant(0, getCurSDLoc(),
1502                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1503     }
1504 
1505     if (match(C, m_VScale(DAG.getDataLayout())))
1506       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1507 
1508     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1509       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1510 
1511     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1512       return DAG.getUNDEF(VT);
1513 
1514     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1515       visit(CE->getOpcode(), *CE);
1516       SDValue N1 = NodeMap[V];
1517       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1518       return N1;
1519     }
1520 
1521     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1522       SmallVector<SDValue, 4> Constants;
1523       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1524            OI != OE; ++OI) {
1525         SDNode *Val = getValue(*OI).getNode();
1526         // If the operand is an empty aggregate, there are no values.
1527         if (!Val) continue;
1528         // Add each leaf value from the operand to the Constants list
1529         // to form a flattened list of all the values.
1530         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1531           Constants.push_back(SDValue(Val, i));
1532       }
1533 
1534       return DAG.getMergeValues(Constants, getCurSDLoc());
1535     }
1536 
1537     if (const ConstantDataSequential *CDS =
1538           dyn_cast<ConstantDataSequential>(C)) {
1539       SmallVector<SDValue, 4> Ops;
1540       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1541         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1542         // Add each leaf value from the operand to the Constants list
1543         // to form a flattened list of all the values.
1544         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1545           Ops.push_back(SDValue(Val, i));
1546       }
1547 
1548       if (isa<ArrayType>(CDS->getType()))
1549         return DAG.getMergeValues(Ops, getCurSDLoc());
1550       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1551     }
1552 
1553     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1554       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1555              "Unknown struct or array constant!");
1556 
1557       SmallVector<EVT, 4> ValueVTs;
1558       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1559       unsigned NumElts = ValueVTs.size();
1560       if (NumElts == 0)
1561         return SDValue(); // empty struct
1562       SmallVector<SDValue, 4> Constants(NumElts);
1563       for (unsigned i = 0; i != NumElts; ++i) {
1564         EVT EltVT = ValueVTs[i];
1565         if (isa<UndefValue>(C))
1566           Constants[i] = DAG.getUNDEF(EltVT);
1567         else if (EltVT.isFloatingPoint())
1568           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1569         else
1570           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1571       }
1572 
1573       return DAG.getMergeValues(Constants, getCurSDLoc());
1574     }
1575 
1576     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1577       return DAG.getBlockAddress(BA, VT);
1578 
1579     VectorType *VecTy = cast<VectorType>(V->getType());
1580 
1581     // Now that we know the number and type of the elements, get that number of
1582     // elements into the Ops array based on what kind of constant it is.
1583     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1584       SmallVector<SDValue, 16> Ops;
1585       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1586       for (unsigned i = 0; i != NumElements; ++i)
1587         Ops.push_back(getValue(CV->getOperand(i)));
1588 
1589       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1590     } else if (isa<ConstantAggregateZero>(C)) {
1591       EVT EltVT =
1592           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1593 
1594       SDValue Op;
1595       if (EltVT.isFloatingPoint())
1596         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1597       else
1598         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1599 
1600       if (isa<ScalableVectorType>(VecTy))
1601         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1602       else {
1603         SmallVector<SDValue, 16> Ops;
1604         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1605         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1606       }
1607     }
1608     llvm_unreachable("Unknown vector constant");
1609   }
1610 
1611   // If this is a static alloca, generate it as the frameindex instead of
1612   // computation.
1613   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1614     DenseMap<const AllocaInst*, int>::iterator SI =
1615       FuncInfo.StaticAllocaMap.find(AI);
1616     if (SI != FuncInfo.StaticAllocaMap.end())
1617       return DAG.getFrameIndex(SI->second,
1618                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1619   }
1620 
1621   // If this is an instruction which fast-isel has deferred, select it now.
1622   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1623     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1624 
1625     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1626                      Inst->getType(), getABIRegCopyCC(V));
1627     SDValue Chain = DAG.getEntryNode();
1628     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1629   }
1630 
1631   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1632     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1633   }
1634   llvm_unreachable("Can't get register for value!");
1635 }
1636 
1637 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1638   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1639   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1640   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1641   bool IsSEH = isAsynchronousEHPersonality(Pers);
1642   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1643   if (!IsSEH)
1644     CatchPadMBB->setIsEHScopeEntry();
1645   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1646   if (IsMSVCCXX || IsCoreCLR)
1647     CatchPadMBB->setIsEHFuncletEntry();
1648 }
1649 
1650 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1651   // Update machine-CFG edge.
1652   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1653   FuncInfo.MBB->addSuccessor(TargetMBB);
1654 
1655   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1656   bool IsSEH = isAsynchronousEHPersonality(Pers);
1657   if (IsSEH) {
1658     // If this is not a fall-through branch or optimizations are switched off,
1659     // emit the branch.
1660     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1661         TM.getOptLevel() == CodeGenOpt::None)
1662       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1663                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1664     return;
1665   }
1666 
1667   // Figure out the funclet membership for the catchret's successor.
1668   // This will be used by the FuncletLayout pass to determine how to order the
1669   // BB's.
1670   // A 'catchret' returns to the outer scope's color.
1671   Value *ParentPad = I.getCatchSwitchParentPad();
1672   const BasicBlock *SuccessorColor;
1673   if (isa<ConstantTokenNone>(ParentPad))
1674     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1675   else
1676     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1677   assert(SuccessorColor && "No parent funclet for catchret!");
1678   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1679   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1680 
1681   // Create the terminator node.
1682   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1683                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1684                             DAG.getBasicBlock(SuccessorColorMBB));
1685   DAG.setRoot(Ret);
1686 }
1687 
1688 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1689   // Don't emit any special code for the cleanuppad instruction. It just marks
1690   // the start of an EH scope/funclet.
1691   FuncInfo.MBB->setIsEHScopeEntry();
1692   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1693   if (Pers != EHPersonality::Wasm_CXX) {
1694     FuncInfo.MBB->setIsEHFuncletEntry();
1695     FuncInfo.MBB->setIsCleanupFuncletEntry();
1696   }
1697 }
1698 
1699 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1700 // the control flow always stops at the single catch pad, as it does for a
1701 // cleanup pad. In case the exception caught is not of the types the catch pad
1702 // catches, it will be rethrown by a rethrow.
1703 static void findWasmUnwindDestinations(
1704     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1705     BranchProbability Prob,
1706     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1707         &UnwindDests) {
1708   while (EHPadBB) {
1709     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1710     if (isa<CleanupPadInst>(Pad)) {
1711       // Stop on cleanup pads.
1712       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1713       UnwindDests.back().first->setIsEHScopeEntry();
1714       break;
1715     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1716       // Add the catchpad handlers to the possible destinations. We don't
1717       // continue to the unwind destination of the catchswitch for wasm.
1718       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1719         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1720         UnwindDests.back().first->setIsEHScopeEntry();
1721       }
1722       break;
1723     } else {
1724       continue;
1725     }
1726   }
1727 }
1728 
1729 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1730 /// many places it could ultimately go. In the IR, we have a single unwind
1731 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1732 /// This function skips over imaginary basic blocks that hold catchswitch
1733 /// instructions, and finds all the "real" machine
1734 /// basic block destinations. As those destinations may not be successors of
1735 /// EHPadBB, here we also calculate the edge probability to those destinations.
1736 /// The passed-in Prob is the edge probability to EHPadBB.
1737 static void findUnwindDestinations(
1738     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1739     BranchProbability Prob,
1740     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1741         &UnwindDests) {
1742   EHPersonality Personality =
1743     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1744   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1745   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1746   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1747   bool IsSEH = isAsynchronousEHPersonality(Personality);
1748 
1749   if (IsWasmCXX) {
1750     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1751     assert(UnwindDests.size() <= 1 &&
1752            "There should be at most one unwind destination for wasm");
1753     return;
1754   }
1755 
1756   while (EHPadBB) {
1757     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1758     BasicBlock *NewEHPadBB = nullptr;
1759     if (isa<LandingPadInst>(Pad)) {
1760       // Stop on landingpads. They are not funclets.
1761       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1762       break;
1763     } else if (isa<CleanupPadInst>(Pad)) {
1764       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1765       // personalities.
1766       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1767       UnwindDests.back().first->setIsEHScopeEntry();
1768       UnwindDests.back().first->setIsEHFuncletEntry();
1769       break;
1770     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1771       // Add the catchpad handlers to the possible destinations.
1772       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1773         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1774         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1775         if (IsMSVCCXX || IsCoreCLR)
1776           UnwindDests.back().first->setIsEHFuncletEntry();
1777         if (!IsSEH)
1778           UnwindDests.back().first->setIsEHScopeEntry();
1779       }
1780       NewEHPadBB = CatchSwitch->getUnwindDest();
1781     } else {
1782       continue;
1783     }
1784 
1785     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1786     if (BPI && NewEHPadBB)
1787       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1788     EHPadBB = NewEHPadBB;
1789   }
1790 }
1791 
1792 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1793   // Update successor info.
1794   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1795   auto UnwindDest = I.getUnwindDest();
1796   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1797   BranchProbability UnwindDestProb =
1798       (BPI && UnwindDest)
1799           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1800           : BranchProbability::getZero();
1801   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1802   for (auto &UnwindDest : UnwindDests) {
1803     UnwindDest.first->setIsEHPad();
1804     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1805   }
1806   FuncInfo.MBB->normalizeSuccProbs();
1807 
1808   // Create the terminator node.
1809   SDValue Ret =
1810       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1811   DAG.setRoot(Ret);
1812 }
1813 
1814 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1815   report_fatal_error("visitCatchSwitch not yet implemented!");
1816 }
1817 
1818 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1820   auto &DL = DAG.getDataLayout();
1821   SDValue Chain = getControlRoot();
1822   SmallVector<ISD::OutputArg, 8> Outs;
1823   SmallVector<SDValue, 8> OutVals;
1824 
1825   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1826   // lower
1827   //
1828   //   %val = call <ty> @llvm.experimental.deoptimize()
1829   //   ret <ty> %val
1830   //
1831   // differently.
1832   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1833     LowerDeoptimizingReturn();
1834     return;
1835   }
1836 
1837   if (!FuncInfo.CanLowerReturn) {
1838     unsigned DemoteReg = FuncInfo.DemoteRegister;
1839     const Function *F = I.getParent()->getParent();
1840 
1841     // Emit a store of the return value through the virtual register.
1842     // Leave Outs empty so that LowerReturn won't try to load return
1843     // registers the usual way.
1844     SmallVector<EVT, 1> PtrValueVTs;
1845     ComputeValueVTs(TLI, DL,
1846                     F->getReturnType()->getPointerTo(
1847                         DAG.getDataLayout().getAllocaAddrSpace()),
1848                     PtrValueVTs);
1849 
1850     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1851                                         DemoteReg, PtrValueVTs[0]);
1852     SDValue RetOp = getValue(I.getOperand(0));
1853 
1854     SmallVector<EVT, 4> ValueVTs, MemVTs;
1855     SmallVector<uint64_t, 4> Offsets;
1856     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1857                     &Offsets);
1858     unsigned NumValues = ValueVTs.size();
1859 
1860     SmallVector<SDValue, 4> Chains(NumValues);
1861     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1862     for (unsigned i = 0; i != NumValues; ++i) {
1863       // An aggregate return value cannot wrap around the address space, so
1864       // offsets to its parts don't wrap either.
1865       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1866 
1867       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1868       if (MemVTs[i] != ValueVTs[i])
1869         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1870       Chains[i] = DAG.getStore(
1871           Chain, getCurSDLoc(), Val,
1872           // FIXME: better loc info would be nice.
1873           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1874           commonAlignment(BaseAlign, Offsets[i]));
1875     }
1876 
1877     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1878                         MVT::Other, Chains);
1879   } else if (I.getNumOperands() != 0) {
1880     SmallVector<EVT, 4> ValueVTs;
1881     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1882     unsigned NumValues = ValueVTs.size();
1883     if (NumValues) {
1884       SDValue RetOp = getValue(I.getOperand(0));
1885 
1886       const Function *F = I.getParent()->getParent();
1887 
1888       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1889           I.getOperand(0)->getType(), F->getCallingConv(),
1890           /*IsVarArg*/ false);
1891 
1892       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1893       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1894                                           Attribute::SExt))
1895         ExtendKind = ISD::SIGN_EXTEND;
1896       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1897                                                Attribute::ZExt))
1898         ExtendKind = ISD::ZERO_EXTEND;
1899 
1900       LLVMContext &Context = F->getContext();
1901       bool RetInReg = F->getAttributes().hasAttribute(
1902           AttributeList::ReturnIndex, Attribute::InReg);
1903 
1904       for (unsigned j = 0; j != NumValues; ++j) {
1905         EVT VT = ValueVTs[j];
1906 
1907         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1908           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1909 
1910         CallingConv::ID CC = F->getCallingConv();
1911 
1912         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1913         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1914         SmallVector<SDValue, 4> Parts(NumParts);
1915         getCopyToParts(DAG, getCurSDLoc(),
1916                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1917                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1918 
1919         // 'inreg' on function refers to return value
1920         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1921         if (RetInReg)
1922           Flags.setInReg();
1923 
1924         if (I.getOperand(0)->getType()->isPointerTy()) {
1925           Flags.setPointer();
1926           Flags.setPointerAddrSpace(
1927               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1928         }
1929 
1930         if (NeedsRegBlock) {
1931           Flags.setInConsecutiveRegs();
1932           if (j == NumValues - 1)
1933             Flags.setInConsecutiveRegsLast();
1934         }
1935 
1936         // Propagate extension type if any
1937         if (ExtendKind == ISD::SIGN_EXTEND)
1938           Flags.setSExt();
1939         else if (ExtendKind == ISD::ZERO_EXTEND)
1940           Flags.setZExt();
1941 
1942         for (unsigned i = 0; i < NumParts; ++i) {
1943           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1944                                         VT, /*isfixed=*/true, 0, 0));
1945           OutVals.push_back(Parts[i]);
1946         }
1947       }
1948     }
1949   }
1950 
1951   // Push in swifterror virtual register as the last element of Outs. This makes
1952   // sure swifterror virtual register will be returned in the swifterror
1953   // physical register.
1954   const Function *F = I.getParent()->getParent();
1955   if (TLI.supportSwiftError() &&
1956       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1957     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1958     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1959     Flags.setSwiftError();
1960     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1961                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1962                                   true /*isfixed*/, 1 /*origidx*/,
1963                                   0 /*partOffs*/));
1964     // Create SDNode for the swifterror virtual register.
1965     OutVals.push_back(
1966         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1967                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1968                         EVT(TLI.getPointerTy(DL))));
1969   }
1970 
1971   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1972   CallingConv::ID CallConv =
1973     DAG.getMachineFunction().getFunction().getCallingConv();
1974   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1975       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1976 
1977   // Verify that the target's LowerReturn behaved as expected.
1978   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1979          "LowerReturn didn't return a valid chain!");
1980 
1981   // Update the DAG with the new chain value resulting from return lowering.
1982   DAG.setRoot(Chain);
1983 }
1984 
1985 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1986 /// created for it, emit nodes to copy the value into the virtual
1987 /// registers.
1988 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1989   // Skip empty types
1990   if (V->getType()->isEmptyTy())
1991     return;
1992 
1993   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1994   if (VMI != FuncInfo.ValueMap.end()) {
1995     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1996     CopyValueToVirtualRegister(V, VMI->second);
1997   }
1998 }
1999 
2000 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2001 /// the current basic block, add it to ValueMap now so that we'll get a
2002 /// CopyTo/FromReg.
2003 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2004   // No need to export constants.
2005   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2006 
2007   // Already exported?
2008   if (FuncInfo.isExportedInst(V)) return;
2009 
2010   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2011   CopyValueToVirtualRegister(V, Reg);
2012 }
2013 
2014 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2015                                                      const BasicBlock *FromBB) {
2016   // The operands of the setcc have to be in this block.  We don't know
2017   // how to export them from some other block.
2018   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2019     // Can export from current BB.
2020     if (VI->getParent() == FromBB)
2021       return true;
2022 
2023     // Is already exported, noop.
2024     return FuncInfo.isExportedInst(V);
2025   }
2026 
2027   // If this is an argument, we can export it if the BB is the entry block or
2028   // if it is already exported.
2029   if (isa<Argument>(V)) {
2030     if (FromBB == &FromBB->getParent()->getEntryBlock())
2031       return true;
2032 
2033     // Otherwise, can only export this if it is already exported.
2034     return FuncInfo.isExportedInst(V);
2035   }
2036 
2037   // Otherwise, constants can always be exported.
2038   return true;
2039 }
2040 
2041 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2042 BranchProbability
2043 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2044                                         const MachineBasicBlock *Dst) const {
2045   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2046   const BasicBlock *SrcBB = Src->getBasicBlock();
2047   const BasicBlock *DstBB = Dst->getBasicBlock();
2048   if (!BPI) {
2049     // If BPI is not available, set the default probability as 1 / N, where N is
2050     // the number of successors.
2051     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2052     return BranchProbability(1, SuccSize);
2053   }
2054   return BPI->getEdgeProbability(SrcBB, DstBB);
2055 }
2056 
2057 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2058                                                MachineBasicBlock *Dst,
2059                                                BranchProbability Prob) {
2060   if (!FuncInfo.BPI)
2061     Src->addSuccessorWithoutProb(Dst);
2062   else {
2063     if (Prob.isUnknown())
2064       Prob = getEdgeProbability(Src, Dst);
2065     Src->addSuccessor(Dst, Prob);
2066   }
2067 }
2068 
2069 static bool InBlock(const Value *V, const BasicBlock *BB) {
2070   if (const Instruction *I = dyn_cast<Instruction>(V))
2071     return I->getParent() == BB;
2072   return true;
2073 }
2074 
2075 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2076 /// This function emits a branch and is used at the leaves of an OR or an
2077 /// AND operator tree.
2078 void
2079 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2080                                                   MachineBasicBlock *TBB,
2081                                                   MachineBasicBlock *FBB,
2082                                                   MachineBasicBlock *CurBB,
2083                                                   MachineBasicBlock *SwitchBB,
2084                                                   BranchProbability TProb,
2085                                                   BranchProbability FProb,
2086                                                   bool InvertCond) {
2087   const BasicBlock *BB = CurBB->getBasicBlock();
2088 
2089   // If the leaf of the tree is a comparison, merge the condition into
2090   // the caseblock.
2091   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2092     // The operands of the cmp have to be in this block.  We don't know
2093     // how to export them from some other block.  If this is the first block
2094     // of the sequence, no exporting is needed.
2095     if (CurBB == SwitchBB ||
2096         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2097          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2098       ISD::CondCode Condition;
2099       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2100         ICmpInst::Predicate Pred =
2101             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2102         Condition = getICmpCondCode(Pred);
2103       } else {
2104         const FCmpInst *FC = cast<FCmpInst>(Cond);
2105         FCmpInst::Predicate Pred =
2106             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2107         Condition = getFCmpCondCode(Pred);
2108         if (TM.Options.NoNaNsFPMath)
2109           Condition = getFCmpCodeWithoutNaN(Condition);
2110       }
2111 
2112       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2113                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2114       SL->SwitchCases.push_back(CB);
2115       return;
2116     }
2117   }
2118 
2119   // Create a CaseBlock record representing this branch.
2120   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2121   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2122                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2123   SL->SwitchCases.push_back(CB);
2124 }
2125 
2126 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2127                                                MachineBasicBlock *TBB,
2128                                                MachineBasicBlock *FBB,
2129                                                MachineBasicBlock *CurBB,
2130                                                MachineBasicBlock *SwitchBB,
2131                                                Instruction::BinaryOps Opc,
2132                                                BranchProbability TProb,
2133                                                BranchProbability FProb,
2134                                                bool InvertCond) {
2135   // Skip over not part of the tree and remember to invert op and operands at
2136   // next level.
2137   Value *NotCond;
2138   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2139       InBlock(NotCond, CurBB->getBasicBlock())) {
2140     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2141                          !InvertCond);
2142     return;
2143   }
2144 
2145   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2146   // Compute the effective opcode for Cond, taking into account whether it needs
2147   // to be inverted, e.g.
2148   //   and (not (or A, B)), C
2149   // gets lowered as
2150   //   and (and (not A, not B), C)
2151   unsigned BOpc = 0;
2152   if (BOp) {
2153     BOpc = BOp->getOpcode();
2154     if (InvertCond) {
2155       if (BOpc == Instruction::And)
2156         BOpc = Instruction::Or;
2157       else if (BOpc == Instruction::Or)
2158         BOpc = Instruction::And;
2159     }
2160   }
2161 
2162   // If this node is not part of the or/and tree, emit it as a branch.
2163   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2164       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2165       BOp->getParent() != CurBB->getBasicBlock() ||
2166       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2167       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2168     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2169                                  TProb, FProb, InvertCond);
2170     return;
2171   }
2172 
2173   //  Create TmpBB after CurBB.
2174   MachineFunction::iterator BBI(CurBB);
2175   MachineFunction &MF = DAG.getMachineFunction();
2176   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2177   CurBB->getParent()->insert(++BBI, TmpBB);
2178 
2179   if (Opc == Instruction::Or) {
2180     // Codegen X | Y as:
2181     // BB1:
2182     //   jmp_if_X TBB
2183     //   jmp TmpBB
2184     // TmpBB:
2185     //   jmp_if_Y TBB
2186     //   jmp FBB
2187     //
2188 
2189     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2190     // The requirement is that
2191     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2192     //     = TrueProb for original BB.
2193     // Assuming the original probabilities are A and B, one choice is to set
2194     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2195     // A/(1+B) and 2B/(1+B). This choice assumes that
2196     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2197     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2198     // TmpBB, but the math is more complicated.
2199 
2200     auto NewTrueProb = TProb / 2;
2201     auto NewFalseProb = TProb / 2 + FProb;
2202     // Emit the LHS condition.
2203     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2204                          NewTrueProb, NewFalseProb, InvertCond);
2205 
2206     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2207     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2208     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2209     // Emit the RHS condition into TmpBB.
2210     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2211                          Probs[0], Probs[1], InvertCond);
2212   } else {
2213     assert(Opc == Instruction::And && "Unknown merge op!");
2214     // Codegen X & Y as:
2215     // BB1:
2216     //   jmp_if_X TmpBB
2217     //   jmp FBB
2218     // TmpBB:
2219     //   jmp_if_Y TBB
2220     //   jmp FBB
2221     //
2222     //  This requires creation of TmpBB after CurBB.
2223 
2224     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2225     // The requirement is that
2226     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2227     //     = FalseProb for original BB.
2228     // Assuming the original probabilities are A and B, one choice is to set
2229     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2230     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2231     // TrueProb for BB1 * FalseProb for TmpBB.
2232 
2233     auto NewTrueProb = TProb + FProb / 2;
2234     auto NewFalseProb = FProb / 2;
2235     // Emit the LHS condition.
2236     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2237                          NewTrueProb, NewFalseProb, InvertCond);
2238 
2239     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2240     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2241     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2242     // Emit the RHS condition into TmpBB.
2243     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2244                          Probs[0], Probs[1], InvertCond);
2245   }
2246 }
2247 
2248 /// If the set of cases should be emitted as a series of branches, return true.
2249 /// If we should emit this as a bunch of and/or'd together conditions, return
2250 /// false.
2251 bool
2252 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2253   if (Cases.size() != 2) return true;
2254 
2255   // If this is two comparisons of the same values or'd or and'd together, they
2256   // will get folded into a single comparison, so don't emit two blocks.
2257   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2258        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2259       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2260        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2261     return false;
2262   }
2263 
2264   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2265   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2266   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2267       Cases[0].CC == Cases[1].CC &&
2268       isa<Constant>(Cases[0].CmpRHS) &&
2269       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2270     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2271       return false;
2272     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2273       return false;
2274   }
2275 
2276   return true;
2277 }
2278 
2279 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2280   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2281 
2282   // Update machine-CFG edges.
2283   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2284 
2285   if (I.isUnconditional()) {
2286     // Update machine-CFG edges.
2287     BrMBB->addSuccessor(Succ0MBB);
2288 
2289     // If this is not a fall-through branch or optimizations are switched off,
2290     // emit the branch.
2291     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2292       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2293                               MVT::Other, getControlRoot(),
2294                               DAG.getBasicBlock(Succ0MBB)));
2295 
2296     return;
2297   }
2298 
2299   // If this condition is one of the special cases we handle, do special stuff
2300   // now.
2301   const Value *CondVal = I.getCondition();
2302   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2303 
2304   // If this is a series of conditions that are or'd or and'd together, emit
2305   // this as a sequence of branches instead of setcc's with and/or operations.
2306   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2307   // unpredictable branches, and vector extracts because those jumps are likely
2308   // expensive for any target), this should improve performance.
2309   // For example, instead of something like:
2310   //     cmp A, B
2311   //     C = seteq
2312   //     cmp D, E
2313   //     F = setle
2314   //     or C, F
2315   //     jnz foo
2316   // Emit:
2317   //     cmp A, B
2318   //     je foo
2319   //     cmp D, E
2320   //     jle foo
2321   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2322     Instruction::BinaryOps Opcode = BOp->getOpcode();
2323     Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1);
2324     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2325         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2326         (Opcode == Instruction::And || Opcode == Instruction::Or) &&
2327         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2328           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2329       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2330                            Opcode,
2331                            getEdgeProbability(BrMBB, Succ0MBB),
2332                            getEdgeProbability(BrMBB, Succ1MBB),
2333                            /*InvertCond=*/false);
2334       // If the compares in later blocks need to use values not currently
2335       // exported from this block, export them now.  This block should always
2336       // be the first entry.
2337       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2338 
2339       // Allow some cases to be rejected.
2340       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2341         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2342           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2343           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2344         }
2345 
2346         // Emit the branch for this block.
2347         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2348         SL->SwitchCases.erase(SL->SwitchCases.begin());
2349         return;
2350       }
2351 
2352       // Okay, we decided not to do this, remove any inserted MBB's and clear
2353       // SwitchCases.
2354       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2355         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2356 
2357       SL->SwitchCases.clear();
2358     }
2359   }
2360 
2361   // Create a CaseBlock record representing this branch.
2362   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2363                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2364 
2365   // Use visitSwitchCase to actually insert the fast branch sequence for this
2366   // cond branch.
2367   visitSwitchCase(CB, BrMBB);
2368 }
2369 
2370 /// visitSwitchCase - Emits the necessary code to represent a single node in
2371 /// the binary search tree resulting from lowering a switch instruction.
2372 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2373                                           MachineBasicBlock *SwitchBB) {
2374   SDValue Cond;
2375   SDValue CondLHS = getValue(CB.CmpLHS);
2376   SDLoc dl = CB.DL;
2377 
2378   if (CB.CC == ISD::SETTRUE) {
2379     // Branch or fall through to TrueBB.
2380     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2381     SwitchBB->normalizeSuccProbs();
2382     if (CB.TrueBB != NextBlock(SwitchBB)) {
2383       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2384                               DAG.getBasicBlock(CB.TrueBB)));
2385     }
2386     return;
2387   }
2388 
2389   auto &TLI = DAG.getTargetLoweringInfo();
2390   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2391 
2392   // Build the setcc now.
2393   if (!CB.CmpMHS) {
2394     // Fold "(X == true)" to X and "(X == false)" to !X to
2395     // handle common cases produced by branch lowering.
2396     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2397         CB.CC == ISD::SETEQ)
2398       Cond = CondLHS;
2399     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2400              CB.CC == ISD::SETEQ) {
2401       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2402       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2403     } else {
2404       SDValue CondRHS = getValue(CB.CmpRHS);
2405 
2406       // If a pointer's DAG type is larger than its memory type then the DAG
2407       // values are zero-extended. This breaks signed comparisons so truncate
2408       // back to the underlying type before doing the compare.
2409       if (CondLHS.getValueType() != MemVT) {
2410         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2411         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2412       }
2413       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2414     }
2415   } else {
2416     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2417 
2418     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2419     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2420 
2421     SDValue CmpOp = getValue(CB.CmpMHS);
2422     EVT VT = CmpOp.getValueType();
2423 
2424     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2425       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2426                           ISD::SETLE);
2427     } else {
2428       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2429                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2430       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2431                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2432     }
2433   }
2434 
2435   // Update successor info
2436   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2437   // TrueBB and FalseBB are always different unless the incoming IR is
2438   // degenerate. This only happens when running llc on weird IR.
2439   if (CB.TrueBB != CB.FalseBB)
2440     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2441   SwitchBB->normalizeSuccProbs();
2442 
2443   // If the lhs block is the next block, invert the condition so that we can
2444   // fall through to the lhs instead of the rhs block.
2445   if (CB.TrueBB == NextBlock(SwitchBB)) {
2446     std::swap(CB.TrueBB, CB.FalseBB);
2447     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2448     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2449   }
2450 
2451   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2452                                MVT::Other, getControlRoot(), Cond,
2453                                DAG.getBasicBlock(CB.TrueBB));
2454 
2455   // Insert the false branch. Do this even if it's a fall through branch,
2456   // this makes it easier to do DAG optimizations which require inverting
2457   // the branch condition.
2458   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2459                        DAG.getBasicBlock(CB.FalseBB));
2460 
2461   DAG.setRoot(BrCond);
2462 }
2463 
2464 /// visitJumpTable - Emit JumpTable node in the current MBB
2465 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2466   // Emit the code for the jump table
2467   assert(JT.Reg != -1U && "Should lower JT Header first!");
2468   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2469   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2470                                      JT.Reg, PTy);
2471   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2472   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2473                                     MVT::Other, Index.getValue(1),
2474                                     Table, Index);
2475   DAG.setRoot(BrJumpTable);
2476 }
2477 
2478 /// visitJumpTableHeader - This function emits necessary code to produce index
2479 /// in the JumpTable from switch case.
2480 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2481                                                JumpTableHeader &JTH,
2482                                                MachineBasicBlock *SwitchBB) {
2483   SDLoc dl = getCurSDLoc();
2484 
2485   // Subtract the lowest switch case value from the value being switched on.
2486   SDValue SwitchOp = getValue(JTH.SValue);
2487   EVT VT = SwitchOp.getValueType();
2488   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2489                             DAG.getConstant(JTH.First, dl, VT));
2490 
2491   // The SDNode we just created, which holds the value being switched on minus
2492   // the smallest case value, needs to be copied to a virtual register so it
2493   // can be used as an index into the jump table in a subsequent basic block.
2494   // This value may be smaller or larger than the target's pointer type, and
2495   // therefore require extension or truncating.
2496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2497   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2498 
2499   unsigned JumpTableReg =
2500       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2501   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2502                                     JumpTableReg, SwitchOp);
2503   JT.Reg = JumpTableReg;
2504 
2505   if (!JTH.OmitRangeCheck) {
2506     // Emit the range check for the jump table, and branch to the default block
2507     // for the switch statement if the value being switched on exceeds the
2508     // largest case in the switch.
2509     SDValue CMP = DAG.getSetCC(
2510         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2511                                    Sub.getValueType()),
2512         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2513 
2514     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2515                                  MVT::Other, CopyTo, CMP,
2516                                  DAG.getBasicBlock(JT.Default));
2517 
2518     // Avoid emitting unnecessary branches to the next block.
2519     if (JT.MBB != NextBlock(SwitchBB))
2520       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2521                            DAG.getBasicBlock(JT.MBB));
2522 
2523     DAG.setRoot(BrCond);
2524   } else {
2525     // Avoid emitting unnecessary branches to the next block.
2526     if (JT.MBB != NextBlock(SwitchBB))
2527       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2528                               DAG.getBasicBlock(JT.MBB)));
2529     else
2530       DAG.setRoot(CopyTo);
2531   }
2532 }
2533 
2534 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2535 /// variable if there exists one.
2536 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2537                                  SDValue &Chain) {
2538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2539   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2540   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2541   MachineFunction &MF = DAG.getMachineFunction();
2542   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2543   MachineSDNode *Node =
2544       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2545   if (Global) {
2546     MachinePointerInfo MPInfo(Global);
2547     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2548                  MachineMemOperand::MODereferenceable;
2549     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2550         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2551     DAG.setNodeMemRefs(Node, {MemRef});
2552   }
2553   if (PtrTy != PtrMemTy)
2554     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2555   return SDValue(Node, 0);
2556 }
2557 
2558 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2559 /// tail spliced into a stack protector check success bb.
2560 ///
2561 /// For a high level explanation of how this fits into the stack protector
2562 /// generation see the comment on the declaration of class
2563 /// StackProtectorDescriptor.
2564 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2565                                                   MachineBasicBlock *ParentBB) {
2566 
2567   // First create the loads to the guard/stack slot for the comparison.
2568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2569   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2570   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2571 
2572   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2573   int FI = MFI.getStackProtectorIndex();
2574 
2575   SDValue Guard;
2576   SDLoc dl = getCurSDLoc();
2577   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2578   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2579   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2580 
2581   // Generate code to load the content of the guard slot.
2582   SDValue GuardVal = DAG.getLoad(
2583       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2584       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2585       MachineMemOperand::MOVolatile);
2586 
2587   if (TLI.useStackGuardXorFP())
2588     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2589 
2590   // Retrieve guard check function, nullptr if instrumentation is inlined.
2591   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2592     // The target provides a guard check function to validate the guard value.
2593     // Generate a call to that function with the content of the guard slot as
2594     // argument.
2595     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2596     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2597 
2598     TargetLowering::ArgListTy Args;
2599     TargetLowering::ArgListEntry Entry;
2600     Entry.Node = GuardVal;
2601     Entry.Ty = FnTy->getParamType(0);
2602     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2603       Entry.IsInReg = true;
2604     Args.push_back(Entry);
2605 
2606     TargetLowering::CallLoweringInfo CLI(DAG);
2607     CLI.setDebugLoc(getCurSDLoc())
2608         .setChain(DAG.getEntryNode())
2609         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2610                    getValue(GuardCheckFn), std::move(Args));
2611 
2612     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2613     DAG.setRoot(Result.second);
2614     return;
2615   }
2616 
2617   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2618   // Otherwise, emit a volatile load to retrieve the stack guard value.
2619   SDValue Chain = DAG.getEntryNode();
2620   if (TLI.useLoadStackGuardNode()) {
2621     Guard = getLoadStackGuard(DAG, dl, Chain);
2622   } else {
2623     const Value *IRGuard = TLI.getSDagStackGuard(M);
2624     SDValue GuardPtr = getValue(IRGuard);
2625 
2626     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2627                         MachinePointerInfo(IRGuard, 0), Align,
2628                         MachineMemOperand::MOVolatile);
2629   }
2630 
2631   // Perform the comparison via a getsetcc.
2632   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2633                                                         *DAG.getContext(),
2634                                                         Guard.getValueType()),
2635                              Guard, GuardVal, ISD::SETNE);
2636 
2637   // If the guard/stackslot do not equal, branch to failure MBB.
2638   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2639                                MVT::Other, GuardVal.getOperand(0),
2640                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2641   // Otherwise branch to success MBB.
2642   SDValue Br = DAG.getNode(ISD::BR, dl,
2643                            MVT::Other, BrCond,
2644                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2645 
2646   DAG.setRoot(Br);
2647 }
2648 
2649 /// Codegen the failure basic block for a stack protector check.
2650 ///
2651 /// A failure stack protector machine basic block consists simply of a call to
2652 /// __stack_chk_fail().
2653 ///
2654 /// For a high level explanation of how this fits into the stack protector
2655 /// generation see the comment on the declaration of class
2656 /// StackProtectorDescriptor.
2657 void
2658 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2659   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2660   TargetLowering::MakeLibCallOptions CallOptions;
2661   CallOptions.setDiscardResult(true);
2662   SDValue Chain =
2663       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2664                       None, CallOptions, getCurSDLoc()).second;
2665   // On PS4, the "return address" must still be within the calling function,
2666   // even if it's at the very end, so emit an explicit TRAP here.
2667   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2668   if (TM.getTargetTriple().isPS4CPU())
2669     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2670 
2671   DAG.setRoot(Chain);
2672 }
2673 
2674 /// visitBitTestHeader - This function emits necessary code to produce value
2675 /// suitable for "bit tests"
2676 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2677                                              MachineBasicBlock *SwitchBB) {
2678   SDLoc dl = getCurSDLoc();
2679 
2680   // Subtract the minimum value.
2681   SDValue SwitchOp = getValue(B.SValue);
2682   EVT VT = SwitchOp.getValueType();
2683   SDValue RangeSub =
2684       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2685 
2686   // Determine the type of the test operands.
2687   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2688   bool UsePtrType = false;
2689   if (!TLI.isTypeLegal(VT)) {
2690     UsePtrType = true;
2691   } else {
2692     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2693       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2694         // Switch table case range are encoded into series of masks.
2695         // Just use pointer type, it's guaranteed to fit.
2696         UsePtrType = true;
2697         break;
2698       }
2699   }
2700   SDValue Sub = RangeSub;
2701   if (UsePtrType) {
2702     VT = TLI.getPointerTy(DAG.getDataLayout());
2703     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2704   }
2705 
2706   B.RegVT = VT.getSimpleVT();
2707   B.Reg = FuncInfo.CreateReg(B.RegVT);
2708   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2709 
2710   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2711 
2712   if (!B.OmitRangeCheck)
2713     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2714   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2715   SwitchBB->normalizeSuccProbs();
2716 
2717   SDValue Root = CopyTo;
2718   if (!B.OmitRangeCheck) {
2719     // Conditional branch to the default block.
2720     SDValue RangeCmp = DAG.getSetCC(dl,
2721         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2722                                RangeSub.getValueType()),
2723         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2724         ISD::SETUGT);
2725 
2726     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2727                        DAG.getBasicBlock(B.Default));
2728   }
2729 
2730   // Avoid emitting unnecessary branches to the next block.
2731   if (MBB != NextBlock(SwitchBB))
2732     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2733 
2734   DAG.setRoot(Root);
2735 }
2736 
2737 /// visitBitTestCase - this function produces one "bit test"
2738 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2739                                            MachineBasicBlock* NextMBB,
2740                                            BranchProbability BranchProbToNext,
2741                                            unsigned Reg,
2742                                            BitTestCase &B,
2743                                            MachineBasicBlock *SwitchBB) {
2744   SDLoc dl = getCurSDLoc();
2745   MVT VT = BB.RegVT;
2746   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2747   SDValue Cmp;
2748   unsigned PopCount = countPopulation(B.Mask);
2749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2750   if (PopCount == 1) {
2751     // Testing for a single bit; just compare the shift count with what it
2752     // would need to be to shift a 1 bit in that position.
2753     Cmp = DAG.getSetCC(
2754         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2755         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2756         ISD::SETEQ);
2757   } else if (PopCount == BB.Range) {
2758     // There is only one zero bit in the range, test for it directly.
2759     Cmp = DAG.getSetCC(
2760         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2761         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2762         ISD::SETNE);
2763   } else {
2764     // Make desired shift
2765     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2766                                     DAG.getConstant(1, dl, VT), ShiftOp);
2767 
2768     // Emit bit tests and jumps
2769     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2770                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2771     Cmp = DAG.getSetCC(
2772         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2773         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2774   }
2775 
2776   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2777   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2778   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2779   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2780   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2781   // one as they are relative probabilities (and thus work more like weights),
2782   // and hence we need to normalize them to let the sum of them become one.
2783   SwitchBB->normalizeSuccProbs();
2784 
2785   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2786                               MVT::Other, getControlRoot(),
2787                               Cmp, DAG.getBasicBlock(B.TargetBB));
2788 
2789   // Avoid emitting unnecessary branches to the next block.
2790   if (NextMBB != NextBlock(SwitchBB))
2791     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2792                         DAG.getBasicBlock(NextMBB));
2793 
2794   DAG.setRoot(BrAnd);
2795 }
2796 
2797 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2798   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2799 
2800   // Retrieve successors. Look through artificial IR level blocks like
2801   // catchswitch for successors.
2802   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2803   const BasicBlock *EHPadBB = I.getSuccessor(1);
2804 
2805   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2806   // have to do anything here to lower funclet bundles.
2807   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2808                                         LLVMContext::OB_gc_transition,
2809                                         LLVMContext::OB_gc_live,
2810                                         LLVMContext::OB_funclet,
2811                                         LLVMContext::OB_cfguardtarget}) &&
2812          "Cannot lower invokes with arbitrary operand bundles yet!");
2813 
2814   const Value *Callee(I.getCalledOperand());
2815   const Function *Fn = dyn_cast<Function>(Callee);
2816   if (isa<InlineAsm>(Callee))
2817     visitInlineAsm(I);
2818   else if (Fn && Fn->isIntrinsic()) {
2819     switch (Fn->getIntrinsicID()) {
2820     default:
2821       llvm_unreachable("Cannot invoke this intrinsic");
2822     case Intrinsic::donothing:
2823       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2824       break;
2825     case Intrinsic::experimental_patchpoint_void:
2826     case Intrinsic::experimental_patchpoint_i64:
2827       visitPatchpoint(I, EHPadBB);
2828       break;
2829     case Intrinsic::experimental_gc_statepoint:
2830       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2831       break;
2832     case Intrinsic::wasm_rethrow_in_catch: {
2833       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2834       // special because it can be invoked, so we manually lower it to a DAG
2835       // node here.
2836       SmallVector<SDValue, 8> Ops;
2837       Ops.push_back(getRoot()); // inchain
2838       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2839       Ops.push_back(
2840           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2841                                 TLI.getPointerTy(DAG.getDataLayout())));
2842       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2843       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2844       break;
2845     }
2846     }
2847   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2848     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2849     // Eventually we will support lowering the @llvm.experimental.deoptimize
2850     // intrinsic, and right now there are no plans to support other intrinsics
2851     // with deopt state.
2852     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2853   } else {
2854     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2855   }
2856 
2857   // If the value of the invoke is used outside of its defining block, make it
2858   // available as a virtual register.
2859   // We already took care of the exported value for the statepoint instruction
2860   // during call to the LowerStatepoint.
2861   if (!isa<GCStatepointInst>(I)) {
2862     CopyToExportRegsIfNeeded(&I);
2863   }
2864 
2865   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2866   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2867   BranchProbability EHPadBBProb =
2868       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2869           : BranchProbability::getZero();
2870   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2871 
2872   // Update successor info.
2873   addSuccessorWithProb(InvokeMBB, Return);
2874   for (auto &UnwindDest : UnwindDests) {
2875     UnwindDest.first->setIsEHPad();
2876     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2877   }
2878   InvokeMBB->normalizeSuccProbs();
2879 
2880   // Drop into normal successor.
2881   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2882                           DAG.getBasicBlock(Return)));
2883 }
2884 
2885 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2886   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2887 
2888   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2889   // have to do anything here to lower funclet bundles.
2890   assert(!I.hasOperandBundlesOtherThan(
2891              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2892          "Cannot lower callbrs with arbitrary operand bundles yet!");
2893 
2894   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2895   visitInlineAsm(I);
2896   CopyToExportRegsIfNeeded(&I);
2897 
2898   // Retrieve successors.
2899   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2900 
2901   // Update successor info.
2902   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2903   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2904     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2905     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2906     Target->setIsInlineAsmBrIndirectTarget();
2907   }
2908   CallBrMBB->normalizeSuccProbs();
2909 
2910   // Drop into default successor.
2911   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2912                           MVT::Other, getControlRoot(),
2913                           DAG.getBasicBlock(Return)));
2914 }
2915 
2916 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2917   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2918 }
2919 
2920 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2921   assert(FuncInfo.MBB->isEHPad() &&
2922          "Call to landingpad not in landing pad!");
2923 
2924   // If there aren't registers to copy the values into (e.g., during SjLj
2925   // exceptions), then don't bother to create these DAG nodes.
2926   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2927   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2928   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2929       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2930     return;
2931 
2932   // If landingpad's return type is token type, we don't create DAG nodes
2933   // for its exception pointer and selector value. The extraction of exception
2934   // pointer or selector value from token type landingpads is not currently
2935   // supported.
2936   if (LP.getType()->isTokenTy())
2937     return;
2938 
2939   SmallVector<EVT, 2> ValueVTs;
2940   SDLoc dl = getCurSDLoc();
2941   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2942   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2943 
2944   // Get the two live-in registers as SDValues. The physregs have already been
2945   // copied into virtual registers.
2946   SDValue Ops[2];
2947   if (FuncInfo.ExceptionPointerVirtReg) {
2948     Ops[0] = DAG.getZExtOrTrunc(
2949         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2950                            FuncInfo.ExceptionPointerVirtReg,
2951                            TLI.getPointerTy(DAG.getDataLayout())),
2952         dl, ValueVTs[0]);
2953   } else {
2954     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2955   }
2956   Ops[1] = DAG.getZExtOrTrunc(
2957       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2958                          FuncInfo.ExceptionSelectorVirtReg,
2959                          TLI.getPointerTy(DAG.getDataLayout())),
2960       dl, ValueVTs[1]);
2961 
2962   // Merge into one.
2963   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2964                             DAG.getVTList(ValueVTs), Ops);
2965   setValue(&LP, Res);
2966 }
2967 
2968 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2969                                            MachineBasicBlock *Last) {
2970   // Update JTCases.
2971   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2972     if (SL->JTCases[i].first.HeaderBB == First)
2973       SL->JTCases[i].first.HeaderBB = Last;
2974 
2975   // Update BitTestCases.
2976   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2977     if (SL->BitTestCases[i].Parent == First)
2978       SL->BitTestCases[i].Parent = Last;
2979 }
2980 
2981 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2982   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2983 
2984   // Update machine-CFG edges with unique successors.
2985   SmallSet<BasicBlock*, 32> Done;
2986   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2987     BasicBlock *BB = I.getSuccessor(i);
2988     bool Inserted = Done.insert(BB).second;
2989     if (!Inserted)
2990         continue;
2991 
2992     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2993     addSuccessorWithProb(IndirectBrMBB, Succ);
2994   }
2995   IndirectBrMBB->normalizeSuccProbs();
2996 
2997   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2998                           MVT::Other, getControlRoot(),
2999                           getValue(I.getAddress())));
3000 }
3001 
3002 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3003   if (!DAG.getTarget().Options.TrapUnreachable)
3004     return;
3005 
3006   // We may be able to ignore unreachable behind a noreturn call.
3007   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3008     const BasicBlock &BB = *I.getParent();
3009     if (&I != &BB.front()) {
3010       BasicBlock::const_iterator PredI =
3011         std::prev(BasicBlock::const_iterator(&I));
3012       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3013         if (Call->doesNotReturn())
3014           return;
3015       }
3016     }
3017   }
3018 
3019   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3020 }
3021 
3022 void SelectionDAGBuilder::visitFSub(const User &I) {
3023   // -0.0 - X --> fneg
3024   Type *Ty = I.getType();
3025   if (isa<Constant>(I.getOperand(0)) &&
3026       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
3027     SDValue Op2 = getValue(I.getOperand(1));
3028     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
3029                              Op2.getValueType(), Op2));
3030     return;
3031   }
3032 
3033   visitBinary(I, ISD::FSUB);
3034 }
3035 
3036 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3037   SDNodeFlags Flags;
3038 
3039   SDValue Op = getValue(I.getOperand(0));
3040   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3041                                     Op, Flags);
3042   setValue(&I, UnNodeValue);
3043 }
3044 
3045 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3046   SDNodeFlags Flags;
3047   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3048     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3049     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3050   }
3051   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3052     Flags.setExact(ExactOp->isExact());
3053   }
3054 
3055   SDValue Op1 = getValue(I.getOperand(0));
3056   SDValue Op2 = getValue(I.getOperand(1));
3057   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3058                                      Op1, Op2, Flags);
3059   setValue(&I, BinNodeValue);
3060 }
3061 
3062 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3063   SDValue Op1 = getValue(I.getOperand(0));
3064   SDValue Op2 = getValue(I.getOperand(1));
3065 
3066   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3067       Op1.getValueType(), DAG.getDataLayout());
3068 
3069   // Coerce the shift amount to the right type if we can.
3070   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3071     unsigned ShiftSize = ShiftTy.getSizeInBits();
3072     unsigned Op2Size = Op2.getValueSizeInBits();
3073     SDLoc DL = getCurSDLoc();
3074 
3075     // If the operand is smaller than the shift count type, promote it.
3076     if (ShiftSize > Op2Size)
3077       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3078 
3079     // If the operand is larger than the shift count type but the shift
3080     // count type has enough bits to represent any shift value, truncate
3081     // it now. This is a common case and it exposes the truncate to
3082     // optimization early.
3083     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3084       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3085     // Otherwise we'll need to temporarily settle for some other convenient
3086     // type.  Type legalization will make adjustments once the shiftee is split.
3087     else
3088       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3089   }
3090 
3091   bool nuw = false;
3092   bool nsw = false;
3093   bool exact = false;
3094 
3095   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3096 
3097     if (const OverflowingBinaryOperator *OFBinOp =
3098             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3099       nuw = OFBinOp->hasNoUnsignedWrap();
3100       nsw = OFBinOp->hasNoSignedWrap();
3101     }
3102     if (const PossiblyExactOperator *ExactOp =
3103             dyn_cast<const PossiblyExactOperator>(&I))
3104       exact = ExactOp->isExact();
3105   }
3106   SDNodeFlags Flags;
3107   Flags.setExact(exact);
3108   Flags.setNoSignedWrap(nsw);
3109   Flags.setNoUnsignedWrap(nuw);
3110   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3111                             Flags);
3112   setValue(&I, Res);
3113 }
3114 
3115 void SelectionDAGBuilder::visitSDiv(const User &I) {
3116   SDValue Op1 = getValue(I.getOperand(0));
3117   SDValue Op2 = getValue(I.getOperand(1));
3118 
3119   SDNodeFlags Flags;
3120   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3121                  cast<PossiblyExactOperator>(&I)->isExact());
3122   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3123                            Op2, Flags));
3124 }
3125 
3126 void SelectionDAGBuilder::visitICmp(const User &I) {
3127   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3128   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3129     predicate = IC->getPredicate();
3130   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3131     predicate = ICmpInst::Predicate(IC->getPredicate());
3132   SDValue Op1 = getValue(I.getOperand(0));
3133   SDValue Op2 = getValue(I.getOperand(1));
3134   ISD::CondCode Opcode = getICmpCondCode(predicate);
3135 
3136   auto &TLI = DAG.getTargetLoweringInfo();
3137   EVT MemVT =
3138       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3139 
3140   // If a pointer's DAG type is larger than its memory type then the DAG values
3141   // are zero-extended. This breaks signed comparisons so truncate back to the
3142   // underlying type before doing the compare.
3143   if (Op1.getValueType() != MemVT) {
3144     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3145     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3146   }
3147 
3148   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3149                                                         I.getType());
3150   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3151 }
3152 
3153 void SelectionDAGBuilder::visitFCmp(const User &I) {
3154   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3155   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3156     predicate = FC->getPredicate();
3157   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3158     predicate = FCmpInst::Predicate(FC->getPredicate());
3159   SDValue Op1 = getValue(I.getOperand(0));
3160   SDValue Op2 = getValue(I.getOperand(1));
3161 
3162   ISD::CondCode Condition = getFCmpCondCode(predicate);
3163   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3164   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3165     Condition = getFCmpCodeWithoutNaN(Condition);
3166 
3167   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3168                                                         I.getType());
3169   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3170 }
3171 
3172 // Check if the condition of the select has one use or two users that are both
3173 // selects with the same condition.
3174 static bool hasOnlySelectUsers(const Value *Cond) {
3175   return llvm::all_of(Cond->users(), [](const Value *V) {
3176     return isa<SelectInst>(V);
3177   });
3178 }
3179 
3180 void SelectionDAGBuilder::visitSelect(const User &I) {
3181   SmallVector<EVT, 4> ValueVTs;
3182   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3183                   ValueVTs);
3184   unsigned NumValues = ValueVTs.size();
3185   if (NumValues == 0) return;
3186 
3187   SmallVector<SDValue, 4> Values(NumValues);
3188   SDValue Cond     = getValue(I.getOperand(0));
3189   SDValue LHSVal   = getValue(I.getOperand(1));
3190   SDValue RHSVal   = getValue(I.getOperand(2));
3191   SmallVector<SDValue, 1> BaseOps(1, Cond);
3192   ISD::NodeType OpCode =
3193       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3194 
3195   bool IsUnaryAbs = false;
3196 
3197   // Min/max matching is only viable if all output VTs are the same.
3198   if (is_splat(ValueVTs)) {
3199     EVT VT = ValueVTs[0];
3200     LLVMContext &Ctx = *DAG.getContext();
3201     auto &TLI = DAG.getTargetLoweringInfo();
3202 
3203     // We care about the legality of the operation after it has been type
3204     // legalized.
3205     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3206       VT = TLI.getTypeToTransformTo(Ctx, VT);
3207 
3208     // If the vselect is legal, assume we want to leave this as a vector setcc +
3209     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3210     // min/max is legal on the scalar type.
3211     bool UseScalarMinMax = VT.isVector() &&
3212       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3213 
3214     Value *LHS, *RHS;
3215     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3216     ISD::NodeType Opc = ISD::DELETED_NODE;
3217     switch (SPR.Flavor) {
3218     case SPF_UMAX:    Opc = ISD::UMAX; break;
3219     case SPF_UMIN:    Opc = ISD::UMIN; break;
3220     case SPF_SMAX:    Opc = ISD::SMAX; break;
3221     case SPF_SMIN:    Opc = ISD::SMIN; break;
3222     case SPF_FMINNUM:
3223       switch (SPR.NaNBehavior) {
3224       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3225       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3226       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3227       case SPNB_RETURNS_ANY: {
3228         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3229           Opc = ISD::FMINNUM;
3230         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3231           Opc = ISD::FMINIMUM;
3232         else if (UseScalarMinMax)
3233           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3234             ISD::FMINNUM : ISD::FMINIMUM;
3235         break;
3236       }
3237       }
3238       break;
3239     case SPF_FMAXNUM:
3240       switch (SPR.NaNBehavior) {
3241       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3242       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3243       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3244       case SPNB_RETURNS_ANY:
3245 
3246         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3247           Opc = ISD::FMAXNUM;
3248         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3249           Opc = ISD::FMAXIMUM;
3250         else if (UseScalarMinMax)
3251           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3252             ISD::FMAXNUM : ISD::FMAXIMUM;
3253         break;
3254       }
3255       break;
3256     case SPF_ABS:
3257       IsUnaryAbs = true;
3258       Opc = ISD::ABS;
3259       break;
3260     case SPF_NABS:
3261       // TODO: we need to produce sub(0, abs(X)).
3262     default: break;
3263     }
3264 
3265     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3266         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3267          (UseScalarMinMax &&
3268           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3269         // If the underlying comparison instruction is used by any other
3270         // instruction, the consumed instructions won't be destroyed, so it is
3271         // not profitable to convert to a min/max.
3272         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3273       OpCode = Opc;
3274       LHSVal = getValue(LHS);
3275       RHSVal = getValue(RHS);
3276       BaseOps.clear();
3277     }
3278 
3279     if (IsUnaryAbs) {
3280       OpCode = Opc;
3281       LHSVal = getValue(LHS);
3282       BaseOps.clear();
3283     }
3284   }
3285 
3286   if (IsUnaryAbs) {
3287     for (unsigned i = 0; i != NumValues; ++i) {
3288       Values[i] =
3289           DAG.getNode(OpCode, getCurSDLoc(),
3290                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3291                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3292     }
3293   } else {
3294     for (unsigned i = 0; i != NumValues; ++i) {
3295       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3296       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3297       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3298       Values[i] = DAG.getNode(
3299           OpCode, getCurSDLoc(),
3300           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3301     }
3302   }
3303 
3304   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3305                            DAG.getVTList(ValueVTs), Values));
3306 }
3307 
3308 void SelectionDAGBuilder::visitTrunc(const User &I) {
3309   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3310   SDValue N = getValue(I.getOperand(0));
3311   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3312                                                         I.getType());
3313   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3314 }
3315 
3316 void SelectionDAGBuilder::visitZExt(const User &I) {
3317   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3318   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3319   SDValue N = getValue(I.getOperand(0));
3320   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3321                                                         I.getType());
3322   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3323 }
3324 
3325 void SelectionDAGBuilder::visitSExt(const User &I) {
3326   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3327   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3328   SDValue N = getValue(I.getOperand(0));
3329   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3330                                                         I.getType());
3331   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3332 }
3333 
3334 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3335   // FPTrunc is never a no-op cast, no need to check
3336   SDValue N = getValue(I.getOperand(0));
3337   SDLoc dl = getCurSDLoc();
3338   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3339   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3340   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3341                            DAG.getTargetConstant(
3342                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3343 }
3344 
3345 void SelectionDAGBuilder::visitFPExt(const User &I) {
3346   // FPExt is never a no-op cast, no need to check
3347   SDValue N = getValue(I.getOperand(0));
3348   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3349                                                         I.getType());
3350   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3351 }
3352 
3353 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3354   // FPToUI is never a no-op cast, no need to check
3355   SDValue N = getValue(I.getOperand(0));
3356   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3357                                                         I.getType());
3358   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3359 }
3360 
3361 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3362   // FPToSI is never a no-op cast, no need to check
3363   SDValue N = getValue(I.getOperand(0));
3364   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3365                                                         I.getType());
3366   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3367 }
3368 
3369 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3370   // UIToFP is never a no-op cast, no need to check
3371   SDValue N = getValue(I.getOperand(0));
3372   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3373                                                         I.getType());
3374   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3375 }
3376 
3377 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3378   // SIToFP is never a no-op cast, no need to check
3379   SDValue N = getValue(I.getOperand(0));
3380   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3381                                                         I.getType());
3382   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3383 }
3384 
3385 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3386   // What to do depends on the size of the integer and the size of the pointer.
3387   // We can either truncate, zero extend, or no-op, accordingly.
3388   SDValue N = getValue(I.getOperand(0));
3389   auto &TLI = DAG.getTargetLoweringInfo();
3390   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3391                                                         I.getType());
3392   EVT PtrMemVT =
3393       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3394   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3395   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3396   setValue(&I, N);
3397 }
3398 
3399 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3400   // What to do depends on the size of the integer and the size of the pointer.
3401   // We can either truncate, zero extend, or no-op, accordingly.
3402   SDValue N = getValue(I.getOperand(0));
3403   auto &TLI = DAG.getTargetLoweringInfo();
3404   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3405   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3406   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3407   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3408   setValue(&I, N);
3409 }
3410 
3411 void SelectionDAGBuilder::visitBitCast(const User &I) {
3412   SDValue N = getValue(I.getOperand(0));
3413   SDLoc dl = getCurSDLoc();
3414   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3415                                                         I.getType());
3416 
3417   // BitCast assures us that source and destination are the same size so this is
3418   // either a BITCAST or a no-op.
3419   if (DestVT != N.getValueType())
3420     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3421                              DestVT, N)); // convert types.
3422   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3423   // might fold any kind of constant expression to an integer constant and that
3424   // is not what we are looking for. Only recognize a bitcast of a genuine
3425   // constant integer as an opaque constant.
3426   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3427     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3428                                  /*isOpaque*/true));
3429   else
3430     setValue(&I, N);            // noop cast.
3431 }
3432 
3433 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3435   const Value *SV = I.getOperand(0);
3436   SDValue N = getValue(SV);
3437   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3438 
3439   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3440   unsigned DestAS = I.getType()->getPointerAddressSpace();
3441 
3442   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3443     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3444 
3445   setValue(&I, N);
3446 }
3447 
3448 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3450   SDValue InVec = getValue(I.getOperand(0));
3451   SDValue InVal = getValue(I.getOperand(1));
3452   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3453                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3454   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3455                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3456                            InVec, InVal, InIdx));
3457 }
3458 
3459 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3460   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3461   SDValue InVec = getValue(I.getOperand(0));
3462   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3463                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3464   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3465                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3466                            InVec, InIdx));
3467 }
3468 
3469 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3470   SDValue Src1 = getValue(I.getOperand(0));
3471   SDValue Src2 = getValue(I.getOperand(1));
3472   ArrayRef<int> Mask;
3473   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3474     Mask = SVI->getShuffleMask();
3475   else
3476     Mask = cast<ConstantExpr>(I).getShuffleMask();
3477   SDLoc DL = getCurSDLoc();
3478   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3479   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3480   EVT SrcVT = Src1.getValueType();
3481 
3482   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3483       VT.isScalableVector()) {
3484     // Canonical splat form of first element of first input vector.
3485     SDValue FirstElt =
3486         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3487                     DAG.getVectorIdxConstant(0, DL));
3488     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3489     return;
3490   }
3491 
3492   // For now, we only handle splats for scalable vectors.
3493   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3494   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3495   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3496 
3497   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3498   unsigned MaskNumElts = Mask.size();
3499 
3500   if (SrcNumElts == MaskNumElts) {
3501     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3502     return;
3503   }
3504 
3505   // Normalize the shuffle vector since mask and vector length don't match.
3506   if (SrcNumElts < MaskNumElts) {
3507     // Mask is longer than the source vectors. We can use concatenate vector to
3508     // make the mask and vectors lengths match.
3509 
3510     if (MaskNumElts % SrcNumElts == 0) {
3511       // Mask length is a multiple of the source vector length.
3512       // Check if the shuffle is some kind of concatenation of the input
3513       // vectors.
3514       unsigned NumConcat = MaskNumElts / SrcNumElts;
3515       bool IsConcat = true;
3516       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3517       for (unsigned i = 0; i != MaskNumElts; ++i) {
3518         int Idx = Mask[i];
3519         if (Idx < 0)
3520           continue;
3521         // Ensure the indices in each SrcVT sized piece are sequential and that
3522         // the same source is used for the whole piece.
3523         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3524             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3525              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3526           IsConcat = false;
3527           break;
3528         }
3529         // Remember which source this index came from.
3530         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3531       }
3532 
3533       // The shuffle is concatenating multiple vectors together. Just emit
3534       // a CONCAT_VECTORS operation.
3535       if (IsConcat) {
3536         SmallVector<SDValue, 8> ConcatOps;
3537         for (auto Src : ConcatSrcs) {
3538           if (Src < 0)
3539             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3540           else if (Src == 0)
3541             ConcatOps.push_back(Src1);
3542           else
3543             ConcatOps.push_back(Src2);
3544         }
3545         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3546         return;
3547       }
3548     }
3549 
3550     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3551     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3552     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3553                                     PaddedMaskNumElts);
3554 
3555     // Pad both vectors with undefs to make them the same length as the mask.
3556     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3557 
3558     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3559     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3560     MOps1[0] = Src1;
3561     MOps2[0] = Src2;
3562 
3563     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3564     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3565 
3566     // Readjust mask for new input vector length.
3567     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3568     for (unsigned i = 0; i != MaskNumElts; ++i) {
3569       int Idx = Mask[i];
3570       if (Idx >= (int)SrcNumElts)
3571         Idx -= SrcNumElts - PaddedMaskNumElts;
3572       MappedOps[i] = Idx;
3573     }
3574 
3575     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3576 
3577     // If the concatenated vector was padded, extract a subvector with the
3578     // correct number of elements.
3579     if (MaskNumElts != PaddedMaskNumElts)
3580       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3581                            DAG.getVectorIdxConstant(0, DL));
3582 
3583     setValue(&I, Result);
3584     return;
3585   }
3586 
3587   if (SrcNumElts > MaskNumElts) {
3588     // Analyze the access pattern of the vector to see if we can extract
3589     // two subvectors and do the shuffle.
3590     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3591     bool CanExtract = true;
3592     for (int Idx : Mask) {
3593       unsigned Input = 0;
3594       if (Idx < 0)
3595         continue;
3596 
3597       if (Idx >= (int)SrcNumElts) {
3598         Input = 1;
3599         Idx -= SrcNumElts;
3600       }
3601 
3602       // If all the indices come from the same MaskNumElts sized portion of
3603       // the sources we can use extract. Also make sure the extract wouldn't
3604       // extract past the end of the source.
3605       int NewStartIdx = alignDown(Idx, MaskNumElts);
3606       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3607           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3608         CanExtract = false;
3609       // Make sure we always update StartIdx as we use it to track if all
3610       // elements are undef.
3611       StartIdx[Input] = NewStartIdx;
3612     }
3613 
3614     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3615       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3616       return;
3617     }
3618     if (CanExtract) {
3619       // Extract appropriate subvector and generate a vector shuffle
3620       for (unsigned Input = 0; Input < 2; ++Input) {
3621         SDValue &Src = Input == 0 ? Src1 : Src2;
3622         if (StartIdx[Input] < 0)
3623           Src = DAG.getUNDEF(VT);
3624         else {
3625           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3626                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3627         }
3628       }
3629 
3630       // Calculate new mask.
3631       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3632       for (int &Idx : MappedOps) {
3633         if (Idx >= (int)SrcNumElts)
3634           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3635         else if (Idx >= 0)
3636           Idx -= StartIdx[0];
3637       }
3638 
3639       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3640       return;
3641     }
3642   }
3643 
3644   // We can't use either concat vectors or extract subvectors so fall back to
3645   // replacing the shuffle with extract and build vector.
3646   // to insert and build vector.
3647   EVT EltVT = VT.getVectorElementType();
3648   SmallVector<SDValue,8> Ops;
3649   for (int Idx : Mask) {
3650     SDValue Res;
3651 
3652     if (Idx < 0) {
3653       Res = DAG.getUNDEF(EltVT);
3654     } else {
3655       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3656       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3657 
3658       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3659                         DAG.getVectorIdxConstant(Idx, DL));
3660     }
3661 
3662     Ops.push_back(Res);
3663   }
3664 
3665   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3666 }
3667 
3668 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3669   ArrayRef<unsigned> Indices;
3670   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3671     Indices = IV->getIndices();
3672   else
3673     Indices = cast<ConstantExpr>(&I)->getIndices();
3674 
3675   const Value *Op0 = I.getOperand(0);
3676   const Value *Op1 = I.getOperand(1);
3677   Type *AggTy = I.getType();
3678   Type *ValTy = Op1->getType();
3679   bool IntoUndef = isa<UndefValue>(Op0);
3680   bool FromUndef = isa<UndefValue>(Op1);
3681 
3682   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3683 
3684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3685   SmallVector<EVT, 4> AggValueVTs;
3686   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3687   SmallVector<EVT, 4> ValValueVTs;
3688   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3689 
3690   unsigned NumAggValues = AggValueVTs.size();
3691   unsigned NumValValues = ValValueVTs.size();
3692   SmallVector<SDValue, 4> Values(NumAggValues);
3693 
3694   // Ignore an insertvalue that produces an empty object
3695   if (!NumAggValues) {
3696     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3697     return;
3698   }
3699 
3700   SDValue Agg = getValue(Op0);
3701   unsigned i = 0;
3702   // Copy the beginning value(s) from the original aggregate.
3703   for (; i != LinearIndex; ++i)
3704     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3705                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3706   // Copy values from the inserted value(s).
3707   if (NumValValues) {
3708     SDValue Val = getValue(Op1);
3709     for (; i != LinearIndex + NumValValues; ++i)
3710       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3711                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3712   }
3713   // Copy remaining value(s) from the original aggregate.
3714   for (; i != NumAggValues; ++i)
3715     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3716                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3717 
3718   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3719                            DAG.getVTList(AggValueVTs), Values));
3720 }
3721 
3722 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3723   ArrayRef<unsigned> Indices;
3724   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3725     Indices = EV->getIndices();
3726   else
3727     Indices = cast<ConstantExpr>(&I)->getIndices();
3728 
3729   const Value *Op0 = I.getOperand(0);
3730   Type *AggTy = Op0->getType();
3731   Type *ValTy = I.getType();
3732   bool OutOfUndef = isa<UndefValue>(Op0);
3733 
3734   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3735 
3736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3737   SmallVector<EVT, 4> ValValueVTs;
3738   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3739 
3740   unsigned NumValValues = ValValueVTs.size();
3741 
3742   // Ignore a extractvalue that produces an empty object
3743   if (!NumValValues) {
3744     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3745     return;
3746   }
3747 
3748   SmallVector<SDValue, 4> Values(NumValValues);
3749 
3750   SDValue Agg = getValue(Op0);
3751   // Copy out the selected value(s).
3752   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3753     Values[i - LinearIndex] =
3754       OutOfUndef ?
3755         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3756         SDValue(Agg.getNode(), Agg.getResNo() + i);
3757 
3758   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3759                            DAG.getVTList(ValValueVTs), Values));
3760 }
3761 
3762 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3763   Value *Op0 = I.getOperand(0);
3764   // Note that the pointer operand may be a vector of pointers. Take the scalar
3765   // element which holds a pointer.
3766   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3767   SDValue N = getValue(Op0);
3768   SDLoc dl = getCurSDLoc();
3769   auto &TLI = DAG.getTargetLoweringInfo();
3770   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3771   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3772 
3773   // Normalize Vector GEP - all scalar operands should be converted to the
3774   // splat vector.
3775   bool IsVectorGEP = I.getType()->isVectorTy();
3776   ElementCount VectorElementCount =
3777       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3778                   : ElementCount(0, false);
3779 
3780   if (IsVectorGEP && !N.getValueType().isVector()) {
3781     LLVMContext &Context = *DAG.getContext();
3782     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3783     if (VectorElementCount.Scalable)
3784       N = DAG.getSplatVector(VT, dl, N);
3785     else
3786       N = DAG.getSplatBuildVector(VT, dl, N);
3787   }
3788 
3789   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3790        GTI != E; ++GTI) {
3791     const Value *Idx = GTI.getOperand();
3792     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3793       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3794       if (Field) {
3795         // N = N + Offset
3796         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3797 
3798         // In an inbounds GEP with an offset that is nonnegative even when
3799         // interpreted as signed, assume there is no unsigned overflow.
3800         SDNodeFlags Flags;
3801         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3802           Flags.setNoUnsignedWrap(true);
3803 
3804         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3805                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3806       }
3807     } else {
3808       // IdxSize is the width of the arithmetic according to IR semantics.
3809       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3810       // (and fix up the result later).
3811       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3812       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3813       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3814       // We intentionally mask away the high bits here; ElementSize may not
3815       // fit in IdxTy.
3816       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3817       bool ElementScalable = ElementSize.isScalable();
3818 
3819       // If this is a scalar constant or a splat vector of constants,
3820       // handle it quickly.
3821       const auto *C = dyn_cast<Constant>(Idx);
3822       if (C && isa<VectorType>(C->getType()))
3823         C = C->getSplatValue();
3824 
3825       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3826       if (CI && CI->isZero())
3827         continue;
3828       if (CI && !ElementScalable) {
3829         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3830         LLVMContext &Context = *DAG.getContext();
3831         SDValue OffsVal;
3832         if (IsVectorGEP)
3833           OffsVal = DAG.getConstant(
3834               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3835         else
3836           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3837 
3838         // In an inbounds GEP with an offset that is nonnegative even when
3839         // interpreted as signed, assume there is no unsigned overflow.
3840         SDNodeFlags Flags;
3841         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3842           Flags.setNoUnsignedWrap(true);
3843 
3844         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3845 
3846         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3847         continue;
3848       }
3849 
3850       // N = N + Idx * ElementMul;
3851       SDValue IdxN = getValue(Idx);
3852 
3853       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3854         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3855                                   VectorElementCount);
3856         if (VectorElementCount.Scalable)
3857           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3858         else
3859           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3860       }
3861 
3862       // If the index is smaller or larger than intptr_t, truncate or extend
3863       // it.
3864       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3865 
3866       if (ElementScalable) {
3867         EVT VScaleTy = N.getValueType().getScalarType();
3868         SDValue VScale = DAG.getNode(
3869             ISD::VSCALE, dl, VScaleTy,
3870             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3871         if (IsVectorGEP)
3872           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3873         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3874       } else {
3875         // If this is a multiply by a power of two, turn it into a shl
3876         // immediately.  This is a very common case.
3877         if (ElementMul != 1) {
3878           if (ElementMul.isPowerOf2()) {
3879             unsigned Amt = ElementMul.logBase2();
3880             IdxN = DAG.getNode(ISD::SHL, dl,
3881                                N.getValueType(), IdxN,
3882                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3883           } else {
3884             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3885                                             IdxN.getValueType());
3886             IdxN = DAG.getNode(ISD::MUL, dl,
3887                                N.getValueType(), IdxN, Scale);
3888           }
3889         }
3890       }
3891 
3892       N = DAG.getNode(ISD::ADD, dl,
3893                       N.getValueType(), N, IdxN);
3894     }
3895   }
3896 
3897   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3898     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3899 
3900   setValue(&I, N);
3901 }
3902 
3903 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3904   // If this is a fixed sized alloca in the entry block of the function,
3905   // allocate it statically on the stack.
3906   if (FuncInfo.StaticAllocaMap.count(&I))
3907     return;   // getValue will auto-populate this.
3908 
3909   SDLoc dl = getCurSDLoc();
3910   Type *Ty = I.getAllocatedType();
3911   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3912   auto &DL = DAG.getDataLayout();
3913   uint64_t TySize = DL.getTypeAllocSize(Ty);
3914   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3915 
3916   SDValue AllocSize = getValue(I.getArraySize());
3917 
3918   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3919   if (AllocSize.getValueType() != IntPtr)
3920     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3921 
3922   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3923                           AllocSize,
3924                           DAG.getConstant(TySize, dl, IntPtr));
3925 
3926   // Handle alignment.  If the requested alignment is less than or equal to
3927   // the stack alignment, ignore it.  If the size is greater than or equal to
3928   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3929   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3930   if (*Alignment <= StackAlign)
3931     Alignment = None;
3932 
3933   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3934   // Round the size of the allocation up to the stack alignment size
3935   // by add SA-1 to the size. This doesn't overflow because we're computing
3936   // an address inside an alloca.
3937   SDNodeFlags Flags;
3938   Flags.setNoUnsignedWrap(true);
3939   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3940                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3941 
3942   // Mask out the low bits for alignment purposes.
3943   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3944                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3945 
3946   SDValue Ops[] = {
3947       getRoot(), AllocSize,
3948       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3949   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3950   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3951   setValue(&I, DSA);
3952   DAG.setRoot(DSA.getValue(1));
3953 
3954   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3955 }
3956 
3957 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3958   if (I.isAtomic())
3959     return visitAtomicLoad(I);
3960 
3961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3962   const Value *SV = I.getOperand(0);
3963   if (TLI.supportSwiftError()) {
3964     // Swifterror values can come from either a function parameter with
3965     // swifterror attribute or an alloca with swifterror attribute.
3966     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3967       if (Arg->hasSwiftErrorAttr())
3968         return visitLoadFromSwiftError(I);
3969     }
3970 
3971     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3972       if (Alloca->isSwiftError())
3973         return visitLoadFromSwiftError(I);
3974     }
3975   }
3976 
3977   SDValue Ptr = getValue(SV);
3978 
3979   Type *Ty = I.getType();
3980   Align Alignment = I.getAlign();
3981 
3982   AAMDNodes AAInfo;
3983   I.getAAMetadata(AAInfo);
3984   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3985 
3986   SmallVector<EVT, 4> ValueVTs, MemVTs;
3987   SmallVector<uint64_t, 4> Offsets;
3988   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3989   unsigned NumValues = ValueVTs.size();
3990   if (NumValues == 0)
3991     return;
3992 
3993   bool isVolatile = I.isVolatile();
3994 
3995   SDValue Root;
3996   bool ConstantMemory = false;
3997   if (isVolatile)
3998     // Serialize volatile loads with other side effects.
3999     Root = getRoot();
4000   else if (NumValues > MaxParallelChains)
4001     Root = getMemoryRoot();
4002   else if (AA &&
4003            AA->pointsToConstantMemory(MemoryLocation(
4004                SV,
4005                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4006                AAInfo))) {
4007     // Do not serialize (non-volatile) loads of constant memory with anything.
4008     Root = DAG.getEntryNode();
4009     ConstantMemory = true;
4010   } else {
4011     // Do not serialize non-volatile loads against each other.
4012     Root = DAG.getRoot();
4013   }
4014 
4015   SDLoc dl = getCurSDLoc();
4016 
4017   if (isVolatile)
4018     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4019 
4020   // An aggregate load cannot wrap around the address space, so offsets to its
4021   // parts don't wrap either.
4022   SDNodeFlags Flags;
4023   Flags.setNoUnsignedWrap(true);
4024 
4025   SmallVector<SDValue, 4> Values(NumValues);
4026   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4027   EVT PtrVT = Ptr.getValueType();
4028 
4029   MachineMemOperand::Flags MMOFlags
4030     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4031 
4032   unsigned ChainI = 0;
4033   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4034     // Serializing loads here may result in excessive register pressure, and
4035     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4036     // could recover a bit by hoisting nodes upward in the chain by recognizing
4037     // they are side-effect free or do not alias. The optimizer should really
4038     // avoid this case by converting large object/array copies to llvm.memcpy
4039     // (MaxParallelChains should always remain as failsafe).
4040     if (ChainI == MaxParallelChains) {
4041       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4042       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4043                                   makeArrayRef(Chains.data(), ChainI));
4044       Root = Chain;
4045       ChainI = 0;
4046     }
4047     SDValue A = DAG.getNode(ISD::ADD, dl,
4048                             PtrVT, Ptr,
4049                             DAG.getConstant(Offsets[i], dl, PtrVT),
4050                             Flags);
4051 
4052     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4053                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4054                             MMOFlags, AAInfo, Ranges);
4055     Chains[ChainI] = L.getValue(1);
4056 
4057     if (MemVTs[i] != ValueVTs[i])
4058       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4059 
4060     Values[i] = L;
4061   }
4062 
4063   if (!ConstantMemory) {
4064     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4065                                 makeArrayRef(Chains.data(), ChainI));
4066     if (isVolatile)
4067       DAG.setRoot(Chain);
4068     else
4069       PendingLoads.push_back(Chain);
4070   }
4071 
4072   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4073                            DAG.getVTList(ValueVTs), Values));
4074 }
4075 
4076 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4077   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4078          "call visitStoreToSwiftError when backend supports swifterror");
4079 
4080   SmallVector<EVT, 4> ValueVTs;
4081   SmallVector<uint64_t, 4> Offsets;
4082   const Value *SrcV = I.getOperand(0);
4083   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4084                   SrcV->getType(), ValueVTs, &Offsets);
4085   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4086          "expect a single EVT for swifterror");
4087 
4088   SDValue Src = getValue(SrcV);
4089   // Create a virtual register, then update the virtual register.
4090   Register VReg =
4091       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4092   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4093   // Chain can be getRoot or getControlRoot.
4094   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4095                                       SDValue(Src.getNode(), Src.getResNo()));
4096   DAG.setRoot(CopyNode);
4097 }
4098 
4099 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4100   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4101          "call visitLoadFromSwiftError when backend supports swifterror");
4102 
4103   assert(!I.isVolatile() &&
4104          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4105          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4106          "Support volatile, non temporal, invariant for load_from_swift_error");
4107 
4108   const Value *SV = I.getOperand(0);
4109   Type *Ty = I.getType();
4110   AAMDNodes AAInfo;
4111   I.getAAMetadata(AAInfo);
4112   assert(
4113       (!AA ||
4114        !AA->pointsToConstantMemory(MemoryLocation(
4115            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4116            AAInfo))) &&
4117       "load_from_swift_error should not be constant memory");
4118 
4119   SmallVector<EVT, 4> ValueVTs;
4120   SmallVector<uint64_t, 4> Offsets;
4121   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4122                   ValueVTs, &Offsets);
4123   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4124          "expect a single EVT for swifterror");
4125 
4126   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4127   SDValue L = DAG.getCopyFromReg(
4128       getRoot(), getCurSDLoc(),
4129       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4130 
4131   setValue(&I, L);
4132 }
4133 
4134 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4135   if (I.isAtomic())
4136     return visitAtomicStore(I);
4137 
4138   const Value *SrcV = I.getOperand(0);
4139   const Value *PtrV = I.getOperand(1);
4140 
4141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4142   if (TLI.supportSwiftError()) {
4143     // Swifterror values can come from either a function parameter with
4144     // swifterror attribute or an alloca with swifterror attribute.
4145     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4146       if (Arg->hasSwiftErrorAttr())
4147         return visitStoreToSwiftError(I);
4148     }
4149 
4150     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4151       if (Alloca->isSwiftError())
4152         return visitStoreToSwiftError(I);
4153     }
4154   }
4155 
4156   SmallVector<EVT, 4> ValueVTs, MemVTs;
4157   SmallVector<uint64_t, 4> Offsets;
4158   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4159                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4160   unsigned NumValues = ValueVTs.size();
4161   if (NumValues == 0)
4162     return;
4163 
4164   // Get the lowered operands. Note that we do this after
4165   // checking if NumResults is zero, because with zero results
4166   // the operands won't have values in the map.
4167   SDValue Src = getValue(SrcV);
4168   SDValue Ptr = getValue(PtrV);
4169 
4170   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4171   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4172   SDLoc dl = getCurSDLoc();
4173   Align Alignment = I.getAlign();
4174   AAMDNodes AAInfo;
4175   I.getAAMetadata(AAInfo);
4176 
4177   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4178 
4179   // An aggregate load cannot wrap around the address space, so offsets to its
4180   // parts don't wrap either.
4181   SDNodeFlags Flags;
4182   Flags.setNoUnsignedWrap(true);
4183 
4184   unsigned ChainI = 0;
4185   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4186     // See visitLoad comments.
4187     if (ChainI == MaxParallelChains) {
4188       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4189                                   makeArrayRef(Chains.data(), ChainI));
4190       Root = Chain;
4191       ChainI = 0;
4192     }
4193     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4194     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4195     if (MemVTs[i] != ValueVTs[i])
4196       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4197     SDValue St =
4198         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4199                      Alignment, MMOFlags, AAInfo);
4200     Chains[ChainI] = St;
4201   }
4202 
4203   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4204                                   makeArrayRef(Chains.data(), ChainI));
4205   DAG.setRoot(StoreNode);
4206 }
4207 
4208 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4209                                            bool IsCompressing) {
4210   SDLoc sdl = getCurSDLoc();
4211 
4212   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4213                                MaybeAlign &Alignment) {
4214     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4215     Src0 = I.getArgOperand(0);
4216     Ptr = I.getArgOperand(1);
4217     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4218     Mask = I.getArgOperand(3);
4219   };
4220   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4221                                     MaybeAlign &Alignment) {
4222     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4223     Src0 = I.getArgOperand(0);
4224     Ptr = I.getArgOperand(1);
4225     Mask = I.getArgOperand(2);
4226     Alignment = None;
4227   };
4228 
4229   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4230   MaybeAlign Alignment;
4231   if (IsCompressing)
4232     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4233   else
4234     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4235 
4236   SDValue Ptr = getValue(PtrOperand);
4237   SDValue Src0 = getValue(Src0Operand);
4238   SDValue Mask = getValue(MaskOperand);
4239   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4240 
4241   EVT VT = Src0.getValueType();
4242   if (!Alignment)
4243     Alignment = DAG.getEVTAlign(VT);
4244 
4245   AAMDNodes AAInfo;
4246   I.getAAMetadata(AAInfo);
4247 
4248   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4249       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4250       // TODO: Make MachineMemOperands aware of scalable
4251       // vectors.
4252       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4253   SDValue StoreNode =
4254       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4255                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4256   DAG.setRoot(StoreNode);
4257   setValue(&I, StoreNode);
4258 }
4259 
4260 // Get a uniform base for the Gather/Scatter intrinsic.
4261 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4262 // We try to represent it as a base pointer + vector of indices.
4263 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4264 // The first operand of the GEP may be a single pointer or a vector of pointers
4265 // Example:
4266 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4267 //  or
4268 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4269 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4270 //
4271 // When the first GEP operand is a single pointer - it is the uniform base we
4272 // are looking for. If first operand of the GEP is a splat vector - we
4273 // extract the splat value and use it as a uniform base.
4274 // In all other cases the function returns 'false'.
4275 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4276                            ISD::MemIndexType &IndexType, SDValue &Scale,
4277                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4278   SelectionDAG& DAG = SDB->DAG;
4279   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4280   const DataLayout &DL = DAG.getDataLayout();
4281 
4282   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4283 
4284   // Handle splat constant pointer.
4285   if (auto *C = dyn_cast<Constant>(Ptr)) {
4286     C = C->getSplatValue();
4287     if (!C)
4288       return false;
4289 
4290     Base = SDB->getValue(C);
4291 
4292     unsigned NumElts = cast<VectorType>(Ptr->getType())->getNumElements();
4293     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4294     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4295     IndexType = ISD::SIGNED_SCALED;
4296     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4297     return true;
4298   }
4299 
4300   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4301   if (!GEP || GEP->getParent() != CurBB)
4302     return false;
4303 
4304   if (GEP->getNumOperands() != 2)
4305     return false;
4306 
4307   const Value *BasePtr = GEP->getPointerOperand();
4308   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4309 
4310   // Make sure the base is scalar and the index is a vector.
4311   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4312     return false;
4313 
4314   Base = SDB->getValue(BasePtr);
4315   Index = SDB->getValue(IndexVal);
4316   IndexType = ISD::SIGNED_SCALED;
4317   Scale = DAG.getTargetConstant(
4318               DL.getTypeAllocSize(GEP->getResultElementType()),
4319               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4320   return true;
4321 }
4322 
4323 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4324   SDLoc sdl = getCurSDLoc();
4325 
4326   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4327   const Value *Ptr = I.getArgOperand(1);
4328   SDValue Src0 = getValue(I.getArgOperand(0));
4329   SDValue Mask = getValue(I.getArgOperand(3));
4330   EVT VT = Src0.getValueType();
4331   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4332                         ->getMaybeAlignValue()
4333                         .getValueOr(DAG.getEVTAlign(VT));
4334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4335 
4336   AAMDNodes AAInfo;
4337   I.getAAMetadata(AAInfo);
4338 
4339   SDValue Base;
4340   SDValue Index;
4341   ISD::MemIndexType IndexType;
4342   SDValue Scale;
4343   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4344                                     I.getParent());
4345 
4346   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4347   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4348       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4349       // TODO: Make MachineMemOperands aware of scalable
4350       // vectors.
4351       MemoryLocation::UnknownSize, Alignment, AAInfo);
4352   if (!UniformBase) {
4353     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4354     Index = getValue(Ptr);
4355     IndexType = ISD::SIGNED_SCALED;
4356     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4357   }
4358   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4359   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4360                                          Ops, MMO, IndexType);
4361   DAG.setRoot(Scatter);
4362   setValue(&I, Scatter);
4363 }
4364 
4365 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4366   SDLoc sdl = getCurSDLoc();
4367 
4368   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4369                               MaybeAlign &Alignment) {
4370     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4371     Ptr = I.getArgOperand(0);
4372     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4373     Mask = I.getArgOperand(2);
4374     Src0 = I.getArgOperand(3);
4375   };
4376   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4377                                  MaybeAlign &Alignment) {
4378     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4379     Ptr = I.getArgOperand(0);
4380     Alignment = None;
4381     Mask = I.getArgOperand(1);
4382     Src0 = I.getArgOperand(2);
4383   };
4384 
4385   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4386   MaybeAlign Alignment;
4387   if (IsExpanding)
4388     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4389   else
4390     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4391 
4392   SDValue Ptr = getValue(PtrOperand);
4393   SDValue Src0 = getValue(Src0Operand);
4394   SDValue Mask = getValue(MaskOperand);
4395   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4396 
4397   EVT VT = Src0.getValueType();
4398   if (!Alignment)
4399     Alignment = DAG.getEVTAlign(VT);
4400 
4401   AAMDNodes AAInfo;
4402   I.getAAMetadata(AAInfo);
4403   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4404 
4405   // Do not serialize masked loads of constant memory with anything.
4406   MemoryLocation ML;
4407   if (VT.isScalableVector())
4408     ML = MemoryLocation(PtrOperand);
4409   else
4410     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4411                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4412                            AAInfo);
4413   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4414 
4415   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4416 
4417   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4418       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4419       // TODO: Make MachineMemOperands aware of scalable
4420       // vectors.
4421       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4422 
4423   SDValue Load =
4424       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4425                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4426   if (AddToChain)
4427     PendingLoads.push_back(Load.getValue(1));
4428   setValue(&I, Load);
4429 }
4430 
4431 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4432   SDLoc sdl = getCurSDLoc();
4433 
4434   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4435   const Value *Ptr = I.getArgOperand(0);
4436   SDValue Src0 = getValue(I.getArgOperand(3));
4437   SDValue Mask = getValue(I.getArgOperand(2));
4438 
4439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4440   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4441   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4442                         ->getMaybeAlignValue()
4443                         .getValueOr(DAG.getEVTAlign(VT));
4444 
4445   AAMDNodes AAInfo;
4446   I.getAAMetadata(AAInfo);
4447   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4448 
4449   SDValue Root = DAG.getRoot();
4450   SDValue Base;
4451   SDValue Index;
4452   ISD::MemIndexType IndexType;
4453   SDValue Scale;
4454   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4455                                     I.getParent());
4456   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4457   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4458       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4459       // TODO: Make MachineMemOperands aware of scalable
4460       // vectors.
4461       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4462 
4463   if (!UniformBase) {
4464     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4465     Index = getValue(Ptr);
4466     IndexType = ISD::SIGNED_SCALED;
4467     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4468   }
4469   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4470   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4471                                        Ops, MMO, IndexType);
4472 
4473   PendingLoads.push_back(Gather.getValue(1));
4474   setValue(&I, Gather);
4475 }
4476 
4477 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4478   SDLoc dl = getCurSDLoc();
4479   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4480   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4481   SyncScope::ID SSID = I.getSyncScopeID();
4482 
4483   SDValue InChain = getRoot();
4484 
4485   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4486   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4487 
4488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4489   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4490 
4491   MachineFunction &MF = DAG.getMachineFunction();
4492   MachineMemOperand *MMO = MF.getMachineMemOperand(
4493       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4494       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4495       FailureOrdering);
4496 
4497   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4498                                    dl, MemVT, VTs, InChain,
4499                                    getValue(I.getPointerOperand()),
4500                                    getValue(I.getCompareOperand()),
4501                                    getValue(I.getNewValOperand()), MMO);
4502 
4503   SDValue OutChain = L.getValue(2);
4504 
4505   setValue(&I, L);
4506   DAG.setRoot(OutChain);
4507 }
4508 
4509 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4510   SDLoc dl = getCurSDLoc();
4511   ISD::NodeType NT;
4512   switch (I.getOperation()) {
4513   default: llvm_unreachable("Unknown atomicrmw operation");
4514   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4515   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4516   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4517   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4518   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4519   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4520   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4521   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4522   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4523   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4524   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4525   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4526   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4527   }
4528   AtomicOrdering Ordering = I.getOrdering();
4529   SyncScope::ID SSID = I.getSyncScopeID();
4530 
4531   SDValue InChain = getRoot();
4532 
4533   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4534   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4535   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4536 
4537   MachineFunction &MF = DAG.getMachineFunction();
4538   MachineMemOperand *MMO = MF.getMachineMemOperand(
4539       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4540       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4541 
4542   SDValue L =
4543     DAG.getAtomic(NT, dl, MemVT, InChain,
4544                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4545                   MMO);
4546 
4547   SDValue OutChain = L.getValue(1);
4548 
4549   setValue(&I, L);
4550   DAG.setRoot(OutChain);
4551 }
4552 
4553 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4554   SDLoc dl = getCurSDLoc();
4555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4556   SDValue Ops[3];
4557   Ops[0] = getRoot();
4558   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4559                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4560   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4561                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4562   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4563 }
4564 
4565 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4566   SDLoc dl = getCurSDLoc();
4567   AtomicOrdering Order = I.getOrdering();
4568   SyncScope::ID SSID = I.getSyncScopeID();
4569 
4570   SDValue InChain = getRoot();
4571 
4572   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4573   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4574   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4575 
4576   if (!TLI.supportsUnalignedAtomics() &&
4577       I.getAlignment() < MemVT.getSizeInBits() / 8)
4578     report_fatal_error("Cannot generate unaligned atomic load");
4579 
4580   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4581 
4582   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4583       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4584       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4585 
4586   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4587 
4588   SDValue Ptr = getValue(I.getPointerOperand());
4589 
4590   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4591     // TODO: Once this is better exercised by tests, it should be merged with
4592     // the normal path for loads to prevent future divergence.
4593     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4594     if (MemVT != VT)
4595       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4596 
4597     setValue(&I, L);
4598     SDValue OutChain = L.getValue(1);
4599     if (!I.isUnordered())
4600       DAG.setRoot(OutChain);
4601     else
4602       PendingLoads.push_back(OutChain);
4603     return;
4604   }
4605 
4606   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4607                             Ptr, MMO);
4608 
4609   SDValue OutChain = L.getValue(1);
4610   if (MemVT != VT)
4611     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4612 
4613   setValue(&I, L);
4614   DAG.setRoot(OutChain);
4615 }
4616 
4617 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4618   SDLoc dl = getCurSDLoc();
4619 
4620   AtomicOrdering Ordering = I.getOrdering();
4621   SyncScope::ID SSID = I.getSyncScopeID();
4622 
4623   SDValue InChain = getRoot();
4624 
4625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4626   EVT MemVT =
4627       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4628 
4629   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4630     report_fatal_error("Cannot generate unaligned atomic store");
4631 
4632   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4633 
4634   MachineFunction &MF = DAG.getMachineFunction();
4635   MachineMemOperand *MMO = MF.getMachineMemOperand(
4636       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4637       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4638 
4639   SDValue Val = getValue(I.getValueOperand());
4640   if (Val.getValueType() != MemVT)
4641     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4642   SDValue Ptr = getValue(I.getPointerOperand());
4643 
4644   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4645     // TODO: Once this is better exercised by tests, it should be merged with
4646     // the normal path for stores to prevent future divergence.
4647     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4648     DAG.setRoot(S);
4649     return;
4650   }
4651   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4652                                    Ptr, Val, MMO);
4653 
4654 
4655   DAG.setRoot(OutChain);
4656 }
4657 
4658 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4659 /// node.
4660 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4661                                                unsigned Intrinsic) {
4662   // Ignore the callsite's attributes. A specific call site may be marked with
4663   // readnone, but the lowering code will expect the chain based on the
4664   // definition.
4665   const Function *F = I.getCalledFunction();
4666   bool HasChain = !F->doesNotAccessMemory();
4667   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4668 
4669   // Build the operand list.
4670   SmallVector<SDValue, 8> Ops;
4671   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4672     if (OnlyLoad) {
4673       // We don't need to serialize loads against other loads.
4674       Ops.push_back(DAG.getRoot());
4675     } else {
4676       Ops.push_back(getRoot());
4677     }
4678   }
4679 
4680   // Info is set by getTgtMemInstrinsic
4681   TargetLowering::IntrinsicInfo Info;
4682   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4683   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4684                                                DAG.getMachineFunction(),
4685                                                Intrinsic);
4686 
4687   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4688   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4689       Info.opc == ISD::INTRINSIC_W_CHAIN)
4690     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4691                                         TLI.getPointerTy(DAG.getDataLayout())));
4692 
4693   // Add all operands of the call to the operand list.
4694   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4695     const Value *Arg = I.getArgOperand(i);
4696     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4697       Ops.push_back(getValue(Arg));
4698       continue;
4699     }
4700 
4701     // Use TargetConstant instead of a regular constant for immarg.
4702     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4703     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4704       assert(CI->getBitWidth() <= 64 &&
4705              "large intrinsic immediates not handled");
4706       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4707     } else {
4708       Ops.push_back(
4709           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4710     }
4711   }
4712 
4713   SmallVector<EVT, 4> ValueVTs;
4714   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4715 
4716   if (HasChain)
4717     ValueVTs.push_back(MVT::Other);
4718 
4719   SDVTList VTs = DAG.getVTList(ValueVTs);
4720 
4721   // Create the node.
4722   SDValue Result;
4723   if (IsTgtIntrinsic) {
4724     // This is target intrinsic that touches memory
4725     AAMDNodes AAInfo;
4726     I.getAAMetadata(AAInfo);
4727     Result =
4728         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4729                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4730                                 Info.align, Info.flags, Info.size, AAInfo);
4731   } else if (!HasChain) {
4732     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4733   } else if (!I.getType()->isVoidTy()) {
4734     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4735   } else {
4736     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4737   }
4738 
4739   if (HasChain) {
4740     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4741     if (OnlyLoad)
4742       PendingLoads.push_back(Chain);
4743     else
4744       DAG.setRoot(Chain);
4745   }
4746 
4747   if (!I.getType()->isVoidTy()) {
4748     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4749       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4750       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4751     } else
4752       Result = lowerRangeToAssertZExt(DAG, I, Result);
4753 
4754     MaybeAlign Alignment = I.getRetAlign();
4755     if (!Alignment)
4756       Alignment = F->getAttributes().getRetAlignment();
4757     // Insert `assertalign` node if there's an alignment.
4758     if (InsertAssertAlign && Alignment) {
4759       Result =
4760           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4761     }
4762 
4763     setValue(&I, Result);
4764   }
4765 }
4766 
4767 /// GetSignificand - Get the significand and build it into a floating-point
4768 /// number with exponent of 1:
4769 ///
4770 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4771 ///
4772 /// where Op is the hexadecimal representation of floating point value.
4773 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4774   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4775                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4776   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4777                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4778   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4779 }
4780 
4781 /// GetExponent - Get the exponent:
4782 ///
4783 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4784 ///
4785 /// where Op is the hexadecimal representation of floating point value.
4786 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4787                            const TargetLowering &TLI, const SDLoc &dl) {
4788   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4789                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4790   SDValue t1 = DAG.getNode(
4791       ISD::SRL, dl, MVT::i32, t0,
4792       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4793   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4794                            DAG.getConstant(127, dl, MVT::i32));
4795   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4796 }
4797 
4798 /// getF32Constant - Get 32-bit floating point constant.
4799 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4800                               const SDLoc &dl) {
4801   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4802                            MVT::f32);
4803 }
4804 
4805 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4806                                        SelectionDAG &DAG) {
4807   // TODO: What fast-math-flags should be set on the floating-point nodes?
4808 
4809   //   IntegerPartOfX = ((int32_t)(t0);
4810   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4811 
4812   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4813   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4814   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4815 
4816   //   IntegerPartOfX <<= 23;
4817   IntegerPartOfX = DAG.getNode(
4818       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4819       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4820                                   DAG.getDataLayout())));
4821 
4822   SDValue TwoToFractionalPartOfX;
4823   if (LimitFloatPrecision <= 6) {
4824     // For floating-point precision of 6:
4825     //
4826     //   TwoToFractionalPartOfX =
4827     //     0.997535578f +
4828     //       (0.735607626f + 0.252464424f * x) * x;
4829     //
4830     // error 0.0144103317, which is 6 bits
4831     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4832                              getF32Constant(DAG, 0x3e814304, dl));
4833     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4834                              getF32Constant(DAG, 0x3f3c50c8, dl));
4835     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4836     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4837                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4838   } else if (LimitFloatPrecision <= 12) {
4839     // For floating-point precision of 12:
4840     //
4841     //   TwoToFractionalPartOfX =
4842     //     0.999892986f +
4843     //       (0.696457318f +
4844     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4845     //
4846     // error 0.000107046256, which is 13 to 14 bits
4847     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4848                              getF32Constant(DAG, 0x3da235e3, dl));
4849     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4850                              getF32Constant(DAG, 0x3e65b8f3, dl));
4851     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4852     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4853                              getF32Constant(DAG, 0x3f324b07, dl));
4854     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4855     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4856                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4857   } else { // LimitFloatPrecision <= 18
4858     // For floating-point precision of 18:
4859     //
4860     //   TwoToFractionalPartOfX =
4861     //     0.999999982f +
4862     //       (0.693148872f +
4863     //         (0.240227044f +
4864     //           (0.554906021e-1f +
4865     //             (0.961591928e-2f +
4866     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4867     // error 2.47208000*10^(-7), which is better than 18 bits
4868     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4869                              getF32Constant(DAG, 0x3924b03e, dl));
4870     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4871                              getF32Constant(DAG, 0x3ab24b87, dl));
4872     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4873     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4874                              getF32Constant(DAG, 0x3c1d8c17, dl));
4875     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4876     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4877                              getF32Constant(DAG, 0x3d634a1d, dl));
4878     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4879     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4880                              getF32Constant(DAG, 0x3e75fe14, dl));
4881     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4882     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4883                               getF32Constant(DAG, 0x3f317234, dl));
4884     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4885     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4886                                          getF32Constant(DAG, 0x3f800000, dl));
4887   }
4888 
4889   // Add the exponent into the result in integer domain.
4890   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4891   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4892                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4893 }
4894 
4895 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4896 /// limited-precision mode.
4897 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4898                          const TargetLowering &TLI) {
4899   if (Op.getValueType() == MVT::f32 &&
4900       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4901 
4902     // Put the exponent in the right bit position for later addition to the
4903     // final result:
4904     //
4905     // t0 = Op * log2(e)
4906 
4907     // TODO: What fast-math-flags should be set here?
4908     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4909                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4910     return getLimitedPrecisionExp2(t0, dl, DAG);
4911   }
4912 
4913   // No special expansion.
4914   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4915 }
4916 
4917 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4918 /// limited-precision mode.
4919 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4920                          const TargetLowering &TLI) {
4921   // TODO: What fast-math-flags should be set on the floating-point nodes?
4922 
4923   if (Op.getValueType() == MVT::f32 &&
4924       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4925     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4926 
4927     // Scale the exponent by log(2).
4928     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4929     SDValue LogOfExponent =
4930         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4931                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4932 
4933     // Get the significand and build it into a floating-point number with
4934     // exponent of 1.
4935     SDValue X = GetSignificand(DAG, Op1, dl);
4936 
4937     SDValue LogOfMantissa;
4938     if (LimitFloatPrecision <= 6) {
4939       // For floating-point precision of 6:
4940       //
4941       //   LogofMantissa =
4942       //     -1.1609546f +
4943       //       (1.4034025f - 0.23903021f * x) * x;
4944       //
4945       // error 0.0034276066, which is better than 8 bits
4946       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4947                                getF32Constant(DAG, 0xbe74c456, dl));
4948       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4949                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4950       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4951       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4952                                   getF32Constant(DAG, 0x3f949a29, dl));
4953     } else if (LimitFloatPrecision <= 12) {
4954       // For floating-point precision of 12:
4955       //
4956       //   LogOfMantissa =
4957       //     -1.7417939f +
4958       //       (2.8212026f +
4959       //         (-1.4699568f +
4960       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4961       //
4962       // error 0.000061011436, which is 14 bits
4963       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4964                                getF32Constant(DAG, 0xbd67b6d6, dl));
4965       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4966                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4967       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4968       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4969                                getF32Constant(DAG, 0x3fbc278b, dl));
4970       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4971       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4972                                getF32Constant(DAG, 0x40348e95, dl));
4973       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4974       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4975                                   getF32Constant(DAG, 0x3fdef31a, dl));
4976     } else { // LimitFloatPrecision <= 18
4977       // For floating-point precision of 18:
4978       //
4979       //   LogOfMantissa =
4980       //     -2.1072184f +
4981       //       (4.2372794f +
4982       //         (-3.7029485f +
4983       //           (2.2781945f +
4984       //             (-0.87823314f +
4985       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4986       //
4987       // error 0.0000023660568, which is better than 18 bits
4988       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4989                                getF32Constant(DAG, 0xbc91e5ac, dl));
4990       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4991                                getF32Constant(DAG, 0x3e4350aa, dl));
4992       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4993       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4994                                getF32Constant(DAG, 0x3f60d3e3, dl));
4995       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4996       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4997                                getF32Constant(DAG, 0x4011cdf0, dl));
4998       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4999       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5000                                getF32Constant(DAG, 0x406cfd1c, dl));
5001       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5002       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5003                                getF32Constant(DAG, 0x408797cb, dl));
5004       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5005       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5006                                   getF32Constant(DAG, 0x4006dcab, dl));
5007     }
5008 
5009     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5010   }
5011 
5012   // No special expansion.
5013   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5014 }
5015 
5016 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5017 /// limited-precision mode.
5018 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5019                           const TargetLowering &TLI) {
5020   // TODO: What fast-math-flags should be set on the floating-point nodes?
5021 
5022   if (Op.getValueType() == MVT::f32 &&
5023       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5024     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5025 
5026     // Get the exponent.
5027     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5028 
5029     // Get the significand and build it into a floating-point number with
5030     // exponent of 1.
5031     SDValue X = GetSignificand(DAG, Op1, dl);
5032 
5033     // Different possible minimax approximations of significand in
5034     // floating-point for various degrees of accuracy over [1,2].
5035     SDValue Log2ofMantissa;
5036     if (LimitFloatPrecision <= 6) {
5037       // For floating-point precision of 6:
5038       //
5039       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5040       //
5041       // error 0.0049451742, which is more than 7 bits
5042       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5043                                getF32Constant(DAG, 0xbeb08fe0, dl));
5044       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5045                                getF32Constant(DAG, 0x40019463, dl));
5046       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5047       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5048                                    getF32Constant(DAG, 0x3fd6633d, dl));
5049     } else if (LimitFloatPrecision <= 12) {
5050       // For floating-point precision of 12:
5051       //
5052       //   Log2ofMantissa =
5053       //     -2.51285454f +
5054       //       (4.07009056f +
5055       //         (-2.12067489f +
5056       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5057       //
5058       // error 0.0000876136000, which is better than 13 bits
5059       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5060                                getF32Constant(DAG, 0xbda7262e, dl));
5061       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5062                                getF32Constant(DAG, 0x3f25280b, dl));
5063       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5064       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5065                                getF32Constant(DAG, 0x4007b923, dl));
5066       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5067       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5068                                getF32Constant(DAG, 0x40823e2f, dl));
5069       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5070       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5071                                    getF32Constant(DAG, 0x4020d29c, dl));
5072     } else { // LimitFloatPrecision <= 18
5073       // For floating-point precision of 18:
5074       //
5075       //   Log2ofMantissa =
5076       //     -3.0400495f +
5077       //       (6.1129976f +
5078       //         (-5.3420409f +
5079       //           (3.2865683f +
5080       //             (-1.2669343f +
5081       //               (0.27515199f -
5082       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5083       //
5084       // error 0.0000018516, which is better than 18 bits
5085       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5086                                getF32Constant(DAG, 0xbcd2769e, dl));
5087       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5088                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5089       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5090       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5091                                getF32Constant(DAG, 0x3fa22ae7, dl));
5092       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5093       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5094                                getF32Constant(DAG, 0x40525723, dl));
5095       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5096       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5097                                getF32Constant(DAG, 0x40aaf200, dl));
5098       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5099       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5100                                getF32Constant(DAG, 0x40c39dad, dl));
5101       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5102       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5103                                    getF32Constant(DAG, 0x4042902c, dl));
5104     }
5105 
5106     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5107   }
5108 
5109   // No special expansion.
5110   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5111 }
5112 
5113 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5114 /// limited-precision mode.
5115 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5116                            const TargetLowering &TLI) {
5117   // TODO: What fast-math-flags should be set on the floating-point nodes?
5118 
5119   if (Op.getValueType() == MVT::f32 &&
5120       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5121     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5122 
5123     // Scale the exponent by log10(2) [0.30102999f].
5124     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5125     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5126                                         getF32Constant(DAG, 0x3e9a209a, dl));
5127 
5128     // Get the significand and build it into a floating-point number with
5129     // exponent of 1.
5130     SDValue X = GetSignificand(DAG, Op1, dl);
5131 
5132     SDValue Log10ofMantissa;
5133     if (LimitFloatPrecision <= 6) {
5134       // For floating-point precision of 6:
5135       //
5136       //   Log10ofMantissa =
5137       //     -0.50419619f +
5138       //       (0.60948995f - 0.10380950f * x) * x;
5139       //
5140       // error 0.0014886165, which is 6 bits
5141       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5142                                getF32Constant(DAG, 0xbdd49a13, dl));
5143       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5144                                getF32Constant(DAG, 0x3f1c0789, dl));
5145       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5146       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5147                                     getF32Constant(DAG, 0x3f011300, dl));
5148     } else if (LimitFloatPrecision <= 12) {
5149       // For floating-point precision of 12:
5150       //
5151       //   Log10ofMantissa =
5152       //     -0.64831180f +
5153       //       (0.91751397f +
5154       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5155       //
5156       // error 0.00019228036, which is better than 12 bits
5157       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5158                                getF32Constant(DAG, 0x3d431f31, dl));
5159       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5160                                getF32Constant(DAG, 0x3ea21fb2, dl));
5161       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5162       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5163                                getF32Constant(DAG, 0x3f6ae232, dl));
5164       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5165       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5166                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5167     } else { // LimitFloatPrecision <= 18
5168       // For floating-point precision of 18:
5169       //
5170       //   Log10ofMantissa =
5171       //     -0.84299375f +
5172       //       (1.5327582f +
5173       //         (-1.0688956f +
5174       //           (0.49102474f +
5175       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5176       //
5177       // error 0.0000037995730, which is better than 18 bits
5178       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5179                                getF32Constant(DAG, 0x3c5d51ce, dl));
5180       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5181                                getF32Constant(DAG, 0x3e00685a, dl));
5182       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5183       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5184                                getF32Constant(DAG, 0x3efb6798, dl));
5185       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5186       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5187                                getF32Constant(DAG, 0x3f88d192, dl));
5188       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5189       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5190                                getF32Constant(DAG, 0x3fc4316c, dl));
5191       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5192       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5193                                     getF32Constant(DAG, 0x3f57ce70, dl));
5194     }
5195 
5196     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5197   }
5198 
5199   // No special expansion.
5200   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5201 }
5202 
5203 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5204 /// limited-precision mode.
5205 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5206                           const TargetLowering &TLI) {
5207   if (Op.getValueType() == MVT::f32 &&
5208       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5209     return getLimitedPrecisionExp2(Op, dl, DAG);
5210 
5211   // No special expansion.
5212   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5213 }
5214 
5215 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5216 /// limited-precision mode with x == 10.0f.
5217 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5218                          SelectionDAG &DAG, const TargetLowering &TLI) {
5219   bool IsExp10 = false;
5220   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5221       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5222     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5223       APFloat Ten(10.0f);
5224       IsExp10 = LHSC->isExactlyValue(Ten);
5225     }
5226   }
5227 
5228   // TODO: What fast-math-flags should be set on the FMUL node?
5229   if (IsExp10) {
5230     // Put the exponent in the right bit position for later addition to the
5231     // final result:
5232     //
5233     //   #define LOG2OF10 3.3219281f
5234     //   t0 = Op * LOG2OF10;
5235     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5236                              getF32Constant(DAG, 0x40549a78, dl));
5237     return getLimitedPrecisionExp2(t0, dl, DAG);
5238   }
5239 
5240   // No special expansion.
5241   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5242 }
5243 
5244 /// ExpandPowI - Expand a llvm.powi intrinsic.
5245 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5246                           SelectionDAG &DAG) {
5247   // If RHS is a constant, we can expand this out to a multiplication tree,
5248   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5249   // optimizing for size, we only want to do this if the expansion would produce
5250   // a small number of multiplies, otherwise we do the full expansion.
5251   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5252     // Get the exponent as a positive value.
5253     unsigned Val = RHSC->getSExtValue();
5254     if ((int)Val < 0) Val = -Val;
5255 
5256     // powi(x, 0) -> 1.0
5257     if (Val == 0)
5258       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5259 
5260     bool OptForSize = DAG.shouldOptForSize();
5261     if (!OptForSize ||
5262         // If optimizing for size, don't insert too many multiplies.
5263         // This inserts up to 5 multiplies.
5264         countPopulation(Val) + Log2_32(Val) < 7) {
5265       // We use the simple binary decomposition method to generate the multiply
5266       // sequence.  There are more optimal ways to do this (for example,
5267       // powi(x,15) generates one more multiply than it should), but this has
5268       // the benefit of being both really simple and much better than a libcall.
5269       SDValue Res;  // Logically starts equal to 1.0
5270       SDValue CurSquare = LHS;
5271       // TODO: Intrinsics should have fast-math-flags that propagate to these
5272       // nodes.
5273       while (Val) {
5274         if (Val & 1) {
5275           if (Res.getNode())
5276             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5277           else
5278             Res = CurSquare;  // 1.0*CurSquare.
5279         }
5280 
5281         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5282                                 CurSquare, CurSquare);
5283         Val >>= 1;
5284       }
5285 
5286       // If the original was negative, invert the result, producing 1/(x*x*x).
5287       if (RHSC->getSExtValue() < 0)
5288         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5289                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5290       return Res;
5291     }
5292   }
5293 
5294   // Otherwise, expand to a libcall.
5295   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5296 }
5297 
5298 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5299                             SDValue LHS, SDValue RHS, SDValue Scale,
5300                             SelectionDAG &DAG, const TargetLowering &TLI) {
5301   EVT VT = LHS.getValueType();
5302   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5303   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5304   LLVMContext &Ctx = *DAG.getContext();
5305 
5306   // If the type is legal but the operation isn't, this node might survive all
5307   // the way to operation legalization. If we end up there and we do not have
5308   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5309   // node.
5310 
5311   // Coax the legalizer into expanding the node during type legalization instead
5312   // by bumping the size by one bit. This will force it to Promote, enabling the
5313   // early expansion and avoiding the need to expand later.
5314 
5315   // We don't have to do this if Scale is 0; that can always be expanded, unless
5316   // it's a saturating signed operation. Those can experience true integer
5317   // division overflow, a case which we must avoid.
5318 
5319   // FIXME: We wouldn't have to do this (or any of the early
5320   // expansion/promotion) if it was possible to expand a libcall of an
5321   // illegal type during operation legalization. But it's not, so things
5322   // get a bit hacky.
5323   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5324   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5325       (TLI.isTypeLegal(VT) ||
5326        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5327     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5328         Opcode, VT, ScaleInt);
5329     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5330       EVT PromVT;
5331       if (VT.isScalarInteger())
5332         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5333       else if (VT.isVector()) {
5334         PromVT = VT.getVectorElementType();
5335         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5336         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5337       } else
5338         llvm_unreachable("Wrong VT for DIVFIX?");
5339       if (Signed) {
5340         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5341         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5342       } else {
5343         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5344         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5345       }
5346       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5347       // For saturating operations, we need to shift up the LHS to get the
5348       // proper saturation width, and then shift down again afterwards.
5349       if (Saturating)
5350         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5351                           DAG.getConstant(1, DL, ShiftTy));
5352       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5353       if (Saturating)
5354         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5355                           DAG.getConstant(1, DL, ShiftTy));
5356       return DAG.getZExtOrTrunc(Res, DL, VT);
5357     }
5358   }
5359 
5360   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5361 }
5362 
5363 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5364 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5365 static void
5366 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5367                      const SDValue &N) {
5368   switch (N.getOpcode()) {
5369   case ISD::CopyFromReg: {
5370     SDValue Op = N.getOperand(1);
5371     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5372                       Op.getValueType().getSizeInBits());
5373     return;
5374   }
5375   case ISD::BITCAST:
5376   case ISD::AssertZext:
5377   case ISD::AssertSext:
5378   case ISD::TRUNCATE:
5379     getUnderlyingArgRegs(Regs, N.getOperand(0));
5380     return;
5381   case ISD::BUILD_PAIR:
5382   case ISD::BUILD_VECTOR:
5383   case ISD::CONCAT_VECTORS:
5384     for (SDValue Op : N->op_values())
5385       getUnderlyingArgRegs(Regs, Op);
5386     return;
5387   default:
5388     return;
5389   }
5390 }
5391 
5392 /// If the DbgValueInst is a dbg_value of a function argument, create the
5393 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5394 /// instruction selection, they will be inserted to the entry BB.
5395 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5396     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5397     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5398   const Argument *Arg = dyn_cast<Argument>(V);
5399   if (!Arg)
5400     return false;
5401 
5402   if (!IsDbgDeclare) {
5403     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5404     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5405     // the entry block.
5406     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5407     if (!IsInEntryBlock)
5408       return false;
5409 
5410     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5411     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5412     // variable that also is a param.
5413     //
5414     // Although, if we are at the top of the entry block already, we can still
5415     // emit using ArgDbgValue. This might catch some situations when the
5416     // dbg.value refers to an argument that isn't used in the entry block, so
5417     // any CopyToReg node would be optimized out and the only way to express
5418     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5419     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5420     // we should only emit as ArgDbgValue if the Variable is an argument to the
5421     // current function, and the dbg.value intrinsic is found in the entry
5422     // block.
5423     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5424         !DL->getInlinedAt();
5425     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5426     if (!IsInPrologue && !VariableIsFunctionInputArg)
5427       return false;
5428 
5429     // Here we assume that a function argument on IR level only can be used to
5430     // describe one input parameter on source level. If we for example have
5431     // source code like this
5432     //
5433     //    struct A { long x, y; };
5434     //    void foo(struct A a, long b) {
5435     //      ...
5436     //      b = a.x;
5437     //      ...
5438     //    }
5439     //
5440     // and IR like this
5441     //
5442     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5443     //  entry:
5444     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5445     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5446     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5447     //    ...
5448     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5449     //    ...
5450     //
5451     // then the last dbg.value is describing a parameter "b" using a value that
5452     // is an argument. But since we already has used %a1 to describe a parameter
5453     // we should not handle that last dbg.value here (that would result in an
5454     // incorrect hoisting of the DBG_VALUE to the function entry).
5455     // Notice that we allow one dbg.value per IR level argument, to accommodate
5456     // for the situation with fragments above.
5457     if (VariableIsFunctionInputArg) {
5458       unsigned ArgNo = Arg->getArgNo();
5459       if (ArgNo >= FuncInfo.DescribedArgs.size())
5460         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5461       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5462         return false;
5463       FuncInfo.DescribedArgs.set(ArgNo);
5464     }
5465   }
5466 
5467   MachineFunction &MF = DAG.getMachineFunction();
5468   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5469 
5470   bool IsIndirect = false;
5471   Optional<MachineOperand> Op;
5472   // Some arguments' frame index is recorded during argument lowering.
5473   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5474   if (FI != std::numeric_limits<int>::max())
5475     Op = MachineOperand::CreateFI(FI);
5476 
5477   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5478   if (!Op && N.getNode()) {
5479     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5480     Register Reg;
5481     if (ArgRegsAndSizes.size() == 1)
5482       Reg = ArgRegsAndSizes.front().first;
5483 
5484     if (Reg && Reg.isVirtual()) {
5485       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5486       Register PR = RegInfo.getLiveInPhysReg(Reg);
5487       if (PR)
5488         Reg = PR;
5489     }
5490     if (Reg) {
5491       Op = MachineOperand::CreateReg(Reg, false);
5492       IsIndirect = IsDbgDeclare;
5493     }
5494   }
5495 
5496   if (!Op && N.getNode()) {
5497     // Check if frame index is available.
5498     SDValue LCandidate = peekThroughBitcasts(N);
5499     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5500       if (FrameIndexSDNode *FINode =
5501           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5502         Op = MachineOperand::CreateFI(FINode->getIndex());
5503   }
5504 
5505   if (!Op) {
5506     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5507     auto splitMultiRegDbgValue
5508       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5509       unsigned Offset = 0;
5510       for (auto RegAndSize : SplitRegs) {
5511         // If the expression is already a fragment, the current register
5512         // offset+size might extend beyond the fragment. In this case, only
5513         // the register bits that are inside the fragment are relevant.
5514         int RegFragmentSizeInBits = RegAndSize.second;
5515         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5516           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5517           // The register is entirely outside the expression fragment,
5518           // so is irrelevant for debug info.
5519           if (Offset >= ExprFragmentSizeInBits)
5520             break;
5521           // The register is partially outside the expression fragment, only
5522           // the low bits within the fragment are relevant for debug info.
5523           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5524             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5525           }
5526         }
5527 
5528         auto FragmentExpr = DIExpression::createFragmentExpression(
5529             Expr, Offset, RegFragmentSizeInBits);
5530         Offset += RegAndSize.second;
5531         // If a valid fragment expression cannot be created, the variable's
5532         // correct value cannot be determined and so it is set as Undef.
5533         if (!FragmentExpr) {
5534           SDDbgValue *SDV = DAG.getConstantDbgValue(
5535               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5536           DAG.AddDbgValue(SDV, nullptr, false);
5537           continue;
5538         }
5539         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5540         FuncInfo.ArgDbgValues.push_back(
5541           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5542                   RegAndSize.first, Variable, *FragmentExpr));
5543       }
5544     };
5545 
5546     // Check if ValueMap has reg number.
5547     DenseMap<const Value *, Register>::const_iterator
5548       VMI = FuncInfo.ValueMap.find(V);
5549     if (VMI != FuncInfo.ValueMap.end()) {
5550       const auto &TLI = DAG.getTargetLoweringInfo();
5551       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5552                        V->getType(), getABIRegCopyCC(V));
5553       if (RFV.occupiesMultipleRegs()) {
5554         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5555         return true;
5556       }
5557 
5558       Op = MachineOperand::CreateReg(VMI->second, false);
5559       IsIndirect = IsDbgDeclare;
5560     } else if (ArgRegsAndSizes.size() > 1) {
5561       // This was split due to the calling convention, and no virtual register
5562       // mapping exists for the value.
5563       splitMultiRegDbgValue(ArgRegsAndSizes);
5564       return true;
5565     }
5566   }
5567 
5568   if (!Op)
5569     return false;
5570 
5571   assert(Variable->isValidLocationForIntrinsic(DL) &&
5572          "Expected inlined-at fields to agree");
5573   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5574   FuncInfo.ArgDbgValues.push_back(
5575       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5576               *Op, Variable, Expr));
5577 
5578   return true;
5579 }
5580 
5581 /// Return the appropriate SDDbgValue based on N.
5582 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5583                                              DILocalVariable *Variable,
5584                                              DIExpression *Expr,
5585                                              const DebugLoc &dl,
5586                                              unsigned DbgSDNodeOrder) {
5587   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5588     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5589     // stack slot locations.
5590     //
5591     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5592     // debug values here after optimization:
5593     //
5594     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5595     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5596     //
5597     // Both describe the direct values of their associated variables.
5598     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5599                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5600   }
5601   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5602                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5603 }
5604 
5605 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5606   switch (Intrinsic) {
5607   case Intrinsic::smul_fix:
5608     return ISD::SMULFIX;
5609   case Intrinsic::umul_fix:
5610     return ISD::UMULFIX;
5611   case Intrinsic::smul_fix_sat:
5612     return ISD::SMULFIXSAT;
5613   case Intrinsic::umul_fix_sat:
5614     return ISD::UMULFIXSAT;
5615   case Intrinsic::sdiv_fix:
5616     return ISD::SDIVFIX;
5617   case Intrinsic::udiv_fix:
5618     return ISD::UDIVFIX;
5619   case Intrinsic::sdiv_fix_sat:
5620     return ISD::SDIVFIXSAT;
5621   case Intrinsic::udiv_fix_sat:
5622     return ISD::UDIVFIXSAT;
5623   default:
5624     llvm_unreachable("Unhandled fixed point intrinsic");
5625   }
5626 }
5627 
5628 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5629                                            const char *FunctionName) {
5630   assert(FunctionName && "FunctionName must not be nullptr");
5631   SDValue Callee = DAG.getExternalSymbol(
5632       FunctionName,
5633       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5634   LowerCallTo(I, Callee, I.isTailCall());
5635 }
5636 
5637 /// Given a @llvm.call.preallocated.setup, return the corresponding
5638 /// preallocated call.
5639 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5640   assert(cast<CallBase>(PreallocatedSetup)
5641                  ->getCalledFunction()
5642                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5643          "expected call_preallocated_setup Value");
5644   for (auto *U : PreallocatedSetup->users()) {
5645     auto *UseCall = cast<CallBase>(U);
5646     const Function *Fn = UseCall->getCalledFunction();
5647     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5648       return UseCall;
5649     }
5650   }
5651   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5652 }
5653 
5654 /// Lower the call to the specified intrinsic function.
5655 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5656                                              unsigned Intrinsic) {
5657   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5658   SDLoc sdl = getCurSDLoc();
5659   DebugLoc dl = getCurDebugLoc();
5660   SDValue Res;
5661 
5662   switch (Intrinsic) {
5663   default:
5664     // By default, turn this into a target intrinsic node.
5665     visitTargetIntrinsic(I, Intrinsic);
5666     return;
5667   case Intrinsic::vscale: {
5668     match(&I, m_VScale(DAG.getDataLayout()));
5669     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5670     setValue(&I,
5671              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5672     return;
5673   }
5674   case Intrinsic::vastart:  visitVAStart(I); return;
5675   case Intrinsic::vaend:    visitVAEnd(I); return;
5676   case Intrinsic::vacopy:   visitVACopy(I); return;
5677   case Intrinsic::returnaddress:
5678     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5679                              TLI.getPointerTy(DAG.getDataLayout()),
5680                              getValue(I.getArgOperand(0))));
5681     return;
5682   case Intrinsic::addressofreturnaddress:
5683     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5684                              TLI.getPointerTy(DAG.getDataLayout())));
5685     return;
5686   case Intrinsic::sponentry:
5687     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5688                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5689     return;
5690   case Intrinsic::frameaddress:
5691     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5692                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5693                              getValue(I.getArgOperand(0))));
5694     return;
5695   case Intrinsic::read_register: {
5696     Value *Reg = I.getArgOperand(0);
5697     SDValue Chain = getRoot();
5698     SDValue RegName =
5699         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5700     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5701     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5702       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5703     setValue(&I, Res);
5704     DAG.setRoot(Res.getValue(1));
5705     return;
5706   }
5707   case Intrinsic::write_register: {
5708     Value *Reg = I.getArgOperand(0);
5709     Value *RegValue = I.getArgOperand(1);
5710     SDValue Chain = getRoot();
5711     SDValue RegName =
5712         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5713     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5714                             RegName, getValue(RegValue)));
5715     return;
5716   }
5717   case Intrinsic::memcpy: {
5718     const auto &MCI = cast<MemCpyInst>(I);
5719     SDValue Op1 = getValue(I.getArgOperand(0));
5720     SDValue Op2 = getValue(I.getArgOperand(1));
5721     SDValue Op3 = getValue(I.getArgOperand(2));
5722     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5723     Align DstAlign = MCI.getDestAlign().valueOrOne();
5724     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5725     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5726     bool isVol = MCI.isVolatile();
5727     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5728     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5729     // node.
5730     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5731     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5732                                /* AlwaysInline */ false, isTC,
5733                                MachinePointerInfo(I.getArgOperand(0)),
5734                                MachinePointerInfo(I.getArgOperand(1)));
5735     updateDAGForMaybeTailCall(MC);
5736     return;
5737   }
5738   case Intrinsic::memcpy_inline: {
5739     const auto &MCI = cast<MemCpyInlineInst>(I);
5740     SDValue Dst = getValue(I.getArgOperand(0));
5741     SDValue Src = getValue(I.getArgOperand(1));
5742     SDValue Size = getValue(I.getArgOperand(2));
5743     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5744     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5745     Align DstAlign = MCI.getDestAlign().valueOrOne();
5746     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5747     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5748     bool isVol = MCI.isVolatile();
5749     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5750     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5751     // node.
5752     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5753                                /* AlwaysInline */ true, isTC,
5754                                MachinePointerInfo(I.getArgOperand(0)),
5755                                MachinePointerInfo(I.getArgOperand(1)));
5756     updateDAGForMaybeTailCall(MC);
5757     return;
5758   }
5759   case Intrinsic::memset: {
5760     const auto &MSI = cast<MemSetInst>(I);
5761     SDValue Op1 = getValue(I.getArgOperand(0));
5762     SDValue Op2 = getValue(I.getArgOperand(1));
5763     SDValue Op3 = getValue(I.getArgOperand(2));
5764     // @llvm.memset defines 0 and 1 to both mean no alignment.
5765     Align Alignment = MSI.getDestAlign().valueOrOne();
5766     bool isVol = MSI.isVolatile();
5767     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5768     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5769     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5770                                MachinePointerInfo(I.getArgOperand(0)));
5771     updateDAGForMaybeTailCall(MS);
5772     return;
5773   }
5774   case Intrinsic::memmove: {
5775     const auto &MMI = cast<MemMoveInst>(I);
5776     SDValue Op1 = getValue(I.getArgOperand(0));
5777     SDValue Op2 = getValue(I.getArgOperand(1));
5778     SDValue Op3 = getValue(I.getArgOperand(2));
5779     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5780     Align DstAlign = MMI.getDestAlign().valueOrOne();
5781     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5782     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5783     bool isVol = MMI.isVolatile();
5784     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5785     // FIXME: Support passing different dest/src alignments to the memmove DAG
5786     // node.
5787     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5788     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5789                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5790                                 MachinePointerInfo(I.getArgOperand(1)));
5791     updateDAGForMaybeTailCall(MM);
5792     return;
5793   }
5794   case Intrinsic::memcpy_element_unordered_atomic: {
5795     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5796     SDValue Dst = getValue(MI.getRawDest());
5797     SDValue Src = getValue(MI.getRawSource());
5798     SDValue Length = getValue(MI.getLength());
5799 
5800     unsigned DstAlign = MI.getDestAlignment();
5801     unsigned SrcAlign = MI.getSourceAlignment();
5802     Type *LengthTy = MI.getLength()->getType();
5803     unsigned ElemSz = MI.getElementSizeInBytes();
5804     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5805     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5806                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5807                                      MachinePointerInfo(MI.getRawDest()),
5808                                      MachinePointerInfo(MI.getRawSource()));
5809     updateDAGForMaybeTailCall(MC);
5810     return;
5811   }
5812   case Intrinsic::memmove_element_unordered_atomic: {
5813     auto &MI = cast<AtomicMemMoveInst>(I);
5814     SDValue Dst = getValue(MI.getRawDest());
5815     SDValue Src = getValue(MI.getRawSource());
5816     SDValue Length = getValue(MI.getLength());
5817 
5818     unsigned DstAlign = MI.getDestAlignment();
5819     unsigned SrcAlign = MI.getSourceAlignment();
5820     Type *LengthTy = MI.getLength()->getType();
5821     unsigned ElemSz = MI.getElementSizeInBytes();
5822     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5823     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5824                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5825                                       MachinePointerInfo(MI.getRawDest()),
5826                                       MachinePointerInfo(MI.getRawSource()));
5827     updateDAGForMaybeTailCall(MC);
5828     return;
5829   }
5830   case Intrinsic::memset_element_unordered_atomic: {
5831     auto &MI = cast<AtomicMemSetInst>(I);
5832     SDValue Dst = getValue(MI.getRawDest());
5833     SDValue Val = getValue(MI.getValue());
5834     SDValue Length = getValue(MI.getLength());
5835 
5836     unsigned DstAlign = MI.getDestAlignment();
5837     Type *LengthTy = MI.getLength()->getType();
5838     unsigned ElemSz = MI.getElementSizeInBytes();
5839     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5840     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5841                                      LengthTy, ElemSz, isTC,
5842                                      MachinePointerInfo(MI.getRawDest()));
5843     updateDAGForMaybeTailCall(MC);
5844     return;
5845   }
5846   case Intrinsic::call_preallocated_setup: {
5847     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5848     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5849     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5850                               getRoot(), SrcValue);
5851     setValue(&I, Res);
5852     DAG.setRoot(Res);
5853     return;
5854   }
5855   case Intrinsic::call_preallocated_arg: {
5856     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5857     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5858     SDValue Ops[3];
5859     Ops[0] = getRoot();
5860     Ops[1] = SrcValue;
5861     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5862                                    MVT::i32); // arg index
5863     SDValue Res = DAG.getNode(
5864         ISD::PREALLOCATED_ARG, sdl,
5865         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5866     setValue(&I, Res);
5867     DAG.setRoot(Res.getValue(1));
5868     return;
5869   }
5870   case Intrinsic::dbg_addr:
5871   case Intrinsic::dbg_declare: {
5872     const auto &DI = cast<DbgVariableIntrinsic>(I);
5873     DILocalVariable *Variable = DI.getVariable();
5874     DIExpression *Expression = DI.getExpression();
5875     dropDanglingDebugInfo(Variable, Expression);
5876     assert(Variable && "Missing variable");
5877     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5878                       << "\n");
5879     // Check if address has undef value.
5880     const Value *Address = DI.getVariableLocation();
5881     if (!Address || isa<UndefValue>(Address) ||
5882         (Address->use_empty() && !isa<Argument>(Address))) {
5883       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5884                         << " (bad/undef/unused-arg address)\n");
5885       return;
5886     }
5887 
5888     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5889 
5890     // Check if this variable can be described by a frame index, typically
5891     // either as a static alloca or a byval parameter.
5892     int FI = std::numeric_limits<int>::max();
5893     if (const auto *AI =
5894             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5895       if (AI->isStaticAlloca()) {
5896         auto I = FuncInfo.StaticAllocaMap.find(AI);
5897         if (I != FuncInfo.StaticAllocaMap.end())
5898           FI = I->second;
5899       }
5900     } else if (const auto *Arg = dyn_cast<Argument>(
5901                    Address->stripInBoundsConstantOffsets())) {
5902       FI = FuncInfo.getArgumentFrameIndex(Arg);
5903     }
5904 
5905     // llvm.dbg.addr is control dependent and always generates indirect
5906     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5907     // the MachineFunction variable table.
5908     if (FI != std::numeric_limits<int>::max()) {
5909       if (Intrinsic == Intrinsic::dbg_addr) {
5910         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5911             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5912         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5913       } else {
5914         LLVM_DEBUG(dbgs() << "Skipping " << DI
5915                           << " (variable info stashed in MF side table)\n");
5916       }
5917       return;
5918     }
5919 
5920     SDValue &N = NodeMap[Address];
5921     if (!N.getNode() && isa<Argument>(Address))
5922       // Check unused arguments map.
5923       N = UnusedArgNodeMap[Address];
5924     SDDbgValue *SDV;
5925     if (N.getNode()) {
5926       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5927         Address = BCI->getOperand(0);
5928       // Parameters are handled specially.
5929       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5930       if (isParameter && FINode) {
5931         // Byval parameter. We have a frame index at this point.
5932         SDV =
5933             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5934                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5935       } else if (isa<Argument>(Address)) {
5936         // Address is an argument, so try to emit its dbg value using
5937         // virtual register info from the FuncInfo.ValueMap.
5938         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5939         return;
5940       } else {
5941         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5942                               true, dl, SDNodeOrder);
5943       }
5944       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5945     } else {
5946       // If Address is an argument then try to emit its dbg value using
5947       // virtual register info from the FuncInfo.ValueMap.
5948       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5949                                     N)) {
5950         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5951                           << " (could not emit func-arg dbg_value)\n");
5952       }
5953     }
5954     return;
5955   }
5956   case Intrinsic::dbg_label: {
5957     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5958     DILabel *Label = DI.getLabel();
5959     assert(Label && "Missing label");
5960 
5961     SDDbgLabel *SDV;
5962     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5963     DAG.AddDbgLabel(SDV);
5964     return;
5965   }
5966   case Intrinsic::dbg_value: {
5967     const DbgValueInst &DI = cast<DbgValueInst>(I);
5968     assert(DI.getVariable() && "Missing variable");
5969 
5970     DILocalVariable *Variable = DI.getVariable();
5971     DIExpression *Expression = DI.getExpression();
5972     dropDanglingDebugInfo(Variable, Expression);
5973     const Value *V = DI.getValue();
5974     if (!V)
5975       return;
5976 
5977     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5978         SDNodeOrder))
5979       return;
5980 
5981     // TODO: Dangling debug info will eventually either be resolved or produce
5982     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5983     // between the original dbg.value location and its resolved DBG_VALUE, which
5984     // we should ideally fill with an extra Undef DBG_VALUE.
5985 
5986     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5987     return;
5988   }
5989 
5990   case Intrinsic::eh_typeid_for: {
5991     // Find the type id for the given typeinfo.
5992     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5993     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5994     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5995     setValue(&I, Res);
5996     return;
5997   }
5998 
5999   case Intrinsic::eh_return_i32:
6000   case Intrinsic::eh_return_i64:
6001     DAG.getMachineFunction().setCallsEHReturn(true);
6002     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6003                             MVT::Other,
6004                             getControlRoot(),
6005                             getValue(I.getArgOperand(0)),
6006                             getValue(I.getArgOperand(1))));
6007     return;
6008   case Intrinsic::eh_unwind_init:
6009     DAG.getMachineFunction().setCallsUnwindInit(true);
6010     return;
6011   case Intrinsic::eh_dwarf_cfa:
6012     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6013                              TLI.getPointerTy(DAG.getDataLayout()),
6014                              getValue(I.getArgOperand(0))));
6015     return;
6016   case Intrinsic::eh_sjlj_callsite: {
6017     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6018     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6019     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6020     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6021 
6022     MMI.setCurrentCallSite(CI->getZExtValue());
6023     return;
6024   }
6025   case Intrinsic::eh_sjlj_functioncontext: {
6026     // Get and store the index of the function context.
6027     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6028     AllocaInst *FnCtx =
6029       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6030     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6031     MFI.setFunctionContextIndex(FI);
6032     return;
6033   }
6034   case Intrinsic::eh_sjlj_setjmp: {
6035     SDValue Ops[2];
6036     Ops[0] = getRoot();
6037     Ops[1] = getValue(I.getArgOperand(0));
6038     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6039                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6040     setValue(&I, Op.getValue(0));
6041     DAG.setRoot(Op.getValue(1));
6042     return;
6043   }
6044   case Intrinsic::eh_sjlj_longjmp:
6045     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6046                             getRoot(), getValue(I.getArgOperand(0))));
6047     return;
6048   case Intrinsic::eh_sjlj_setup_dispatch:
6049     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6050                             getRoot()));
6051     return;
6052   case Intrinsic::masked_gather:
6053     visitMaskedGather(I);
6054     return;
6055   case Intrinsic::masked_load:
6056     visitMaskedLoad(I);
6057     return;
6058   case Intrinsic::masked_scatter:
6059     visitMaskedScatter(I);
6060     return;
6061   case Intrinsic::masked_store:
6062     visitMaskedStore(I);
6063     return;
6064   case Intrinsic::masked_expandload:
6065     visitMaskedLoad(I, true /* IsExpanding */);
6066     return;
6067   case Intrinsic::masked_compressstore:
6068     visitMaskedStore(I, true /* IsCompressing */);
6069     return;
6070   case Intrinsic::powi:
6071     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6072                             getValue(I.getArgOperand(1)), DAG));
6073     return;
6074   case Intrinsic::log:
6075     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6076     return;
6077   case Intrinsic::log2:
6078     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6079     return;
6080   case Intrinsic::log10:
6081     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6082     return;
6083   case Intrinsic::exp:
6084     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6085     return;
6086   case Intrinsic::exp2:
6087     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6088     return;
6089   case Intrinsic::pow:
6090     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6091                            getValue(I.getArgOperand(1)), DAG, TLI));
6092     return;
6093   case Intrinsic::sqrt:
6094   case Intrinsic::fabs:
6095   case Intrinsic::sin:
6096   case Intrinsic::cos:
6097   case Intrinsic::floor:
6098   case Intrinsic::ceil:
6099   case Intrinsic::trunc:
6100   case Intrinsic::rint:
6101   case Intrinsic::nearbyint:
6102   case Intrinsic::round:
6103   case Intrinsic::roundeven:
6104   case Intrinsic::canonicalize: {
6105     unsigned Opcode;
6106     switch (Intrinsic) {
6107     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6108     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6109     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6110     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6111     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6112     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6113     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6114     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6115     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6116     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6117     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6118     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6119     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6120     }
6121 
6122     setValue(&I, DAG.getNode(Opcode, sdl,
6123                              getValue(I.getArgOperand(0)).getValueType(),
6124                              getValue(I.getArgOperand(0))));
6125     return;
6126   }
6127   case Intrinsic::lround:
6128   case Intrinsic::llround:
6129   case Intrinsic::lrint:
6130   case Intrinsic::llrint: {
6131     unsigned Opcode;
6132     switch (Intrinsic) {
6133     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6134     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6135     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6136     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6137     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6138     }
6139 
6140     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6141     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6142                              getValue(I.getArgOperand(0))));
6143     return;
6144   }
6145   case Intrinsic::minnum:
6146     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6147                              getValue(I.getArgOperand(0)).getValueType(),
6148                              getValue(I.getArgOperand(0)),
6149                              getValue(I.getArgOperand(1))));
6150     return;
6151   case Intrinsic::maxnum:
6152     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6153                              getValue(I.getArgOperand(0)).getValueType(),
6154                              getValue(I.getArgOperand(0)),
6155                              getValue(I.getArgOperand(1))));
6156     return;
6157   case Intrinsic::minimum:
6158     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6159                              getValue(I.getArgOperand(0)).getValueType(),
6160                              getValue(I.getArgOperand(0)),
6161                              getValue(I.getArgOperand(1))));
6162     return;
6163   case Intrinsic::maximum:
6164     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6165                              getValue(I.getArgOperand(0)).getValueType(),
6166                              getValue(I.getArgOperand(0)),
6167                              getValue(I.getArgOperand(1))));
6168     return;
6169   case Intrinsic::copysign:
6170     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6171                              getValue(I.getArgOperand(0)).getValueType(),
6172                              getValue(I.getArgOperand(0)),
6173                              getValue(I.getArgOperand(1))));
6174     return;
6175   case Intrinsic::fma:
6176     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6177                              getValue(I.getArgOperand(0)).getValueType(),
6178                              getValue(I.getArgOperand(0)),
6179                              getValue(I.getArgOperand(1)),
6180                              getValue(I.getArgOperand(2))));
6181     return;
6182 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6183   case Intrinsic::INTRINSIC:
6184 #include "llvm/IR/ConstrainedOps.def"
6185     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6186     return;
6187   case Intrinsic::fmuladd: {
6188     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6189     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6190         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6191       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6192                                getValue(I.getArgOperand(0)).getValueType(),
6193                                getValue(I.getArgOperand(0)),
6194                                getValue(I.getArgOperand(1)),
6195                                getValue(I.getArgOperand(2))));
6196     } else {
6197       // TODO: Intrinsic calls should have fast-math-flags.
6198       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6199                                 getValue(I.getArgOperand(0)).getValueType(),
6200                                 getValue(I.getArgOperand(0)),
6201                                 getValue(I.getArgOperand(1)));
6202       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6203                                 getValue(I.getArgOperand(0)).getValueType(),
6204                                 Mul,
6205                                 getValue(I.getArgOperand(2)));
6206       setValue(&I, Add);
6207     }
6208     return;
6209   }
6210   case Intrinsic::convert_to_fp16:
6211     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6212                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6213                                          getValue(I.getArgOperand(0)),
6214                                          DAG.getTargetConstant(0, sdl,
6215                                                                MVT::i32))));
6216     return;
6217   case Intrinsic::convert_from_fp16:
6218     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6219                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6220                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6221                                          getValue(I.getArgOperand(0)))));
6222     return;
6223   case Intrinsic::pcmarker: {
6224     SDValue Tmp = getValue(I.getArgOperand(0));
6225     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6226     return;
6227   }
6228   case Intrinsic::readcyclecounter: {
6229     SDValue Op = getRoot();
6230     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6231                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6232     setValue(&I, Res);
6233     DAG.setRoot(Res.getValue(1));
6234     return;
6235   }
6236   case Intrinsic::bitreverse:
6237     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6238                              getValue(I.getArgOperand(0)).getValueType(),
6239                              getValue(I.getArgOperand(0))));
6240     return;
6241   case Intrinsic::bswap:
6242     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6243                              getValue(I.getArgOperand(0)).getValueType(),
6244                              getValue(I.getArgOperand(0))));
6245     return;
6246   case Intrinsic::cttz: {
6247     SDValue Arg = getValue(I.getArgOperand(0));
6248     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6249     EVT Ty = Arg.getValueType();
6250     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6251                              sdl, Ty, Arg));
6252     return;
6253   }
6254   case Intrinsic::ctlz: {
6255     SDValue Arg = getValue(I.getArgOperand(0));
6256     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6257     EVT Ty = Arg.getValueType();
6258     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6259                              sdl, Ty, Arg));
6260     return;
6261   }
6262   case Intrinsic::ctpop: {
6263     SDValue Arg = getValue(I.getArgOperand(0));
6264     EVT Ty = Arg.getValueType();
6265     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6266     return;
6267   }
6268   case Intrinsic::fshl:
6269   case Intrinsic::fshr: {
6270     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6271     SDValue X = getValue(I.getArgOperand(0));
6272     SDValue Y = getValue(I.getArgOperand(1));
6273     SDValue Z = getValue(I.getArgOperand(2));
6274     EVT VT = X.getValueType();
6275     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6276     SDValue Zero = DAG.getConstant(0, sdl, VT);
6277     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6278 
6279     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6280     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6281       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6282       return;
6283     }
6284 
6285     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6286     // avoid the select that is necessary in the general case to filter out
6287     // the 0-shift possibility that leads to UB.
6288     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6289       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6290       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6291         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6292         return;
6293       }
6294 
6295       // Some targets only rotate one way. Try the opposite direction.
6296       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6297       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6298         // Negate the shift amount because it is safe to ignore the high bits.
6299         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6300         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6301         return;
6302       }
6303 
6304       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6305       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6306       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6307       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6308       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6309       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6310       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6311       return;
6312     }
6313 
6314     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6315     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6316     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6317     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6318     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6319     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6320 
6321     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6322     // and that is undefined. We must compare and select to avoid UB.
6323     EVT CCVT = MVT::i1;
6324     if (VT.isVector())
6325       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6326 
6327     // For fshl, 0-shift returns the 1st arg (X).
6328     // For fshr, 0-shift returns the 2nd arg (Y).
6329     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6330     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6331     return;
6332   }
6333   case Intrinsic::sadd_sat: {
6334     SDValue Op1 = getValue(I.getArgOperand(0));
6335     SDValue Op2 = getValue(I.getArgOperand(1));
6336     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6337     return;
6338   }
6339   case Intrinsic::uadd_sat: {
6340     SDValue Op1 = getValue(I.getArgOperand(0));
6341     SDValue Op2 = getValue(I.getArgOperand(1));
6342     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6343     return;
6344   }
6345   case Intrinsic::ssub_sat: {
6346     SDValue Op1 = getValue(I.getArgOperand(0));
6347     SDValue Op2 = getValue(I.getArgOperand(1));
6348     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6349     return;
6350   }
6351   case Intrinsic::usub_sat: {
6352     SDValue Op1 = getValue(I.getArgOperand(0));
6353     SDValue Op2 = getValue(I.getArgOperand(1));
6354     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6355     return;
6356   }
6357   case Intrinsic::smul_fix:
6358   case Intrinsic::umul_fix:
6359   case Intrinsic::smul_fix_sat:
6360   case Intrinsic::umul_fix_sat: {
6361     SDValue Op1 = getValue(I.getArgOperand(0));
6362     SDValue Op2 = getValue(I.getArgOperand(1));
6363     SDValue Op3 = getValue(I.getArgOperand(2));
6364     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6365                              Op1.getValueType(), Op1, Op2, Op3));
6366     return;
6367   }
6368   case Intrinsic::sdiv_fix:
6369   case Intrinsic::udiv_fix:
6370   case Intrinsic::sdiv_fix_sat:
6371   case Intrinsic::udiv_fix_sat: {
6372     SDValue Op1 = getValue(I.getArgOperand(0));
6373     SDValue Op2 = getValue(I.getArgOperand(1));
6374     SDValue Op3 = getValue(I.getArgOperand(2));
6375     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6376                               Op1, Op2, Op3, DAG, TLI));
6377     return;
6378   }
6379   case Intrinsic::stacksave: {
6380     SDValue Op = getRoot();
6381     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6382     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6383     setValue(&I, Res);
6384     DAG.setRoot(Res.getValue(1));
6385     return;
6386   }
6387   case Intrinsic::stackrestore:
6388     Res = getValue(I.getArgOperand(0));
6389     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6390     return;
6391   case Intrinsic::get_dynamic_area_offset: {
6392     SDValue Op = getRoot();
6393     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6394     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6395     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6396     // target.
6397     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6398       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6399                          " intrinsic!");
6400     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6401                       Op);
6402     DAG.setRoot(Op);
6403     setValue(&I, Res);
6404     return;
6405   }
6406   case Intrinsic::stackguard: {
6407     MachineFunction &MF = DAG.getMachineFunction();
6408     const Module &M = *MF.getFunction().getParent();
6409     SDValue Chain = getRoot();
6410     if (TLI.useLoadStackGuardNode()) {
6411       Res = getLoadStackGuard(DAG, sdl, Chain);
6412     } else {
6413       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6414       const Value *Global = TLI.getSDagStackGuard(M);
6415       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6416       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6417                         MachinePointerInfo(Global, 0), Align,
6418                         MachineMemOperand::MOVolatile);
6419     }
6420     if (TLI.useStackGuardXorFP())
6421       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6422     DAG.setRoot(Chain);
6423     setValue(&I, Res);
6424     return;
6425   }
6426   case Intrinsic::stackprotector: {
6427     // Emit code into the DAG to store the stack guard onto the stack.
6428     MachineFunction &MF = DAG.getMachineFunction();
6429     MachineFrameInfo &MFI = MF.getFrameInfo();
6430     SDValue Src, Chain = getRoot();
6431 
6432     if (TLI.useLoadStackGuardNode())
6433       Src = getLoadStackGuard(DAG, sdl, Chain);
6434     else
6435       Src = getValue(I.getArgOperand(0));   // The guard's value.
6436 
6437     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6438 
6439     int FI = FuncInfo.StaticAllocaMap[Slot];
6440     MFI.setStackProtectorIndex(FI);
6441     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6442 
6443     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6444 
6445     // Store the stack protector onto the stack.
6446     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6447                                                  DAG.getMachineFunction(), FI),
6448                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6449     setValue(&I, Res);
6450     DAG.setRoot(Res);
6451     return;
6452   }
6453   case Intrinsic::objectsize:
6454     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6455 
6456   case Intrinsic::is_constant:
6457     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6458 
6459   case Intrinsic::annotation:
6460   case Intrinsic::ptr_annotation:
6461   case Intrinsic::launder_invariant_group:
6462   case Intrinsic::strip_invariant_group:
6463     // Drop the intrinsic, but forward the value
6464     setValue(&I, getValue(I.getOperand(0)));
6465     return;
6466   case Intrinsic::assume:
6467   case Intrinsic::var_annotation:
6468   case Intrinsic::sideeffect:
6469     // Discard annotate attributes, assumptions, and artificial side-effects.
6470     return;
6471 
6472   case Intrinsic::codeview_annotation: {
6473     // Emit a label associated with this metadata.
6474     MachineFunction &MF = DAG.getMachineFunction();
6475     MCSymbol *Label =
6476         MF.getMMI().getContext().createTempSymbol("annotation", true);
6477     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6478     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6479     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6480     DAG.setRoot(Res);
6481     return;
6482   }
6483 
6484   case Intrinsic::init_trampoline: {
6485     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6486 
6487     SDValue Ops[6];
6488     Ops[0] = getRoot();
6489     Ops[1] = getValue(I.getArgOperand(0));
6490     Ops[2] = getValue(I.getArgOperand(1));
6491     Ops[3] = getValue(I.getArgOperand(2));
6492     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6493     Ops[5] = DAG.getSrcValue(F);
6494 
6495     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6496 
6497     DAG.setRoot(Res);
6498     return;
6499   }
6500   case Intrinsic::adjust_trampoline:
6501     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6502                              TLI.getPointerTy(DAG.getDataLayout()),
6503                              getValue(I.getArgOperand(0))));
6504     return;
6505   case Intrinsic::gcroot: {
6506     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6507            "only valid in functions with gc specified, enforced by Verifier");
6508     assert(GFI && "implied by previous");
6509     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6510     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6511 
6512     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6513     GFI->addStackRoot(FI->getIndex(), TypeMap);
6514     return;
6515   }
6516   case Intrinsic::gcread:
6517   case Intrinsic::gcwrite:
6518     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6519   case Intrinsic::flt_rounds:
6520     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6521     setValue(&I, Res);
6522     DAG.setRoot(Res.getValue(1));
6523     return;
6524 
6525   case Intrinsic::expect:
6526     // Just replace __builtin_expect(exp, c) with EXP.
6527     setValue(&I, getValue(I.getArgOperand(0)));
6528     return;
6529 
6530   case Intrinsic::debugtrap:
6531   case Intrinsic::trap: {
6532     StringRef TrapFuncName =
6533         I.getAttributes()
6534             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6535             .getValueAsString();
6536     if (TrapFuncName.empty()) {
6537       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6538         ISD::TRAP : ISD::DEBUGTRAP;
6539       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6540       return;
6541     }
6542     TargetLowering::ArgListTy Args;
6543 
6544     TargetLowering::CallLoweringInfo CLI(DAG);
6545     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6546         CallingConv::C, I.getType(),
6547         DAG.getExternalSymbol(TrapFuncName.data(),
6548                               TLI.getPointerTy(DAG.getDataLayout())),
6549         std::move(Args));
6550 
6551     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6552     DAG.setRoot(Result.second);
6553     return;
6554   }
6555 
6556   case Intrinsic::uadd_with_overflow:
6557   case Intrinsic::sadd_with_overflow:
6558   case Intrinsic::usub_with_overflow:
6559   case Intrinsic::ssub_with_overflow:
6560   case Intrinsic::umul_with_overflow:
6561   case Intrinsic::smul_with_overflow: {
6562     ISD::NodeType Op;
6563     switch (Intrinsic) {
6564     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6565     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6566     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6567     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6568     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6569     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6570     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6571     }
6572     SDValue Op1 = getValue(I.getArgOperand(0));
6573     SDValue Op2 = getValue(I.getArgOperand(1));
6574 
6575     EVT ResultVT = Op1.getValueType();
6576     EVT OverflowVT = MVT::i1;
6577     if (ResultVT.isVector())
6578       OverflowVT = EVT::getVectorVT(
6579           *Context, OverflowVT, ResultVT.getVectorNumElements());
6580 
6581     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6582     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6583     return;
6584   }
6585   case Intrinsic::prefetch: {
6586     SDValue Ops[5];
6587     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6588     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6589     Ops[0] = DAG.getRoot();
6590     Ops[1] = getValue(I.getArgOperand(0));
6591     Ops[2] = getValue(I.getArgOperand(1));
6592     Ops[3] = getValue(I.getArgOperand(2));
6593     Ops[4] = getValue(I.getArgOperand(3));
6594     SDValue Result = DAG.getMemIntrinsicNode(
6595         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6596         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6597         /* align */ None, Flags);
6598 
6599     // Chain the prefetch in parallell with any pending loads, to stay out of
6600     // the way of later optimizations.
6601     PendingLoads.push_back(Result);
6602     Result = getRoot();
6603     DAG.setRoot(Result);
6604     return;
6605   }
6606   case Intrinsic::lifetime_start:
6607   case Intrinsic::lifetime_end: {
6608     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6609     // Stack coloring is not enabled in O0, discard region information.
6610     if (TM.getOptLevel() == CodeGenOpt::None)
6611       return;
6612 
6613     const int64_t ObjectSize =
6614         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6615     Value *const ObjectPtr = I.getArgOperand(1);
6616     SmallVector<const Value *, 4> Allocas;
6617     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6618 
6619     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6620            E = Allocas.end(); Object != E; ++Object) {
6621       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6622 
6623       // Could not find an Alloca.
6624       if (!LifetimeObject)
6625         continue;
6626 
6627       // First check that the Alloca is static, otherwise it won't have a
6628       // valid frame index.
6629       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6630       if (SI == FuncInfo.StaticAllocaMap.end())
6631         return;
6632 
6633       const int FrameIndex = SI->second;
6634       int64_t Offset;
6635       if (GetPointerBaseWithConstantOffset(
6636               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6637         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6638       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6639                                 Offset);
6640       DAG.setRoot(Res);
6641     }
6642     return;
6643   }
6644   case Intrinsic::invariant_start:
6645     // Discard region information.
6646     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6647     return;
6648   case Intrinsic::invariant_end:
6649     // Discard region information.
6650     return;
6651   case Intrinsic::clear_cache:
6652     /// FunctionName may be null.
6653     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6654       lowerCallToExternalSymbol(I, FunctionName);
6655     return;
6656   case Intrinsic::donothing:
6657     // ignore
6658     return;
6659   case Intrinsic::experimental_stackmap:
6660     visitStackmap(I);
6661     return;
6662   case Intrinsic::experimental_patchpoint_void:
6663   case Intrinsic::experimental_patchpoint_i64:
6664     visitPatchpoint(I);
6665     return;
6666   case Intrinsic::experimental_gc_statepoint:
6667     LowerStatepoint(cast<GCStatepointInst>(I));
6668     return;
6669   case Intrinsic::experimental_gc_result:
6670     visitGCResult(cast<GCResultInst>(I));
6671     return;
6672   case Intrinsic::experimental_gc_relocate:
6673     visitGCRelocate(cast<GCRelocateInst>(I));
6674     return;
6675   case Intrinsic::instrprof_increment:
6676     llvm_unreachable("instrprof failed to lower an increment");
6677   case Intrinsic::instrprof_value_profile:
6678     llvm_unreachable("instrprof failed to lower a value profiling call");
6679   case Intrinsic::localescape: {
6680     MachineFunction &MF = DAG.getMachineFunction();
6681     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6682 
6683     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6684     // is the same on all targets.
6685     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6686       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6687       if (isa<ConstantPointerNull>(Arg))
6688         continue; // Skip null pointers. They represent a hole in index space.
6689       AllocaInst *Slot = cast<AllocaInst>(Arg);
6690       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6691              "can only escape static allocas");
6692       int FI = FuncInfo.StaticAllocaMap[Slot];
6693       MCSymbol *FrameAllocSym =
6694           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6695               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6696       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6697               TII->get(TargetOpcode::LOCAL_ESCAPE))
6698           .addSym(FrameAllocSym)
6699           .addFrameIndex(FI);
6700     }
6701 
6702     return;
6703   }
6704 
6705   case Intrinsic::localrecover: {
6706     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6707     MachineFunction &MF = DAG.getMachineFunction();
6708 
6709     // Get the symbol that defines the frame offset.
6710     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6711     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6712     unsigned IdxVal =
6713         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6714     MCSymbol *FrameAllocSym =
6715         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6716             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6717 
6718     Value *FP = I.getArgOperand(1);
6719     SDValue FPVal = getValue(FP);
6720     EVT PtrVT = FPVal.getValueType();
6721 
6722     // Create a MCSymbol for the label to avoid any target lowering
6723     // that would make this PC relative.
6724     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6725     SDValue OffsetVal =
6726         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6727 
6728     // Add the offset to the FP.
6729     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6730     setValue(&I, Add);
6731 
6732     return;
6733   }
6734 
6735   case Intrinsic::eh_exceptionpointer:
6736   case Intrinsic::eh_exceptioncode: {
6737     // Get the exception pointer vreg, copy from it, and resize it to fit.
6738     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6739     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6740     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6741     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6742     SDValue N =
6743         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6744     if (Intrinsic == Intrinsic::eh_exceptioncode)
6745       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6746     setValue(&I, N);
6747     return;
6748   }
6749   case Intrinsic::xray_customevent: {
6750     // Here we want to make sure that the intrinsic behaves as if it has a
6751     // specific calling convention, and only for x86_64.
6752     // FIXME: Support other platforms later.
6753     const auto &Triple = DAG.getTarget().getTargetTriple();
6754     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6755       return;
6756 
6757     SDLoc DL = getCurSDLoc();
6758     SmallVector<SDValue, 8> Ops;
6759 
6760     // We want to say that we always want the arguments in registers.
6761     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6762     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6763     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6764     SDValue Chain = getRoot();
6765     Ops.push_back(LogEntryVal);
6766     Ops.push_back(StrSizeVal);
6767     Ops.push_back(Chain);
6768 
6769     // We need to enforce the calling convention for the callsite, so that
6770     // argument ordering is enforced correctly, and that register allocation can
6771     // see that some registers may be assumed clobbered and have to preserve
6772     // them across calls to the intrinsic.
6773     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6774                                            DL, NodeTys, Ops);
6775     SDValue patchableNode = SDValue(MN, 0);
6776     DAG.setRoot(patchableNode);
6777     setValue(&I, patchableNode);
6778     return;
6779   }
6780   case Intrinsic::xray_typedevent: {
6781     // Here we want to make sure that the intrinsic behaves as if it has a
6782     // specific calling convention, and only for x86_64.
6783     // FIXME: Support other platforms later.
6784     const auto &Triple = DAG.getTarget().getTargetTriple();
6785     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6786       return;
6787 
6788     SDLoc DL = getCurSDLoc();
6789     SmallVector<SDValue, 8> Ops;
6790 
6791     // We want to say that we always want the arguments in registers.
6792     // It's unclear to me how manipulating the selection DAG here forces callers
6793     // to provide arguments in registers instead of on the stack.
6794     SDValue LogTypeId = getValue(I.getArgOperand(0));
6795     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6796     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6797     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6798     SDValue Chain = getRoot();
6799     Ops.push_back(LogTypeId);
6800     Ops.push_back(LogEntryVal);
6801     Ops.push_back(StrSizeVal);
6802     Ops.push_back(Chain);
6803 
6804     // We need to enforce the calling convention for the callsite, so that
6805     // argument ordering is enforced correctly, and that register allocation can
6806     // see that some registers may be assumed clobbered and have to preserve
6807     // them across calls to the intrinsic.
6808     MachineSDNode *MN = DAG.getMachineNode(
6809         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6810     SDValue patchableNode = SDValue(MN, 0);
6811     DAG.setRoot(patchableNode);
6812     setValue(&I, patchableNode);
6813     return;
6814   }
6815   case Intrinsic::experimental_deoptimize:
6816     LowerDeoptimizeCall(&I);
6817     return;
6818 
6819   case Intrinsic::experimental_vector_reduce_v2_fadd:
6820   case Intrinsic::experimental_vector_reduce_v2_fmul:
6821   case Intrinsic::experimental_vector_reduce_add:
6822   case Intrinsic::experimental_vector_reduce_mul:
6823   case Intrinsic::experimental_vector_reduce_and:
6824   case Intrinsic::experimental_vector_reduce_or:
6825   case Intrinsic::experimental_vector_reduce_xor:
6826   case Intrinsic::experimental_vector_reduce_smax:
6827   case Intrinsic::experimental_vector_reduce_smin:
6828   case Intrinsic::experimental_vector_reduce_umax:
6829   case Intrinsic::experimental_vector_reduce_umin:
6830   case Intrinsic::experimental_vector_reduce_fmax:
6831   case Intrinsic::experimental_vector_reduce_fmin:
6832     visitVectorReduce(I, Intrinsic);
6833     return;
6834 
6835   case Intrinsic::icall_branch_funnel: {
6836     SmallVector<SDValue, 16> Ops;
6837     Ops.push_back(getValue(I.getArgOperand(0)));
6838 
6839     int64_t Offset;
6840     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6841         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6842     if (!Base)
6843       report_fatal_error(
6844           "llvm.icall.branch.funnel operand must be a GlobalValue");
6845     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6846 
6847     struct BranchFunnelTarget {
6848       int64_t Offset;
6849       SDValue Target;
6850     };
6851     SmallVector<BranchFunnelTarget, 8> Targets;
6852 
6853     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6854       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6855           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6856       if (ElemBase != Base)
6857         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6858                            "to the same GlobalValue");
6859 
6860       SDValue Val = getValue(I.getArgOperand(Op + 1));
6861       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6862       if (!GA)
6863         report_fatal_error(
6864             "llvm.icall.branch.funnel operand must be a GlobalValue");
6865       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6866                                      GA->getGlobal(), getCurSDLoc(),
6867                                      Val.getValueType(), GA->getOffset())});
6868     }
6869     llvm::sort(Targets,
6870                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6871                  return T1.Offset < T2.Offset;
6872                });
6873 
6874     for (auto &T : Targets) {
6875       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6876       Ops.push_back(T.Target);
6877     }
6878 
6879     Ops.push_back(DAG.getRoot()); // Chain
6880     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6881                                  getCurSDLoc(), MVT::Other, Ops),
6882               0);
6883     DAG.setRoot(N);
6884     setValue(&I, N);
6885     HasTailCall = true;
6886     return;
6887   }
6888 
6889   case Intrinsic::wasm_landingpad_index:
6890     // Information this intrinsic contained has been transferred to
6891     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6892     // delete it now.
6893     return;
6894 
6895   case Intrinsic::aarch64_settag:
6896   case Intrinsic::aarch64_settag_zero: {
6897     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6898     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6899     SDValue Val = TSI.EmitTargetCodeForSetTag(
6900         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6901         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6902         ZeroMemory);
6903     DAG.setRoot(Val);
6904     setValue(&I, Val);
6905     return;
6906   }
6907   case Intrinsic::ptrmask: {
6908     SDValue Ptr = getValue(I.getOperand(0));
6909     SDValue Const = getValue(I.getOperand(1));
6910 
6911     EVT PtrVT = Ptr.getValueType();
6912     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
6913                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
6914     return;
6915   }
6916   case Intrinsic::get_active_lane_mask: {
6917     auto DL = getCurSDLoc();
6918     SDValue Index = getValue(I.getOperand(0));
6919     SDValue BTC = getValue(I.getOperand(1));
6920     Type *ElementTy = I.getOperand(0)->getType();
6921     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6922     unsigned VecWidth = VT.getVectorNumElements();
6923 
6924     SmallVector<SDValue, 16> OpsBTC;
6925     SmallVector<SDValue, 16> OpsIndex;
6926     SmallVector<SDValue, 16> OpsStepConstants;
6927     for (unsigned i = 0; i < VecWidth; i++) {
6928       OpsBTC.push_back(BTC);
6929       OpsIndex.push_back(Index);
6930       OpsStepConstants.push_back(DAG.getConstant(i, DL, MVT::getVT(ElementTy)));
6931     }
6932 
6933     EVT CCVT = MVT::i1;
6934     CCVT = EVT::getVectorVT(I.getContext(), CCVT, VecWidth);
6935 
6936     auto VecTy = MVT::getVT(FixedVectorType::get(ElementTy, VecWidth));
6937     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
6938     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
6939     SDValue VectorInduction = DAG.getNode(
6940        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
6941     SDValue VectorBTC = DAG.getBuildVector(VecTy, DL, OpsBTC);
6942     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
6943                                  VectorBTC, ISD::CondCode::SETULE);
6944     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
6945                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
6946                              SetCC));
6947     return;
6948   }
6949   }
6950 }
6951 
6952 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6953     const ConstrainedFPIntrinsic &FPI) {
6954   SDLoc sdl = getCurSDLoc();
6955 
6956   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6957   SmallVector<EVT, 4> ValueVTs;
6958   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6959   ValueVTs.push_back(MVT::Other); // Out chain
6960 
6961   // We do not need to serialize constrained FP intrinsics against
6962   // each other or against (nonvolatile) loads, so they can be
6963   // chained like loads.
6964   SDValue Chain = DAG.getRoot();
6965   SmallVector<SDValue, 4> Opers;
6966   Opers.push_back(Chain);
6967   if (FPI.isUnaryOp()) {
6968     Opers.push_back(getValue(FPI.getArgOperand(0)));
6969   } else if (FPI.isTernaryOp()) {
6970     Opers.push_back(getValue(FPI.getArgOperand(0)));
6971     Opers.push_back(getValue(FPI.getArgOperand(1)));
6972     Opers.push_back(getValue(FPI.getArgOperand(2)));
6973   } else {
6974     Opers.push_back(getValue(FPI.getArgOperand(0)));
6975     Opers.push_back(getValue(FPI.getArgOperand(1)));
6976   }
6977 
6978   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
6979     assert(Result.getNode()->getNumValues() == 2);
6980 
6981     // Push node to the appropriate list so that future instructions can be
6982     // chained up correctly.
6983     SDValue OutChain = Result.getValue(1);
6984     switch (EB) {
6985     case fp::ExceptionBehavior::ebIgnore:
6986       // The only reason why ebIgnore nodes still need to be chained is that
6987       // they might depend on the current rounding mode, and therefore must
6988       // not be moved across instruction that may change that mode.
6989       LLVM_FALLTHROUGH;
6990     case fp::ExceptionBehavior::ebMayTrap:
6991       // These must not be moved across calls or instructions that may change
6992       // floating-point exception masks.
6993       PendingConstrainedFP.push_back(OutChain);
6994       break;
6995     case fp::ExceptionBehavior::ebStrict:
6996       // These must not be moved across calls or instructions that may change
6997       // floating-point exception masks or read floating-point exception flags.
6998       // In addition, they cannot be optimized out even if unused.
6999       PendingConstrainedFPStrict.push_back(OutChain);
7000       break;
7001     }
7002   };
7003 
7004   SDVTList VTs = DAG.getVTList(ValueVTs);
7005   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7006 
7007   SDNodeFlags Flags;
7008   if (EB == fp::ExceptionBehavior::ebIgnore)
7009     Flags.setNoFPExcept(true);
7010 
7011   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7012     Flags.copyFMF(*FPOp);
7013 
7014   unsigned Opcode;
7015   switch (FPI.getIntrinsicID()) {
7016   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7017 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7018   case Intrinsic::INTRINSIC:                                                   \
7019     Opcode = ISD::STRICT_##DAGN;                                               \
7020     break;
7021 #include "llvm/IR/ConstrainedOps.def"
7022   case Intrinsic::experimental_constrained_fmuladd: {
7023     Opcode = ISD::STRICT_FMA;
7024     // Break fmuladd into fmul and fadd.
7025     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7026         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7027                                         ValueVTs[0])) {
7028       Opers.pop_back();
7029       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7030       pushOutChain(Mul, EB);
7031       Opcode = ISD::STRICT_FADD;
7032       Opers.clear();
7033       Opers.push_back(Mul.getValue(1));
7034       Opers.push_back(Mul.getValue(0));
7035       Opers.push_back(getValue(FPI.getArgOperand(2)));
7036     }
7037     break;
7038   }
7039   }
7040 
7041   // A few strict DAG nodes carry additional operands that are not
7042   // set up by the default code above.
7043   switch (Opcode) {
7044   default: break;
7045   case ISD::STRICT_FP_ROUND:
7046     Opers.push_back(
7047         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7048     break;
7049   case ISD::STRICT_FSETCC:
7050   case ISD::STRICT_FSETCCS: {
7051     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7052     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7053     break;
7054   }
7055   }
7056 
7057   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7058   pushOutChain(Result, EB);
7059 
7060   SDValue FPResult = Result.getValue(0);
7061   setValue(&FPI, FPResult);
7062 }
7063 
7064 std::pair<SDValue, SDValue>
7065 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7066                                     const BasicBlock *EHPadBB) {
7067   MachineFunction &MF = DAG.getMachineFunction();
7068   MachineModuleInfo &MMI = MF.getMMI();
7069   MCSymbol *BeginLabel = nullptr;
7070 
7071   if (EHPadBB) {
7072     // Insert a label before the invoke call to mark the try range.  This can be
7073     // used to detect deletion of the invoke via the MachineModuleInfo.
7074     BeginLabel = MMI.getContext().createTempSymbol();
7075 
7076     // For SjLj, keep track of which landing pads go with which invokes
7077     // so as to maintain the ordering of pads in the LSDA.
7078     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7079     if (CallSiteIndex) {
7080       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7081       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7082 
7083       // Now that the call site is handled, stop tracking it.
7084       MMI.setCurrentCallSite(0);
7085     }
7086 
7087     // Both PendingLoads and PendingExports must be flushed here;
7088     // this call might not return.
7089     (void)getRoot();
7090     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7091 
7092     CLI.setChain(getRoot());
7093   }
7094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7095   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7096 
7097   assert((CLI.IsTailCall || Result.second.getNode()) &&
7098          "Non-null chain expected with non-tail call!");
7099   assert((Result.second.getNode() || !Result.first.getNode()) &&
7100          "Null value expected with tail call!");
7101 
7102   if (!Result.second.getNode()) {
7103     // As a special case, a null chain means that a tail call has been emitted
7104     // and the DAG root is already updated.
7105     HasTailCall = true;
7106 
7107     // Since there's no actual continuation from this block, nothing can be
7108     // relying on us setting vregs for them.
7109     PendingExports.clear();
7110   } else {
7111     DAG.setRoot(Result.second);
7112   }
7113 
7114   if (EHPadBB) {
7115     // Insert a label at the end of the invoke call to mark the try range.  This
7116     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7117     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7118     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7119 
7120     // Inform MachineModuleInfo of range.
7121     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7122     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7123     // actually use outlined funclets and their LSDA info style.
7124     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7125       assert(CLI.CB);
7126       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7127       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7128     } else if (!isScopedEHPersonality(Pers)) {
7129       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7130     }
7131   }
7132 
7133   return Result;
7134 }
7135 
7136 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7137                                       bool isTailCall,
7138                                       const BasicBlock *EHPadBB) {
7139   auto &DL = DAG.getDataLayout();
7140   FunctionType *FTy = CB.getFunctionType();
7141   Type *RetTy = CB.getType();
7142 
7143   TargetLowering::ArgListTy Args;
7144   Args.reserve(CB.arg_size());
7145 
7146   const Value *SwiftErrorVal = nullptr;
7147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7148 
7149   if (isTailCall) {
7150     // Avoid emitting tail calls in functions with the disable-tail-calls
7151     // attribute.
7152     auto *Caller = CB.getParent()->getParent();
7153     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7154         "true")
7155       isTailCall = false;
7156 
7157     // We can't tail call inside a function with a swifterror argument. Lowering
7158     // does not support this yet. It would have to move into the swifterror
7159     // register before the call.
7160     if (TLI.supportSwiftError() &&
7161         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7162       isTailCall = false;
7163   }
7164 
7165   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7166     TargetLowering::ArgListEntry Entry;
7167     const Value *V = *I;
7168 
7169     // Skip empty types
7170     if (V->getType()->isEmptyTy())
7171       continue;
7172 
7173     SDValue ArgNode = getValue(V);
7174     Entry.Node = ArgNode; Entry.Ty = V->getType();
7175 
7176     Entry.setAttributes(&CB, I - CB.arg_begin());
7177 
7178     // Use swifterror virtual register as input to the call.
7179     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7180       SwiftErrorVal = V;
7181       // We find the virtual register for the actual swifterror argument.
7182       // Instead of using the Value, we use the virtual register instead.
7183       Entry.Node =
7184           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7185                           EVT(TLI.getPointerTy(DL)));
7186     }
7187 
7188     Args.push_back(Entry);
7189 
7190     // If we have an explicit sret argument that is an Instruction, (i.e., it
7191     // might point to function-local memory), we can't meaningfully tail-call.
7192     if (Entry.IsSRet && isa<Instruction>(V))
7193       isTailCall = false;
7194   }
7195 
7196   // If call site has a cfguardtarget operand bundle, create and add an
7197   // additional ArgListEntry.
7198   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7199     TargetLowering::ArgListEntry Entry;
7200     Value *V = Bundle->Inputs[0];
7201     SDValue ArgNode = getValue(V);
7202     Entry.Node = ArgNode;
7203     Entry.Ty = V->getType();
7204     Entry.IsCFGuardTarget = true;
7205     Args.push_back(Entry);
7206   }
7207 
7208   // Check if target-independent constraints permit a tail call here.
7209   // Target-dependent constraints are checked within TLI->LowerCallTo.
7210   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7211     isTailCall = false;
7212 
7213   // Disable tail calls if there is an swifterror argument. Targets have not
7214   // been updated to support tail calls.
7215   if (TLI.supportSwiftError() && SwiftErrorVal)
7216     isTailCall = false;
7217 
7218   TargetLowering::CallLoweringInfo CLI(DAG);
7219   CLI.setDebugLoc(getCurSDLoc())
7220       .setChain(getRoot())
7221       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7222       .setTailCall(isTailCall)
7223       .setConvergent(CB.isConvergent())
7224       .setIsPreallocated(
7225           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7226   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7227 
7228   if (Result.first.getNode()) {
7229     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7230     setValue(&CB, Result.first);
7231   }
7232 
7233   // The last element of CLI.InVals has the SDValue for swifterror return.
7234   // Here we copy it to a virtual register and update SwiftErrorMap for
7235   // book-keeping.
7236   if (SwiftErrorVal && TLI.supportSwiftError()) {
7237     // Get the last element of InVals.
7238     SDValue Src = CLI.InVals.back();
7239     Register VReg =
7240         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7241     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7242     DAG.setRoot(CopyNode);
7243   }
7244 }
7245 
7246 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7247                              SelectionDAGBuilder &Builder) {
7248   // Check to see if this load can be trivially constant folded, e.g. if the
7249   // input is from a string literal.
7250   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7251     // Cast pointer to the type we really want to load.
7252     Type *LoadTy =
7253         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7254     if (LoadVT.isVector())
7255       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7256 
7257     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7258                                          PointerType::getUnqual(LoadTy));
7259 
7260     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7261             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7262       return Builder.getValue(LoadCst);
7263   }
7264 
7265   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7266   // still constant memory, the input chain can be the entry node.
7267   SDValue Root;
7268   bool ConstantMemory = false;
7269 
7270   // Do not serialize (non-volatile) loads of constant memory with anything.
7271   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7272     Root = Builder.DAG.getEntryNode();
7273     ConstantMemory = true;
7274   } else {
7275     // Do not serialize non-volatile loads against each other.
7276     Root = Builder.DAG.getRoot();
7277   }
7278 
7279   SDValue Ptr = Builder.getValue(PtrVal);
7280   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7281                                         Ptr, MachinePointerInfo(PtrVal),
7282                                         /* Alignment = */ 1);
7283 
7284   if (!ConstantMemory)
7285     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7286   return LoadVal;
7287 }
7288 
7289 /// Record the value for an instruction that produces an integer result,
7290 /// converting the type where necessary.
7291 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7292                                                   SDValue Value,
7293                                                   bool IsSigned) {
7294   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7295                                                     I.getType(), true);
7296   if (IsSigned)
7297     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7298   else
7299     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7300   setValue(&I, Value);
7301 }
7302 
7303 /// See if we can lower a memcmp call into an optimized form. If so, return
7304 /// true and lower it. Otherwise return false, and it will be lowered like a
7305 /// normal call.
7306 /// The caller already checked that \p I calls the appropriate LibFunc with a
7307 /// correct prototype.
7308 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7309   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7310   const Value *Size = I.getArgOperand(2);
7311   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7312   if (CSize && CSize->getZExtValue() == 0) {
7313     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7314                                                           I.getType(), true);
7315     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7316     return true;
7317   }
7318 
7319   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7320   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7321       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7322       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7323   if (Res.first.getNode()) {
7324     processIntegerCallValue(I, Res.first, true);
7325     PendingLoads.push_back(Res.second);
7326     return true;
7327   }
7328 
7329   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7330   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7331   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7332     return false;
7333 
7334   // If the target has a fast compare for the given size, it will return a
7335   // preferred load type for that size. Require that the load VT is legal and
7336   // that the target supports unaligned loads of that type. Otherwise, return
7337   // INVALID.
7338   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7339     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7340     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7341     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7342       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7343       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7344       // TODO: Check alignment of src and dest ptrs.
7345       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7346       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7347       if (!TLI.isTypeLegal(LVT) ||
7348           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7349           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7350         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7351     }
7352 
7353     return LVT;
7354   };
7355 
7356   // This turns into unaligned loads. We only do this if the target natively
7357   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7358   // we'll only produce a small number of byte loads.
7359   MVT LoadVT;
7360   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7361   switch (NumBitsToCompare) {
7362   default:
7363     return false;
7364   case 16:
7365     LoadVT = MVT::i16;
7366     break;
7367   case 32:
7368     LoadVT = MVT::i32;
7369     break;
7370   case 64:
7371   case 128:
7372   case 256:
7373     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7374     break;
7375   }
7376 
7377   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7378     return false;
7379 
7380   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7381   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7382 
7383   // Bitcast to a wide integer type if the loads are vectors.
7384   if (LoadVT.isVector()) {
7385     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7386     LoadL = DAG.getBitcast(CmpVT, LoadL);
7387     LoadR = DAG.getBitcast(CmpVT, LoadR);
7388   }
7389 
7390   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7391   processIntegerCallValue(I, Cmp, false);
7392   return true;
7393 }
7394 
7395 /// See if we can lower a memchr call into an optimized form. If so, return
7396 /// true and lower it. Otherwise return false, and it will be lowered like a
7397 /// normal call.
7398 /// The caller already checked that \p I calls the appropriate LibFunc with a
7399 /// correct prototype.
7400 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7401   const Value *Src = I.getArgOperand(0);
7402   const Value *Char = I.getArgOperand(1);
7403   const Value *Length = I.getArgOperand(2);
7404 
7405   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7406   std::pair<SDValue, SDValue> Res =
7407     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7408                                 getValue(Src), getValue(Char), getValue(Length),
7409                                 MachinePointerInfo(Src));
7410   if (Res.first.getNode()) {
7411     setValue(&I, Res.first);
7412     PendingLoads.push_back(Res.second);
7413     return true;
7414   }
7415 
7416   return false;
7417 }
7418 
7419 /// See if we can lower a mempcpy call into an optimized form. If so, return
7420 /// true and lower it. Otherwise return false, and it will be lowered like a
7421 /// normal call.
7422 /// The caller already checked that \p I calls the appropriate LibFunc with a
7423 /// correct prototype.
7424 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7425   SDValue Dst = getValue(I.getArgOperand(0));
7426   SDValue Src = getValue(I.getArgOperand(1));
7427   SDValue Size = getValue(I.getArgOperand(2));
7428 
7429   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7430   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7431   // DAG::getMemcpy needs Alignment to be defined.
7432   Align Alignment = std::min(DstAlign, SrcAlign);
7433 
7434   bool isVol = false;
7435   SDLoc sdl = getCurSDLoc();
7436 
7437   // In the mempcpy context we need to pass in a false value for isTailCall
7438   // because the return pointer needs to be adjusted by the size of
7439   // the copied memory.
7440   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7441   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7442                              /*isTailCall=*/false,
7443                              MachinePointerInfo(I.getArgOperand(0)),
7444                              MachinePointerInfo(I.getArgOperand(1)));
7445   assert(MC.getNode() != nullptr &&
7446          "** memcpy should not be lowered as TailCall in mempcpy context **");
7447   DAG.setRoot(MC);
7448 
7449   // Check if Size needs to be truncated or extended.
7450   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7451 
7452   // Adjust return pointer to point just past the last dst byte.
7453   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7454                                     Dst, Size);
7455   setValue(&I, DstPlusSize);
7456   return true;
7457 }
7458 
7459 /// See if we can lower a strcpy 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::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7465   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7466 
7467   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7468   std::pair<SDValue, SDValue> Res =
7469     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7470                                 getValue(Arg0), getValue(Arg1),
7471                                 MachinePointerInfo(Arg0),
7472                                 MachinePointerInfo(Arg1), isStpcpy);
7473   if (Res.first.getNode()) {
7474     setValue(&I, Res.first);
7475     DAG.setRoot(Res.second);
7476     return true;
7477   }
7478 
7479   return false;
7480 }
7481 
7482 /// See if we can lower a strcmp call into an optimized form.  If so, return
7483 /// true and lower it, otherwise return false and it will be lowered like a
7484 /// normal call.
7485 /// The caller already checked that \p I calls the appropriate LibFunc with a
7486 /// correct prototype.
7487 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7488   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7489 
7490   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7491   std::pair<SDValue, SDValue> Res =
7492     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7493                                 getValue(Arg0), getValue(Arg1),
7494                                 MachinePointerInfo(Arg0),
7495                                 MachinePointerInfo(Arg1));
7496   if (Res.first.getNode()) {
7497     processIntegerCallValue(I, Res.first, true);
7498     PendingLoads.push_back(Res.second);
7499     return true;
7500   }
7501 
7502   return false;
7503 }
7504 
7505 /// See if we can lower a strlen call into an optimized form.  If so, return
7506 /// true and lower it, otherwise return false and it will be lowered like a
7507 /// normal call.
7508 /// The caller already checked that \p I calls the appropriate LibFunc with a
7509 /// correct prototype.
7510 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7511   const Value *Arg0 = I.getArgOperand(0);
7512 
7513   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7514   std::pair<SDValue, SDValue> Res =
7515     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7516                                 getValue(Arg0), MachinePointerInfo(Arg0));
7517   if (Res.first.getNode()) {
7518     processIntegerCallValue(I, Res.first, false);
7519     PendingLoads.push_back(Res.second);
7520     return true;
7521   }
7522 
7523   return false;
7524 }
7525 
7526 /// See if we can lower a strnlen call into an optimized form.  If so, return
7527 /// true and lower it, otherwise return false and it will be lowered like a
7528 /// normal call.
7529 /// The caller already checked that \p I calls the appropriate LibFunc with a
7530 /// correct prototype.
7531 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7532   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7533 
7534   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7535   std::pair<SDValue, SDValue> Res =
7536     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7537                                  getValue(Arg0), getValue(Arg1),
7538                                  MachinePointerInfo(Arg0));
7539   if (Res.first.getNode()) {
7540     processIntegerCallValue(I, Res.first, false);
7541     PendingLoads.push_back(Res.second);
7542     return true;
7543   }
7544 
7545   return false;
7546 }
7547 
7548 /// See if we can lower a unary floating-point operation into an SDNode with
7549 /// the specified Opcode.  If so, return true and lower it, otherwise return
7550 /// false and it will be lowered like a normal call.
7551 /// The caller already checked that \p I calls the appropriate LibFunc with a
7552 /// correct prototype.
7553 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7554                                               unsigned Opcode) {
7555   // We already checked this call's prototype; verify it doesn't modify errno.
7556   if (!I.onlyReadsMemory())
7557     return false;
7558 
7559   SDValue Tmp = getValue(I.getArgOperand(0));
7560   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7561   return true;
7562 }
7563 
7564 /// See if we can lower a binary floating-point operation into an SDNode with
7565 /// the specified Opcode. If so, return true and lower it. Otherwise return
7566 /// false, and it will be lowered like a normal call.
7567 /// The caller already checked that \p I calls the appropriate LibFunc with a
7568 /// correct prototype.
7569 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7570                                                unsigned Opcode) {
7571   // We already checked this call's prototype; verify it doesn't modify errno.
7572   if (!I.onlyReadsMemory())
7573     return false;
7574 
7575   SDValue Tmp0 = getValue(I.getArgOperand(0));
7576   SDValue Tmp1 = getValue(I.getArgOperand(1));
7577   EVT VT = Tmp0.getValueType();
7578   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7579   return true;
7580 }
7581 
7582 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7583   // Handle inline assembly differently.
7584   if (I.isInlineAsm()) {
7585     visitInlineAsm(I);
7586     return;
7587   }
7588 
7589   if (Function *F = I.getCalledFunction()) {
7590     if (F->isDeclaration()) {
7591       // Is this an LLVM intrinsic or a target-specific intrinsic?
7592       unsigned IID = F->getIntrinsicID();
7593       if (!IID)
7594         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7595           IID = II->getIntrinsicID(F);
7596 
7597       if (IID) {
7598         visitIntrinsicCall(I, IID);
7599         return;
7600       }
7601     }
7602 
7603     // Check for well-known libc/libm calls.  If the function is internal, it
7604     // can't be a library call.  Don't do the check if marked as nobuiltin for
7605     // some reason or the call site requires strict floating point semantics.
7606     LibFunc Func;
7607     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7608         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7609         LibInfo->hasOptimizedCodeGen(Func)) {
7610       switch (Func) {
7611       default: break;
7612       case LibFunc_copysign:
7613       case LibFunc_copysignf:
7614       case LibFunc_copysignl:
7615         // We already checked this call's prototype; verify it doesn't modify
7616         // errno.
7617         if (I.onlyReadsMemory()) {
7618           SDValue LHS = getValue(I.getArgOperand(0));
7619           SDValue RHS = getValue(I.getArgOperand(1));
7620           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7621                                    LHS.getValueType(), LHS, RHS));
7622           return;
7623         }
7624         break;
7625       case LibFunc_fabs:
7626       case LibFunc_fabsf:
7627       case LibFunc_fabsl:
7628         if (visitUnaryFloatCall(I, ISD::FABS))
7629           return;
7630         break;
7631       case LibFunc_fmin:
7632       case LibFunc_fminf:
7633       case LibFunc_fminl:
7634         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7635           return;
7636         break;
7637       case LibFunc_fmax:
7638       case LibFunc_fmaxf:
7639       case LibFunc_fmaxl:
7640         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7641           return;
7642         break;
7643       case LibFunc_sin:
7644       case LibFunc_sinf:
7645       case LibFunc_sinl:
7646         if (visitUnaryFloatCall(I, ISD::FSIN))
7647           return;
7648         break;
7649       case LibFunc_cos:
7650       case LibFunc_cosf:
7651       case LibFunc_cosl:
7652         if (visitUnaryFloatCall(I, ISD::FCOS))
7653           return;
7654         break;
7655       case LibFunc_sqrt:
7656       case LibFunc_sqrtf:
7657       case LibFunc_sqrtl:
7658       case LibFunc_sqrt_finite:
7659       case LibFunc_sqrtf_finite:
7660       case LibFunc_sqrtl_finite:
7661         if (visitUnaryFloatCall(I, ISD::FSQRT))
7662           return;
7663         break;
7664       case LibFunc_floor:
7665       case LibFunc_floorf:
7666       case LibFunc_floorl:
7667         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7668           return;
7669         break;
7670       case LibFunc_nearbyint:
7671       case LibFunc_nearbyintf:
7672       case LibFunc_nearbyintl:
7673         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7674           return;
7675         break;
7676       case LibFunc_ceil:
7677       case LibFunc_ceilf:
7678       case LibFunc_ceill:
7679         if (visitUnaryFloatCall(I, ISD::FCEIL))
7680           return;
7681         break;
7682       case LibFunc_rint:
7683       case LibFunc_rintf:
7684       case LibFunc_rintl:
7685         if (visitUnaryFloatCall(I, ISD::FRINT))
7686           return;
7687         break;
7688       case LibFunc_round:
7689       case LibFunc_roundf:
7690       case LibFunc_roundl:
7691         if (visitUnaryFloatCall(I, ISD::FROUND))
7692           return;
7693         break;
7694       case LibFunc_trunc:
7695       case LibFunc_truncf:
7696       case LibFunc_truncl:
7697         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7698           return;
7699         break;
7700       case LibFunc_log2:
7701       case LibFunc_log2f:
7702       case LibFunc_log2l:
7703         if (visitUnaryFloatCall(I, ISD::FLOG2))
7704           return;
7705         break;
7706       case LibFunc_exp2:
7707       case LibFunc_exp2f:
7708       case LibFunc_exp2l:
7709         if (visitUnaryFloatCall(I, ISD::FEXP2))
7710           return;
7711         break;
7712       case LibFunc_memcmp:
7713         if (visitMemCmpCall(I))
7714           return;
7715         break;
7716       case LibFunc_mempcpy:
7717         if (visitMemPCpyCall(I))
7718           return;
7719         break;
7720       case LibFunc_memchr:
7721         if (visitMemChrCall(I))
7722           return;
7723         break;
7724       case LibFunc_strcpy:
7725         if (visitStrCpyCall(I, false))
7726           return;
7727         break;
7728       case LibFunc_stpcpy:
7729         if (visitStrCpyCall(I, true))
7730           return;
7731         break;
7732       case LibFunc_strcmp:
7733         if (visitStrCmpCall(I))
7734           return;
7735         break;
7736       case LibFunc_strlen:
7737         if (visitStrLenCall(I))
7738           return;
7739         break;
7740       case LibFunc_strnlen:
7741         if (visitStrNLenCall(I))
7742           return;
7743         break;
7744       }
7745     }
7746   }
7747 
7748   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7749   // have to do anything here to lower funclet bundles.
7750   // CFGuardTarget bundles are lowered in LowerCallTo.
7751   assert(!I.hasOperandBundlesOtherThan(
7752              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7753               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated}) &&
7754          "Cannot lower calls with arbitrary operand bundles!");
7755 
7756   SDValue Callee = getValue(I.getCalledOperand());
7757 
7758   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7759     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7760   else
7761     // Check if we can potentially perform a tail call. More detailed checking
7762     // is be done within LowerCallTo, after more information about the call is
7763     // known.
7764     LowerCallTo(I, Callee, I.isTailCall());
7765 }
7766 
7767 namespace {
7768 
7769 /// AsmOperandInfo - This contains information for each constraint that we are
7770 /// lowering.
7771 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7772 public:
7773   /// CallOperand - If this is the result output operand or a clobber
7774   /// this is null, otherwise it is the incoming operand to the CallInst.
7775   /// This gets modified as the asm is processed.
7776   SDValue CallOperand;
7777 
7778   /// AssignedRegs - If this is a register or register class operand, this
7779   /// contains the set of register corresponding to the operand.
7780   RegsForValue AssignedRegs;
7781 
7782   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7783     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7784   }
7785 
7786   /// Whether or not this operand accesses memory
7787   bool hasMemory(const TargetLowering &TLI) const {
7788     // Indirect operand accesses access memory.
7789     if (isIndirect)
7790       return true;
7791 
7792     for (const auto &Code : Codes)
7793       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7794         return true;
7795 
7796     return false;
7797   }
7798 
7799   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7800   /// corresponds to.  If there is no Value* for this operand, it returns
7801   /// MVT::Other.
7802   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7803                            const DataLayout &DL) const {
7804     if (!CallOperandVal) return MVT::Other;
7805 
7806     if (isa<BasicBlock>(CallOperandVal))
7807       return TLI.getProgramPointerTy(DL);
7808 
7809     llvm::Type *OpTy = CallOperandVal->getType();
7810 
7811     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7812     // If this is an indirect operand, the operand is a pointer to the
7813     // accessed type.
7814     if (isIndirect) {
7815       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7816       if (!PtrTy)
7817         report_fatal_error("Indirect operand for inline asm not a pointer!");
7818       OpTy = PtrTy->getElementType();
7819     }
7820 
7821     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7822     if (StructType *STy = dyn_cast<StructType>(OpTy))
7823       if (STy->getNumElements() == 1)
7824         OpTy = STy->getElementType(0);
7825 
7826     // If OpTy is not a single value, it may be a struct/union that we
7827     // can tile with integers.
7828     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7829       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7830       switch (BitSize) {
7831       default: break;
7832       case 1:
7833       case 8:
7834       case 16:
7835       case 32:
7836       case 64:
7837       case 128:
7838         OpTy = IntegerType::get(Context, BitSize);
7839         break;
7840       }
7841     }
7842 
7843     return TLI.getValueType(DL, OpTy, true);
7844   }
7845 };
7846 
7847 
7848 } // end anonymous namespace
7849 
7850 /// Make sure that the output operand \p OpInfo and its corresponding input
7851 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7852 /// out).
7853 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7854                                SDISelAsmOperandInfo &MatchingOpInfo,
7855                                SelectionDAG &DAG) {
7856   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7857     return;
7858 
7859   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7860   const auto &TLI = DAG.getTargetLoweringInfo();
7861 
7862   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7863       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7864                                        OpInfo.ConstraintVT);
7865   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7866       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7867                                        MatchingOpInfo.ConstraintVT);
7868   if ((OpInfo.ConstraintVT.isInteger() !=
7869        MatchingOpInfo.ConstraintVT.isInteger()) ||
7870       (MatchRC.second != InputRC.second)) {
7871     // FIXME: error out in a more elegant fashion
7872     report_fatal_error("Unsupported asm: input constraint"
7873                        " with a matching output constraint of"
7874                        " incompatible type!");
7875   }
7876   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7877 }
7878 
7879 /// Get a direct memory input to behave well as an indirect operand.
7880 /// This may introduce stores, hence the need for a \p Chain.
7881 /// \return The (possibly updated) chain.
7882 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7883                                         SDISelAsmOperandInfo &OpInfo,
7884                                         SelectionDAG &DAG) {
7885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7886 
7887   // If we don't have an indirect input, put it in the constpool if we can,
7888   // otherwise spill it to a stack slot.
7889   // TODO: This isn't quite right. We need to handle these according to
7890   // the addressing mode that the constraint wants. Also, this may take
7891   // an additional register for the computation and we don't want that
7892   // either.
7893 
7894   // If the operand is a float, integer, or vector constant, spill to a
7895   // constant pool entry to get its address.
7896   const Value *OpVal = OpInfo.CallOperandVal;
7897   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7898       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7899     OpInfo.CallOperand = DAG.getConstantPool(
7900         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7901     return Chain;
7902   }
7903 
7904   // Otherwise, create a stack slot and emit a store to it before the asm.
7905   Type *Ty = OpVal->getType();
7906   auto &DL = DAG.getDataLayout();
7907   uint64_t TySize = DL.getTypeAllocSize(Ty);
7908   MachineFunction &MF = DAG.getMachineFunction();
7909   int SSFI = MF.getFrameInfo().CreateStackObject(
7910       TySize, DL.getPrefTypeAlign(Ty), false);
7911   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7912   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7913                             MachinePointerInfo::getFixedStack(MF, SSFI),
7914                             TLI.getMemValueType(DL, Ty));
7915   OpInfo.CallOperand = StackSlot;
7916 
7917   return Chain;
7918 }
7919 
7920 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7921 /// specified operand.  We prefer to assign virtual registers, to allow the
7922 /// register allocator to handle the assignment process.  However, if the asm
7923 /// uses features that we can't model on machineinstrs, we have SDISel do the
7924 /// allocation.  This produces generally horrible, but correct, code.
7925 ///
7926 ///   OpInfo describes the operand
7927 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7928 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7929                                  SDISelAsmOperandInfo &OpInfo,
7930                                  SDISelAsmOperandInfo &RefOpInfo) {
7931   LLVMContext &Context = *DAG.getContext();
7932   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7933 
7934   MachineFunction &MF = DAG.getMachineFunction();
7935   SmallVector<unsigned, 4> Regs;
7936   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7937 
7938   // No work to do for memory operations.
7939   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7940     return;
7941 
7942   // If this is a constraint for a single physreg, or a constraint for a
7943   // register class, find it.
7944   unsigned AssignedReg;
7945   const TargetRegisterClass *RC;
7946   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7947       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7948   // RC is unset only on failure. Return immediately.
7949   if (!RC)
7950     return;
7951 
7952   // Get the actual register value type.  This is important, because the user
7953   // may have asked for (e.g.) the AX register in i32 type.  We need to
7954   // remember that AX is actually i16 to get the right extension.
7955   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7956 
7957   if (OpInfo.ConstraintVT != MVT::Other) {
7958     // If this is an FP operand in an integer register (or visa versa), or more
7959     // generally if the operand value disagrees with the register class we plan
7960     // to stick it in, fix the operand type.
7961     //
7962     // If this is an input value, the bitcast to the new type is done now.
7963     // Bitcast for output value is done at the end of visitInlineAsm().
7964     if ((OpInfo.Type == InlineAsm::isOutput ||
7965          OpInfo.Type == InlineAsm::isInput) &&
7966         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7967       // Try to convert to the first EVT that the reg class contains.  If the
7968       // types are identical size, use a bitcast to convert (e.g. two differing
7969       // vector types).  Note: output bitcast is done at the end of
7970       // visitInlineAsm().
7971       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7972         // Exclude indirect inputs while they are unsupported because the code
7973         // to perform the load is missing and thus OpInfo.CallOperand still
7974         // refers to the input address rather than the pointed-to value.
7975         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7976           OpInfo.CallOperand =
7977               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7978         OpInfo.ConstraintVT = RegVT;
7979         // If the operand is an FP value and we want it in integer registers,
7980         // use the corresponding integer type. This turns an f64 value into
7981         // i64, which can be passed with two i32 values on a 32-bit machine.
7982       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7983         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7984         if (OpInfo.Type == InlineAsm::isInput)
7985           OpInfo.CallOperand =
7986               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7987         OpInfo.ConstraintVT = VT;
7988       }
7989     }
7990   }
7991 
7992   // No need to allocate a matching input constraint since the constraint it's
7993   // matching to has already been allocated.
7994   if (OpInfo.isMatchingInputConstraint())
7995     return;
7996 
7997   EVT ValueVT = OpInfo.ConstraintVT;
7998   if (OpInfo.ConstraintVT == MVT::Other)
7999     ValueVT = RegVT;
8000 
8001   // Initialize NumRegs.
8002   unsigned NumRegs = 1;
8003   if (OpInfo.ConstraintVT != MVT::Other)
8004     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8005 
8006   // If this is a constraint for a specific physical register, like {r17},
8007   // assign it now.
8008 
8009   // If this associated to a specific register, initialize iterator to correct
8010   // place. If virtual, make sure we have enough registers
8011 
8012   // Initialize iterator if necessary
8013   TargetRegisterClass::iterator I = RC->begin();
8014   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8015 
8016   // Do not check for single registers.
8017   if (AssignedReg) {
8018       for (; *I != AssignedReg; ++I)
8019         assert(I != RC->end() && "AssignedReg should be member of RC");
8020   }
8021 
8022   for (; NumRegs; --NumRegs, ++I) {
8023     assert(I != RC->end() && "Ran out of registers to allocate!");
8024     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8025     Regs.push_back(R);
8026   }
8027 
8028   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8029 }
8030 
8031 static unsigned
8032 findMatchingInlineAsmOperand(unsigned OperandNo,
8033                              const std::vector<SDValue> &AsmNodeOperands) {
8034   // Scan until we find the definition we already emitted of this operand.
8035   unsigned CurOp = InlineAsm::Op_FirstOperand;
8036   for (; OperandNo; --OperandNo) {
8037     // Advance to the next operand.
8038     unsigned OpFlag =
8039         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8040     assert((InlineAsm::isRegDefKind(OpFlag) ||
8041             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8042             InlineAsm::isMemKind(OpFlag)) &&
8043            "Skipped past definitions?");
8044     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8045   }
8046   return CurOp;
8047 }
8048 
8049 namespace {
8050 
8051 class ExtraFlags {
8052   unsigned Flags = 0;
8053 
8054 public:
8055   explicit ExtraFlags(const CallBase &Call) {
8056     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8057     if (IA->hasSideEffects())
8058       Flags |= InlineAsm::Extra_HasSideEffects;
8059     if (IA->isAlignStack())
8060       Flags |= InlineAsm::Extra_IsAlignStack;
8061     if (Call.isConvergent())
8062       Flags |= InlineAsm::Extra_IsConvergent;
8063     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8064   }
8065 
8066   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8067     // Ideally, we would only check against memory constraints.  However, the
8068     // meaning of an Other constraint can be target-specific and we can't easily
8069     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8070     // for Other constraints as well.
8071     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8072         OpInfo.ConstraintType == TargetLowering::C_Other) {
8073       if (OpInfo.Type == InlineAsm::isInput)
8074         Flags |= InlineAsm::Extra_MayLoad;
8075       else if (OpInfo.Type == InlineAsm::isOutput)
8076         Flags |= InlineAsm::Extra_MayStore;
8077       else if (OpInfo.Type == InlineAsm::isClobber)
8078         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8079     }
8080   }
8081 
8082   unsigned get() const { return Flags; }
8083 };
8084 
8085 } // end anonymous namespace
8086 
8087 /// visitInlineAsm - Handle a call to an InlineAsm object.
8088 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8089   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8090 
8091   /// ConstraintOperands - Information about all of the constraints.
8092   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8093 
8094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8095   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8096       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8097 
8098   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8099   // AsmDialect, MayLoad, MayStore).
8100   bool HasSideEffect = IA->hasSideEffects();
8101   ExtraFlags ExtraInfo(Call);
8102 
8103   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8104   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8105   unsigned NumMatchingOps = 0;
8106   for (auto &T : TargetConstraints) {
8107     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8108     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8109 
8110     // Compute the value type for each operand.
8111     if (OpInfo.Type == InlineAsm::isInput ||
8112         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8113       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8114 
8115       // Process the call argument. BasicBlocks are labels, currently appearing
8116       // only in asm's.
8117       if (isa<CallBrInst>(Call) &&
8118           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8119                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8120                         NumMatchingOps) &&
8121           (NumMatchingOps == 0 ||
8122            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8123                         NumMatchingOps))) {
8124         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8125         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8126         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8127       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8128         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8129       } else {
8130         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8131       }
8132 
8133       OpInfo.ConstraintVT =
8134           OpInfo
8135               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8136               .getSimpleVT();
8137     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8138       // The return value of the call is this value.  As such, there is no
8139       // corresponding argument.
8140       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8141       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8142         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8143             DAG.getDataLayout(), STy->getElementType(ResNo));
8144       } else {
8145         assert(ResNo == 0 && "Asm only has one result!");
8146         OpInfo.ConstraintVT =
8147             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8148       }
8149       ++ResNo;
8150     } else {
8151       OpInfo.ConstraintVT = MVT::Other;
8152     }
8153 
8154     if (OpInfo.hasMatchingInput())
8155       ++NumMatchingOps;
8156 
8157     if (!HasSideEffect)
8158       HasSideEffect = OpInfo.hasMemory(TLI);
8159 
8160     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8161     // FIXME: Could we compute this on OpInfo rather than T?
8162 
8163     // Compute the constraint code and ConstraintType to use.
8164     TLI.ComputeConstraintToUse(T, SDValue());
8165 
8166     if (T.ConstraintType == TargetLowering::C_Immediate &&
8167         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8168       // We've delayed emitting a diagnostic like the "n" constraint because
8169       // inlining could cause an integer showing up.
8170       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8171                                           "' expects an integer constant "
8172                                           "expression");
8173 
8174     ExtraInfo.update(T);
8175   }
8176 
8177 
8178   // We won't need to flush pending loads if this asm doesn't touch
8179   // memory and is nonvolatile.
8180   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8181 
8182   bool IsCallBr = isa<CallBrInst>(Call);
8183   if (IsCallBr) {
8184     // If this is a callbr we need to flush pending exports since inlineasm_br
8185     // is a terminator. We need to do this before nodes are glued to
8186     // the inlineasm_br node.
8187     Chain = getControlRoot();
8188   }
8189 
8190   // Second pass over the constraints: compute which constraint option to use.
8191   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8192     // If this is an output operand with a matching input operand, look up the
8193     // matching input. If their types mismatch, e.g. one is an integer, the
8194     // other is floating point, or their sizes are different, flag it as an
8195     // error.
8196     if (OpInfo.hasMatchingInput()) {
8197       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8198       patchMatchingInput(OpInfo, Input, DAG);
8199     }
8200 
8201     // Compute the constraint code and ConstraintType to use.
8202     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8203 
8204     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8205         OpInfo.Type == InlineAsm::isClobber)
8206       continue;
8207 
8208     // If this is a memory input, and if the operand is not indirect, do what we
8209     // need to provide an address for the memory input.
8210     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8211         !OpInfo.isIndirect) {
8212       assert((OpInfo.isMultipleAlternative ||
8213               (OpInfo.Type == InlineAsm::isInput)) &&
8214              "Can only indirectify direct input operands!");
8215 
8216       // Memory operands really want the address of the value.
8217       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8218 
8219       // There is no longer a Value* corresponding to this operand.
8220       OpInfo.CallOperandVal = nullptr;
8221 
8222       // It is now an indirect operand.
8223       OpInfo.isIndirect = true;
8224     }
8225 
8226   }
8227 
8228   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8229   std::vector<SDValue> AsmNodeOperands;
8230   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8231   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8232       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8233 
8234   // If we have a !srcloc metadata node associated with it, we want to attach
8235   // this to the ultimately generated inline asm machineinstr.  To do this, we
8236   // pass in the third operand as this (potentially null) inline asm MDNode.
8237   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8238   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8239 
8240   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8241   // bits as operand 3.
8242   AsmNodeOperands.push_back(DAG.getTargetConstant(
8243       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8244 
8245   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8246   // this, assign virtual and physical registers for inputs and otput.
8247   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8248     // Assign Registers.
8249     SDISelAsmOperandInfo &RefOpInfo =
8250         OpInfo.isMatchingInputConstraint()
8251             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8252             : OpInfo;
8253     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8254 
8255     auto DetectWriteToReservedRegister = [&]() {
8256       const MachineFunction &MF = DAG.getMachineFunction();
8257       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8258       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8259         if (Register::isPhysicalRegister(Reg) &&
8260             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8261           const char *RegName = TRI.getName(Reg);
8262           emitInlineAsmError(Call, "write to reserved register '" +
8263                                        Twine(RegName) + "'");
8264           return true;
8265         }
8266       }
8267       return false;
8268     };
8269 
8270     switch (OpInfo.Type) {
8271     case InlineAsm::isOutput:
8272       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8273         unsigned ConstraintID =
8274             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8275         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8276                "Failed to convert memory constraint code to constraint id.");
8277 
8278         // Add information to the INLINEASM node to know about this output.
8279         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8280         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8281         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8282                                                         MVT::i32));
8283         AsmNodeOperands.push_back(OpInfo.CallOperand);
8284       } else {
8285         // Otherwise, this outputs to a register (directly for C_Register /
8286         // C_RegisterClass, and a target-defined fashion for
8287         // C_Immediate/C_Other). Find a register that we can use.
8288         if (OpInfo.AssignedRegs.Regs.empty()) {
8289           emitInlineAsmError(
8290               Call, "couldn't allocate output register for constraint '" +
8291                         Twine(OpInfo.ConstraintCode) + "'");
8292           return;
8293         }
8294 
8295         if (DetectWriteToReservedRegister())
8296           return;
8297 
8298         // Add information to the INLINEASM node to know that this register is
8299         // set.
8300         OpInfo.AssignedRegs.AddInlineAsmOperands(
8301             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8302                                   : InlineAsm::Kind_RegDef,
8303             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8304       }
8305       break;
8306 
8307     case InlineAsm::isInput: {
8308       SDValue InOperandVal = OpInfo.CallOperand;
8309 
8310       if (OpInfo.isMatchingInputConstraint()) {
8311         // If this is required to match an output register we have already set,
8312         // just use its register.
8313         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8314                                                   AsmNodeOperands);
8315         unsigned OpFlag =
8316           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8317         if (InlineAsm::isRegDefKind(OpFlag) ||
8318             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8319           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8320           if (OpInfo.isIndirect) {
8321             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8322             emitInlineAsmError(Call, "inline asm not supported yet: "
8323                                      "don't know how to handle tied "
8324                                      "indirect register inputs");
8325             return;
8326           }
8327 
8328           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8329           SmallVector<unsigned, 4> Regs;
8330 
8331           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8332             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8333             MachineRegisterInfo &RegInfo =
8334                 DAG.getMachineFunction().getRegInfo();
8335             for (unsigned i = 0; i != NumRegs; ++i)
8336               Regs.push_back(RegInfo.createVirtualRegister(RC));
8337           } else {
8338             emitInlineAsmError(Call,
8339                                "inline asm error: This value type register "
8340                                "class is not natively supported!");
8341             return;
8342           }
8343 
8344           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8345 
8346           SDLoc dl = getCurSDLoc();
8347           // Use the produced MatchedRegs object to
8348           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8349           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8350                                            true, OpInfo.getMatchedOperand(), dl,
8351                                            DAG, AsmNodeOperands);
8352           break;
8353         }
8354 
8355         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8356         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8357                "Unexpected number of operands");
8358         // Add information to the INLINEASM node to know about this input.
8359         // See InlineAsm.h isUseOperandTiedToDef.
8360         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8361         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8362                                                     OpInfo.getMatchedOperand());
8363         AsmNodeOperands.push_back(DAG.getTargetConstant(
8364             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8365         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8366         break;
8367       }
8368 
8369       // Treat indirect 'X' constraint as memory.
8370       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8371           OpInfo.isIndirect)
8372         OpInfo.ConstraintType = TargetLowering::C_Memory;
8373 
8374       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8375           OpInfo.ConstraintType == TargetLowering::C_Other) {
8376         std::vector<SDValue> Ops;
8377         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8378                                           Ops, DAG);
8379         if (Ops.empty()) {
8380           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8381             if (isa<ConstantSDNode>(InOperandVal)) {
8382               emitInlineAsmError(Call, "value out of range for constraint '" +
8383                                            Twine(OpInfo.ConstraintCode) + "'");
8384               return;
8385             }
8386 
8387           emitInlineAsmError(Call,
8388                              "invalid operand for inline asm constraint '" +
8389                                  Twine(OpInfo.ConstraintCode) + "'");
8390           return;
8391         }
8392 
8393         // Add information to the INLINEASM node to know about this input.
8394         unsigned ResOpType =
8395           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8396         AsmNodeOperands.push_back(DAG.getTargetConstant(
8397             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8398         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8399         break;
8400       }
8401 
8402       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8403         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8404         assert(InOperandVal.getValueType() ==
8405                    TLI.getPointerTy(DAG.getDataLayout()) &&
8406                "Memory operands expect pointer values");
8407 
8408         unsigned ConstraintID =
8409             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8410         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8411                "Failed to convert memory constraint code to constraint id.");
8412 
8413         // Add information to the INLINEASM node to know about this input.
8414         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8415         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8416         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8417                                                         getCurSDLoc(),
8418                                                         MVT::i32));
8419         AsmNodeOperands.push_back(InOperandVal);
8420         break;
8421       }
8422 
8423       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8424               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8425              "Unknown constraint type!");
8426 
8427       // TODO: Support this.
8428       if (OpInfo.isIndirect) {
8429         emitInlineAsmError(
8430             Call, "Don't know how to handle indirect register inputs yet "
8431                   "for constraint '" +
8432                       Twine(OpInfo.ConstraintCode) + "'");
8433         return;
8434       }
8435 
8436       // Copy the input into the appropriate registers.
8437       if (OpInfo.AssignedRegs.Regs.empty()) {
8438         emitInlineAsmError(Call,
8439                            "couldn't allocate input reg for constraint '" +
8440                                Twine(OpInfo.ConstraintCode) + "'");
8441         return;
8442       }
8443 
8444       if (DetectWriteToReservedRegister())
8445         return;
8446 
8447       SDLoc dl = getCurSDLoc();
8448 
8449       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8450                                         &Call);
8451 
8452       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8453                                                dl, DAG, AsmNodeOperands);
8454       break;
8455     }
8456     case InlineAsm::isClobber:
8457       // Add the clobbered value to the operand list, so that the register
8458       // allocator is aware that the physreg got clobbered.
8459       if (!OpInfo.AssignedRegs.Regs.empty())
8460         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8461                                                  false, 0, getCurSDLoc(), DAG,
8462                                                  AsmNodeOperands);
8463       break;
8464     }
8465   }
8466 
8467   // Finish up input operands.  Set the input chain and add the flag last.
8468   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8469   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8470 
8471   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8472   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8473                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8474   Flag = Chain.getValue(1);
8475 
8476   // Do additional work to generate outputs.
8477 
8478   SmallVector<EVT, 1> ResultVTs;
8479   SmallVector<SDValue, 1> ResultValues;
8480   SmallVector<SDValue, 8> OutChains;
8481 
8482   llvm::Type *CallResultType = Call.getType();
8483   ArrayRef<Type *> ResultTypes;
8484   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8485     ResultTypes = StructResult->elements();
8486   else if (!CallResultType->isVoidTy())
8487     ResultTypes = makeArrayRef(CallResultType);
8488 
8489   auto CurResultType = ResultTypes.begin();
8490   auto handleRegAssign = [&](SDValue V) {
8491     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8492     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8493     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8494     ++CurResultType;
8495     // If the type of the inline asm call site return value is different but has
8496     // same size as the type of the asm output bitcast it.  One example of this
8497     // is for vectors with different width / number of elements.  This can
8498     // happen for register classes that can contain multiple different value
8499     // types.  The preg or vreg allocated may not have the same VT as was
8500     // expected.
8501     //
8502     // This can also happen for a return value that disagrees with the register
8503     // class it is put in, eg. a double in a general-purpose register on a
8504     // 32-bit machine.
8505     if (ResultVT != V.getValueType() &&
8506         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8507       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8508     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8509              V.getValueType().isInteger()) {
8510       // If a result value was tied to an input value, the computed result
8511       // may have a wider width than the expected result.  Extract the
8512       // relevant portion.
8513       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8514     }
8515     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8516     ResultVTs.push_back(ResultVT);
8517     ResultValues.push_back(V);
8518   };
8519 
8520   // Deal with output operands.
8521   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8522     if (OpInfo.Type == InlineAsm::isOutput) {
8523       SDValue Val;
8524       // Skip trivial output operands.
8525       if (OpInfo.AssignedRegs.Regs.empty())
8526         continue;
8527 
8528       switch (OpInfo.ConstraintType) {
8529       case TargetLowering::C_Register:
8530       case TargetLowering::C_RegisterClass:
8531         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8532                                                   Chain, &Flag, &Call);
8533         break;
8534       case TargetLowering::C_Immediate:
8535       case TargetLowering::C_Other:
8536         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8537                                               OpInfo, DAG);
8538         break;
8539       case TargetLowering::C_Memory:
8540         break; // Already handled.
8541       case TargetLowering::C_Unknown:
8542         assert(false && "Unexpected unknown constraint");
8543       }
8544 
8545       // Indirect output manifest as stores. Record output chains.
8546       if (OpInfo.isIndirect) {
8547         const Value *Ptr = OpInfo.CallOperandVal;
8548         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8549         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8550                                      MachinePointerInfo(Ptr));
8551         OutChains.push_back(Store);
8552       } else {
8553         // generate CopyFromRegs to associated registers.
8554         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8555         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8556           for (const SDValue &V : Val->op_values())
8557             handleRegAssign(V);
8558         } else
8559           handleRegAssign(Val);
8560       }
8561     }
8562   }
8563 
8564   // Set results.
8565   if (!ResultValues.empty()) {
8566     assert(CurResultType == ResultTypes.end() &&
8567            "Mismatch in number of ResultTypes");
8568     assert(ResultValues.size() == ResultTypes.size() &&
8569            "Mismatch in number of output operands in asm result");
8570 
8571     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8572                             DAG.getVTList(ResultVTs), ResultValues);
8573     setValue(&Call, V);
8574   }
8575 
8576   // Collect store chains.
8577   if (!OutChains.empty())
8578     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8579 
8580   // Only Update Root if inline assembly has a memory effect.
8581   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8582     DAG.setRoot(Chain);
8583 }
8584 
8585 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8586                                              const Twine &Message) {
8587   LLVMContext &Ctx = *DAG.getContext();
8588   Ctx.emitError(&Call, Message);
8589 
8590   // Make sure we leave the DAG in a valid state
8591   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8592   SmallVector<EVT, 1> ValueVTs;
8593   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8594 
8595   if (ValueVTs.empty())
8596     return;
8597 
8598   SmallVector<SDValue, 1> Ops;
8599   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8600     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8601 
8602   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8603 }
8604 
8605 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8606   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8607                           MVT::Other, getRoot(),
8608                           getValue(I.getArgOperand(0)),
8609                           DAG.getSrcValue(I.getArgOperand(0))));
8610 }
8611 
8612 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8613   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8614   const DataLayout &DL = DAG.getDataLayout();
8615   SDValue V = DAG.getVAArg(
8616       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8617       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8618       DL.getABITypeAlign(I.getType()).value());
8619   DAG.setRoot(V.getValue(1));
8620 
8621   if (I.getType()->isPointerTy())
8622     V = DAG.getPtrExtOrTrunc(
8623         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8624   setValue(&I, V);
8625 }
8626 
8627 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8628   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8629                           MVT::Other, getRoot(),
8630                           getValue(I.getArgOperand(0)),
8631                           DAG.getSrcValue(I.getArgOperand(0))));
8632 }
8633 
8634 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8635   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8636                           MVT::Other, getRoot(),
8637                           getValue(I.getArgOperand(0)),
8638                           getValue(I.getArgOperand(1)),
8639                           DAG.getSrcValue(I.getArgOperand(0)),
8640                           DAG.getSrcValue(I.getArgOperand(1))));
8641 }
8642 
8643 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8644                                                     const Instruction &I,
8645                                                     SDValue Op) {
8646   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8647   if (!Range)
8648     return Op;
8649 
8650   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8651   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8652     return Op;
8653 
8654   APInt Lo = CR.getUnsignedMin();
8655   if (!Lo.isMinValue())
8656     return Op;
8657 
8658   APInt Hi = CR.getUnsignedMax();
8659   unsigned Bits = std::max(Hi.getActiveBits(),
8660                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8661 
8662   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8663 
8664   SDLoc SL = getCurSDLoc();
8665 
8666   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8667                              DAG.getValueType(SmallVT));
8668   unsigned NumVals = Op.getNode()->getNumValues();
8669   if (NumVals == 1)
8670     return ZExt;
8671 
8672   SmallVector<SDValue, 4> Ops;
8673 
8674   Ops.push_back(ZExt);
8675   for (unsigned I = 1; I != NumVals; ++I)
8676     Ops.push_back(Op.getValue(I));
8677 
8678   return DAG.getMergeValues(Ops, SL);
8679 }
8680 
8681 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8682 /// the call being lowered.
8683 ///
8684 /// This is a helper for lowering intrinsics that follow a target calling
8685 /// convention or require stack pointer adjustment. Only a subset of the
8686 /// intrinsic's operands need to participate in the calling convention.
8687 void SelectionDAGBuilder::populateCallLoweringInfo(
8688     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8689     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8690     bool IsPatchPoint) {
8691   TargetLowering::ArgListTy Args;
8692   Args.reserve(NumArgs);
8693 
8694   // Populate the argument list.
8695   // Attributes for args start at offset 1, after the return attribute.
8696   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8697        ArgI != ArgE; ++ArgI) {
8698     const Value *V = Call->getOperand(ArgI);
8699 
8700     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8701 
8702     TargetLowering::ArgListEntry Entry;
8703     Entry.Node = getValue(V);
8704     Entry.Ty = V->getType();
8705     Entry.setAttributes(Call, ArgI);
8706     Args.push_back(Entry);
8707   }
8708 
8709   CLI.setDebugLoc(getCurSDLoc())
8710       .setChain(getRoot())
8711       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8712       .setDiscardResult(Call->use_empty())
8713       .setIsPatchPoint(IsPatchPoint)
8714       .setIsPreallocated(
8715           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8716 }
8717 
8718 /// Add a stack map intrinsic call's live variable operands to a stackmap
8719 /// or patchpoint target node's operand list.
8720 ///
8721 /// Constants are converted to TargetConstants purely as an optimization to
8722 /// avoid constant materialization and register allocation.
8723 ///
8724 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8725 /// generate addess computation nodes, and so FinalizeISel can convert the
8726 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8727 /// address materialization and register allocation, but may also be required
8728 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8729 /// alloca in the entry block, then the runtime may assume that the alloca's
8730 /// StackMap location can be read immediately after compilation and that the
8731 /// location is valid at any point during execution (this is similar to the
8732 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8733 /// only available in a register, then the runtime would need to trap when
8734 /// execution reaches the StackMap in order to read the alloca's location.
8735 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8736                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8737                                 SelectionDAGBuilder &Builder) {
8738   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8739     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8740     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8741       Ops.push_back(
8742         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8743       Ops.push_back(
8744         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8745     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8746       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8747       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8748           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8749     } else
8750       Ops.push_back(OpVal);
8751   }
8752 }
8753 
8754 /// Lower llvm.experimental.stackmap directly to its target opcode.
8755 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8756   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8757   //                                  [live variables...])
8758 
8759   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8760 
8761   SDValue Chain, InFlag, Callee, NullPtr;
8762   SmallVector<SDValue, 32> Ops;
8763 
8764   SDLoc DL = getCurSDLoc();
8765   Callee = getValue(CI.getCalledOperand());
8766   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8767 
8768   // The stackmap intrinsic only records the live variables (the arguments
8769   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8770   // intrinsic, this won't be lowered to a function call. This means we don't
8771   // have to worry about calling conventions and target specific lowering code.
8772   // Instead we perform the call lowering right here.
8773   //
8774   // chain, flag = CALLSEQ_START(chain, 0, 0)
8775   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8776   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8777   //
8778   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8779   InFlag = Chain.getValue(1);
8780 
8781   // Add the <id> and <numBytes> constants.
8782   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8783   Ops.push_back(DAG.getTargetConstant(
8784                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8785   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8786   Ops.push_back(DAG.getTargetConstant(
8787                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8788                   MVT::i32));
8789 
8790   // Push live variables for the stack map.
8791   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8792 
8793   // We are not pushing any register mask info here on the operands list,
8794   // because the stackmap doesn't clobber anything.
8795 
8796   // Push the chain and the glue flag.
8797   Ops.push_back(Chain);
8798   Ops.push_back(InFlag);
8799 
8800   // Create the STACKMAP node.
8801   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8802   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8803   Chain = SDValue(SM, 0);
8804   InFlag = Chain.getValue(1);
8805 
8806   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8807 
8808   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8809 
8810   // Set the root to the target-lowered call chain.
8811   DAG.setRoot(Chain);
8812 
8813   // Inform the Frame Information that we have a stackmap in this function.
8814   FuncInfo.MF->getFrameInfo().setHasStackMap();
8815 }
8816 
8817 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8818 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8819                                           const BasicBlock *EHPadBB) {
8820   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8821   //                                                 i32 <numBytes>,
8822   //                                                 i8* <target>,
8823   //                                                 i32 <numArgs>,
8824   //                                                 [Args...],
8825   //                                                 [live variables...])
8826 
8827   CallingConv::ID CC = CB.getCallingConv();
8828   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8829   bool HasDef = !CB.getType()->isVoidTy();
8830   SDLoc dl = getCurSDLoc();
8831   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8832 
8833   // Handle immediate and symbolic callees.
8834   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8835     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8836                                    /*isTarget=*/true);
8837   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8838     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8839                                          SDLoc(SymbolicCallee),
8840                                          SymbolicCallee->getValueType(0));
8841 
8842   // Get the real number of arguments participating in the call <numArgs>
8843   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8844   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8845 
8846   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8847   // Intrinsics include all meta-operands up to but not including CC.
8848   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8849   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8850          "Not enough arguments provided to the patchpoint intrinsic");
8851 
8852   // For AnyRegCC the arguments are lowered later on manually.
8853   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8854   Type *ReturnTy =
8855       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8856 
8857   TargetLowering::CallLoweringInfo CLI(DAG);
8858   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8859                            ReturnTy, true);
8860   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8861 
8862   SDNode *CallEnd = Result.second.getNode();
8863   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8864     CallEnd = CallEnd->getOperand(0).getNode();
8865 
8866   /// Get a call instruction from the call sequence chain.
8867   /// Tail calls are not allowed.
8868   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8869          "Expected a callseq node.");
8870   SDNode *Call = CallEnd->getOperand(0).getNode();
8871   bool HasGlue = Call->getGluedNode();
8872 
8873   // Replace the target specific call node with the patchable intrinsic.
8874   SmallVector<SDValue, 8> Ops;
8875 
8876   // Add the <id> and <numBytes> constants.
8877   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
8878   Ops.push_back(DAG.getTargetConstant(
8879                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8880   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
8881   Ops.push_back(DAG.getTargetConstant(
8882                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8883                   MVT::i32));
8884 
8885   // Add the callee.
8886   Ops.push_back(Callee);
8887 
8888   // Adjust <numArgs> to account for any arguments that have been passed on the
8889   // stack instead.
8890   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8891   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8892   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8893   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8894 
8895   // Add the calling convention
8896   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8897 
8898   // Add the arguments we omitted previously. The register allocator should
8899   // place these in any free register.
8900   if (IsAnyRegCC)
8901     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8902       Ops.push_back(getValue(CB.getArgOperand(i)));
8903 
8904   // Push the arguments from the call instruction up to the register mask.
8905   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8906   Ops.append(Call->op_begin() + 2, e);
8907 
8908   // Push live variables for the stack map.
8909   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
8910 
8911   // Push the register mask info.
8912   if (HasGlue)
8913     Ops.push_back(*(Call->op_end()-2));
8914   else
8915     Ops.push_back(*(Call->op_end()-1));
8916 
8917   // Push the chain (this is originally the first operand of the call, but
8918   // becomes now the last or second to last operand).
8919   Ops.push_back(*(Call->op_begin()));
8920 
8921   // Push the glue flag (last operand).
8922   if (HasGlue)
8923     Ops.push_back(*(Call->op_end()-1));
8924 
8925   SDVTList NodeTys;
8926   if (IsAnyRegCC && HasDef) {
8927     // Create the return types based on the intrinsic definition
8928     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8929     SmallVector<EVT, 3> ValueVTs;
8930     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
8931     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8932 
8933     // There is always a chain and a glue type at the end
8934     ValueVTs.push_back(MVT::Other);
8935     ValueVTs.push_back(MVT::Glue);
8936     NodeTys = DAG.getVTList(ValueVTs);
8937   } else
8938     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8939 
8940   // Replace the target specific call node with a PATCHPOINT node.
8941   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8942                                          dl, NodeTys, Ops);
8943 
8944   // Update the NodeMap.
8945   if (HasDef) {
8946     if (IsAnyRegCC)
8947       setValue(&CB, SDValue(MN, 0));
8948     else
8949       setValue(&CB, Result.first);
8950   }
8951 
8952   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8953   // call sequence. Furthermore the location of the chain and glue can change
8954   // when the AnyReg calling convention is used and the intrinsic returns a
8955   // value.
8956   if (IsAnyRegCC && HasDef) {
8957     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8958     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8959     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8960   } else
8961     DAG.ReplaceAllUsesWith(Call, MN);
8962   DAG.DeleteNode(Call);
8963 
8964   // Inform the Frame Information that we have a patchpoint in this function.
8965   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8966 }
8967 
8968 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8969                                             unsigned Intrinsic) {
8970   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8971   SDValue Op1 = getValue(I.getArgOperand(0));
8972   SDValue Op2;
8973   if (I.getNumArgOperands() > 1)
8974     Op2 = getValue(I.getArgOperand(1));
8975   SDLoc dl = getCurSDLoc();
8976   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8977   SDValue Res;
8978   FastMathFlags FMF;
8979   if (isa<FPMathOperator>(I))
8980     FMF = I.getFastMathFlags();
8981 
8982   switch (Intrinsic) {
8983   case Intrinsic::experimental_vector_reduce_v2_fadd:
8984     if (FMF.allowReassoc())
8985       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8986                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8987     else
8988       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8989     break;
8990   case Intrinsic::experimental_vector_reduce_v2_fmul:
8991     if (FMF.allowReassoc())
8992       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8993                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8994     else
8995       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8996     break;
8997   case Intrinsic::experimental_vector_reduce_add:
8998     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8999     break;
9000   case Intrinsic::experimental_vector_reduce_mul:
9001     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9002     break;
9003   case Intrinsic::experimental_vector_reduce_and:
9004     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9005     break;
9006   case Intrinsic::experimental_vector_reduce_or:
9007     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9008     break;
9009   case Intrinsic::experimental_vector_reduce_xor:
9010     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9011     break;
9012   case Intrinsic::experimental_vector_reduce_smax:
9013     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9014     break;
9015   case Intrinsic::experimental_vector_reduce_smin:
9016     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9017     break;
9018   case Intrinsic::experimental_vector_reduce_umax:
9019     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9020     break;
9021   case Intrinsic::experimental_vector_reduce_umin:
9022     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9023     break;
9024   case Intrinsic::experimental_vector_reduce_fmax:
9025     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
9026     break;
9027   case Intrinsic::experimental_vector_reduce_fmin:
9028     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
9029     break;
9030   default:
9031     llvm_unreachable("Unhandled vector reduce intrinsic");
9032   }
9033   setValue(&I, Res);
9034 }
9035 
9036 /// Returns an AttributeList representing the attributes applied to the return
9037 /// value of the given call.
9038 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9039   SmallVector<Attribute::AttrKind, 2> Attrs;
9040   if (CLI.RetSExt)
9041     Attrs.push_back(Attribute::SExt);
9042   if (CLI.RetZExt)
9043     Attrs.push_back(Attribute::ZExt);
9044   if (CLI.IsInReg)
9045     Attrs.push_back(Attribute::InReg);
9046 
9047   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9048                             Attrs);
9049 }
9050 
9051 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9052 /// implementation, which just calls LowerCall.
9053 /// FIXME: When all targets are
9054 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9055 std::pair<SDValue, SDValue>
9056 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9057   // Handle the incoming return values from the call.
9058   CLI.Ins.clear();
9059   Type *OrigRetTy = CLI.RetTy;
9060   SmallVector<EVT, 4> RetTys;
9061   SmallVector<uint64_t, 4> Offsets;
9062   auto &DL = CLI.DAG.getDataLayout();
9063   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9064 
9065   if (CLI.IsPostTypeLegalization) {
9066     // If we are lowering a libcall after legalization, split the return type.
9067     SmallVector<EVT, 4> OldRetTys;
9068     SmallVector<uint64_t, 4> OldOffsets;
9069     RetTys.swap(OldRetTys);
9070     Offsets.swap(OldOffsets);
9071 
9072     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9073       EVT RetVT = OldRetTys[i];
9074       uint64_t Offset = OldOffsets[i];
9075       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9076       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9077       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9078       RetTys.append(NumRegs, RegisterVT);
9079       for (unsigned j = 0; j != NumRegs; ++j)
9080         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9081     }
9082   }
9083 
9084   SmallVector<ISD::OutputArg, 4> Outs;
9085   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9086 
9087   bool CanLowerReturn =
9088       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9089                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9090 
9091   SDValue DemoteStackSlot;
9092   int DemoteStackIdx = -100;
9093   if (!CanLowerReturn) {
9094     // FIXME: equivalent assert?
9095     // assert(!CS.hasInAllocaArgument() &&
9096     //        "sret demotion is incompatible with inalloca");
9097     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9098     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9099     MachineFunction &MF = CLI.DAG.getMachineFunction();
9100     DemoteStackIdx =
9101         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9102     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9103                                               DL.getAllocaAddrSpace());
9104 
9105     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9106     ArgListEntry Entry;
9107     Entry.Node = DemoteStackSlot;
9108     Entry.Ty = StackSlotPtrType;
9109     Entry.IsSExt = false;
9110     Entry.IsZExt = false;
9111     Entry.IsInReg = false;
9112     Entry.IsSRet = true;
9113     Entry.IsNest = false;
9114     Entry.IsByVal = false;
9115     Entry.IsReturned = false;
9116     Entry.IsSwiftSelf = false;
9117     Entry.IsSwiftError = false;
9118     Entry.IsCFGuardTarget = false;
9119     Entry.Alignment = Alignment;
9120     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9121     CLI.NumFixedArgs += 1;
9122     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9123 
9124     // sret demotion isn't compatible with tail-calls, since the sret argument
9125     // points into the callers stack frame.
9126     CLI.IsTailCall = false;
9127   } else {
9128     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9129         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9130     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9131       ISD::ArgFlagsTy Flags;
9132       if (NeedsRegBlock) {
9133         Flags.setInConsecutiveRegs();
9134         if (I == RetTys.size() - 1)
9135           Flags.setInConsecutiveRegsLast();
9136       }
9137       EVT VT = RetTys[I];
9138       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9139                                                      CLI.CallConv, VT);
9140       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9141                                                        CLI.CallConv, VT);
9142       for (unsigned i = 0; i != NumRegs; ++i) {
9143         ISD::InputArg MyFlags;
9144         MyFlags.Flags = Flags;
9145         MyFlags.VT = RegisterVT;
9146         MyFlags.ArgVT = VT;
9147         MyFlags.Used = CLI.IsReturnValueUsed;
9148         if (CLI.RetTy->isPointerTy()) {
9149           MyFlags.Flags.setPointer();
9150           MyFlags.Flags.setPointerAddrSpace(
9151               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9152         }
9153         if (CLI.RetSExt)
9154           MyFlags.Flags.setSExt();
9155         if (CLI.RetZExt)
9156           MyFlags.Flags.setZExt();
9157         if (CLI.IsInReg)
9158           MyFlags.Flags.setInReg();
9159         CLI.Ins.push_back(MyFlags);
9160       }
9161     }
9162   }
9163 
9164   // We push in swifterror return as the last element of CLI.Ins.
9165   ArgListTy &Args = CLI.getArgs();
9166   if (supportSwiftError()) {
9167     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9168       if (Args[i].IsSwiftError) {
9169         ISD::InputArg MyFlags;
9170         MyFlags.VT = getPointerTy(DL);
9171         MyFlags.ArgVT = EVT(getPointerTy(DL));
9172         MyFlags.Flags.setSwiftError();
9173         CLI.Ins.push_back(MyFlags);
9174       }
9175     }
9176   }
9177 
9178   // Handle all of the outgoing arguments.
9179   CLI.Outs.clear();
9180   CLI.OutVals.clear();
9181   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9182     SmallVector<EVT, 4> ValueVTs;
9183     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9184     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9185     Type *FinalType = Args[i].Ty;
9186     if (Args[i].IsByVal)
9187       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9188     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9189         FinalType, CLI.CallConv, CLI.IsVarArg);
9190     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9191          ++Value) {
9192       EVT VT = ValueVTs[Value];
9193       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9194       SDValue Op = SDValue(Args[i].Node.getNode(),
9195                            Args[i].Node.getResNo() + Value);
9196       ISD::ArgFlagsTy Flags;
9197 
9198       // Certain targets (such as MIPS), may have a different ABI alignment
9199       // for a type depending on the context. Give the target a chance to
9200       // specify the alignment it wants.
9201       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9202 
9203       if (Args[i].Ty->isPointerTy()) {
9204         Flags.setPointer();
9205         Flags.setPointerAddrSpace(
9206             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9207       }
9208       if (Args[i].IsZExt)
9209         Flags.setZExt();
9210       if (Args[i].IsSExt)
9211         Flags.setSExt();
9212       if (Args[i].IsInReg) {
9213         // If we are using vectorcall calling convention, a structure that is
9214         // passed InReg - is surely an HVA
9215         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9216             isa<StructType>(FinalType)) {
9217           // The first value of a structure is marked
9218           if (0 == Value)
9219             Flags.setHvaStart();
9220           Flags.setHva();
9221         }
9222         // Set InReg Flag
9223         Flags.setInReg();
9224       }
9225       if (Args[i].IsSRet)
9226         Flags.setSRet();
9227       if (Args[i].IsSwiftSelf)
9228         Flags.setSwiftSelf();
9229       if (Args[i].IsSwiftError)
9230         Flags.setSwiftError();
9231       if (Args[i].IsCFGuardTarget)
9232         Flags.setCFGuardTarget();
9233       if (Args[i].IsByVal)
9234         Flags.setByVal();
9235       if (Args[i].IsPreallocated) {
9236         Flags.setPreallocated();
9237         // Set the byval flag for CCAssignFn callbacks that don't know about
9238         // preallocated.  This way we can know how many bytes we should've
9239         // allocated and how many bytes a callee cleanup function will pop.  If
9240         // we port preallocated to more targets, we'll have to add custom
9241         // preallocated handling in the various CC lowering callbacks.
9242         Flags.setByVal();
9243       }
9244       if (Args[i].IsInAlloca) {
9245         Flags.setInAlloca();
9246         // Set the byval flag for CCAssignFn callbacks that don't know about
9247         // inalloca.  This way we can know how many bytes we should've allocated
9248         // and how many bytes a callee cleanup function will pop.  If we port
9249         // inalloca to more targets, we'll have to add custom inalloca handling
9250         // in the various CC lowering callbacks.
9251         Flags.setByVal();
9252       }
9253       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9254         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9255         Type *ElementTy = Ty->getElementType();
9256 
9257         unsigned FrameSize = DL.getTypeAllocSize(
9258             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9259         Flags.setByValSize(FrameSize);
9260 
9261         // info is not there but there are cases it cannot get right.
9262         Align FrameAlign;
9263         if (auto MA = Args[i].Alignment)
9264           FrameAlign = *MA;
9265         else
9266           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9267         Flags.setByValAlign(FrameAlign);
9268       }
9269       if (Args[i].IsNest)
9270         Flags.setNest();
9271       if (NeedsRegBlock)
9272         Flags.setInConsecutiveRegs();
9273       Flags.setOrigAlign(OriginalAlignment);
9274 
9275       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9276                                                  CLI.CallConv, VT);
9277       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9278                                                         CLI.CallConv, VT);
9279       SmallVector<SDValue, 4> Parts(NumParts);
9280       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9281 
9282       if (Args[i].IsSExt)
9283         ExtendKind = ISD::SIGN_EXTEND;
9284       else if (Args[i].IsZExt)
9285         ExtendKind = ISD::ZERO_EXTEND;
9286 
9287       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9288       // for now.
9289       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9290           CanLowerReturn) {
9291         assert((CLI.RetTy == Args[i].Ty ||
9292                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9293                  CLI.RetTy->getPointerAddressSpace() ==
9294                      Args[i].Ty->getPointerAddressSpace())) &&
9295                RetTys.size() == NumValues && "unexpected use of 'returned'");
9296         // Before passing 'returned' to the target lowering code, ensure that
9297         // either the register MVT and the actual EVT are the same size or that
9298         // the return value and argument are extended in the same way; in these
9299         // cases it's safe to pass the argument register value unchanged as the
9300         // return register value (although it's at the target's option whether
9301         // to do so)
9302         // TODO: allow code generation to take advantage of partially preserved
9303         // registers rather than clobbering the entire register when the
9304         // parameter extension method is not compatible with the return
9305         // extension method
9306         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9307             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9308              CLI.RetZExt == Args[i].IsZExt))
9309           Flags.setReturned();
9310       }
9311 
9312       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9313                      CLI.CallConv, ExtendKind);
9314 
9315       for (unsigned j = 0; j != NumParts; ++j) {
9316         // if it isn't first piece, alignment must be 1
9317         // For scalable vectors the scalable part is currently handled
9318         // by individual targets, so we just use the known minimum size here.
9319         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9320                     i < CLI.NumFixedArgs, i,
9321                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9322         if (NumParts > 1 && j == 0)
9323           MyFlags.Flags.setSplit();
9324         else if (j != 0) {
9325           MyFlags.Flags.setOrigAlign(Align(1));
9326           if (j == NumParts - 1)
9327             MyFlags.Flags.setSplitEnd();
9328         }
9329 
9330         CLI.Outs.push_back(MyFlags);
9331         CLI.OutVals.push_back(Parts[j]);
9332       }
9333 
9334       if (NeedsRegBlock && Value == NumValues - 1)
9335         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9336     }
9337   }
9338 
9339   SmallVector<SDValue, 4> InVals;
9340   CLI.Chain = LowerCall(CLI, InVals);
9341 
9342   // Update CLI.InVals to use outside of this function.
9343   CLI.InVals = InVals;
9344 
9345   // Verify that the target's LowerCall behaved as expected.
9346   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9347          "LowerCall didn't return a valid chain!");
9348   assert((!CLI.IsTailCall || InVals.empty()) &&
9349          "LowerCall emitted a return value for a tail call!");
9350   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9351          "LowerCall didn't emit the correct number of values!");
9352 
9353   // For a tail call, the return value is merely live-out and there aren't
9354   // any nodes in the DAG representing it. Return a special value to
9355   // indicate that a tail call has been emitted and no more Instructions
9356   // should be processed in the current block.
9357   if (CLI.IsTailCall) {
9358     CLI.DAG.setRoot(CLI.Chain);
9359     return std::make_pair(SDValue(), SDValue());
9360   }
9361 
9362 #ifndef NDEBUG
9363   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9364     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9365     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9366            "LowerCall emitted a value with the wrong type!");
9367   }
9368 #endif
9369 
9370   SmallVector<SDValue, 4> ReturnValues;
9371   if (!CanLowerReturn) {
9372     // The instruction result is the result of loading from the
9373     // hidden sret parameter.
9374     SmallVector<EVT, 1> PVTs;
9375     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9376 
9377     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9378     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9379     EVT PtrVT = PVTs[0];
9380 
9381     unsigned NumValues = RetTys.size();
9382     ReturnValues.resize(NumValues);
9383     SmallVector<SDValue, 4> Chains(NumValues);
9384 
9385     // An aggregate return value cannot wrap around the address space, so
9386     // offsets to its parts don't wrap either.
9387     SDNodeFlags Flags;
9388     Flags.setNoUnsignedWrap(true);
9389 
9390     MachineFunction &MF = CLI.DAG.getMachineFunction();
9391     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9392     for (unsigned i = 0; i < NumValues; ++i) {
9393       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9394                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9395                                                         PtrVT), Flags);
9396       SDValue L = CLI.DAG.getLoad(
9397           RetTys[i], CLI.DL, CLI.Chain, Add,
9398           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9399                                             DemoteStackIdx, Offsets[i]),
9400           HiddenSRetAlign);
9401       ReturnValues[i] = L;
9402       Chains[i] = L.getValue(1);
9403     }
9404 
9405     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9406   } else {
9407     // Collect the legal value parts into potentially illegal values
9408     // that correspond to the original function's return values.
9409     Optional<ISD::NodeType> AssertOp;
9410     if (CLI.RetSExt)
9411       AssertOp = ISD::AssertSext;
9412     else if (CLI.RetZExt)
9413       AssertOp = ISD::AssertZext;
9414     unsigned CurReg = 0;
9415     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9416       EVT VT = RetTys[I];
9417       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9418                                                      CLI.CallConv, VT);
9419       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9420                                                        CLI.CallConv, VT);
9421 
9422       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9423                                               NumRegs, RegisterVT, VT, nullptr,
9424                                               CLI.CallConv, AssertOp));
9425       CurReg += NumRegs;
9426     }
9427 
9428     // For a function returning void, there is no return value. We can't create
9429     // such a node, so we just return a null return value in that case. In
9430     // that case, nothing will actually look at the value.
9431     if (ReturnValues.empty())
9432       return std::make_pair(SDValue(), CLI.Chain);
9433   }
9434 
9435   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9436                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9437   return std::make_pair(Res, CLI.Chain);
9438 }
9439 
9440 void TargetLowering::LowerOperationWrapper(SDNode *N,
9441                                            SmallVectorImpl<SDValue> &Results,
9442                                            SelectionDAG &DAG) const {
9443   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9444     Results.push_back(Res);
9445 }
9446 
9447 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9448   llvm_unreachable("LowerOperation not implemented for this target!");
9449 }
9450 
9451 void
9452 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9453   SDValue Op = getNonRegisterValue(V);
9454   assert((Op.getOpcode() != ISD::CopyFromReg ||
9455           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9456          "Copy from a reg to the same reg!");
9457   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9458 
9459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9460   // If this is an InlineAsm we have to match the registers required, not the
9461   // notional registers required by the type.
9462 
9463   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9464                    None); // This is not an ABI copy.
9465   SDValue Chain = DAG.getEntryNode();
9466 
9467   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9468                               FuncInfo.PreferredExtendType.end())
9469                                  ? ISD::ANY_EXTEND
9470                                  : FuncInfo.PreferredExtendType[V];
9471   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9472   PendingExports.push_back(Chain);
9473 }
9474 
9475 #include "llvm/CodeGen/SelectionDAGISel.h"
9476 
9477 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9478 /// entry block, return true.  This includes arguments used by switches, since
9479 /// the switch may expand into multiple basic blocks.
9480 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9481   // With FastISel active, we may be splitting blocks, so force creation
9482   // of virtual registers for all non-dead arguments.
9483   if (FastISel)
9484     return A->use_empty();
9485 
9486   const BasicBlock &Entry = A->getParent()->front();
9487   for (const User *U : A->users())
9488     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9489       return false;  // Use not in entry block.
9490 
9491   return true;
9492 }
9493 
9494 using ArgCopyElisionMapTy =
9495     DenseMap<const Argument *,
9496              std::pair<const AllocaInst *, const StoreInst *>>;
9497 
9498 /// Scan the entry block of the function in FuncInfo for arguments that look
9499 /// like copies into a local alloca. Record any copied arguments in
9500 /// ArgCopyElisionCandidates.
9501 static void
9502 findArgumentCopyElisionCandidates(const DataLayout &DL,
9503                                   FunctionLoweringInfo *FuncInfo,
9504                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9505   // Record the state of every static alloca used in the entry block. Argument
9506   // allocas are all used in the entry block, so we need approximately as many
9507   // entries as we have arguments.
9508   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9509   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9510   unsigned NumArgs = FuncInfo->Fn->arg_size();
9511   StaticAllocas.reserve(NumArgs * 2);
9512 
9513   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9514     if (!V)
9515       return nullptr;
9516     V = V->stripPointerCasts();
9517     const auto *AI = dyn_cast<AllocaInst>(V);
9518     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9519       return nullptr;
9520     auto Iter = StaticAllocas.insert({AI, Unknown});
9521     return &Iter.first->second;
9522   };
9523 
9524   // Look for stores of arguments to static allocas. Look through bitcasts and
9525   // GEPs to handle type coercions, as long as the alloca is fully initialized
9526   // by the store. Any non-store use of an alloca escapes it and any subsequent
9527   // unanalyzed store might write it.
9528   // FIXME: Handle structs initialized with multiple stores.
9529   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9530     // Look for stores, and handle non-store uses conservatively.
9531     const auto *SI = dyn_cast<StoreInst>(&I);
9532     if (!SI) {
9533       // We will look through cast uses, so ignore them completely.
9534       if (I.isCast())
9535         continue;
9536       // Ignore debug info intrinsics, they don't escape or store to allocas.
9537       if (isa<DbgInfoIntrinsic>(I))
9538         continue;
9539       // This is an unknown instruction. Assume it escapes or writes to all
9540       // static alloca operands.
9541       for (const Use &U : I.operands()) {
9542         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9543           *Info = StaticAllocaInfo::Clobbered;
9544       }
9545       continue;
9546     }
9547 
9548     // If the stored value is a static alloca, mark it as escaped.
9549     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9550       *Info = StaticAllocaInfo::Clobbered;
9551 
9552     // Check if the destination is a static alloca.
9553     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9554     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9555     if (!Info)
9556       continue;
9557     const AllocaInst *AI = cast<AllocaInst>(Dst);
9558 
9559     // Skip allocas that have been initialized or clobbered.
9560     if (*Info != StaticAllocaInfo::Unknown)
9561       continue;
9562 
9563     // Check if the stored value is an argument, and that this store fully
9564     // initializes the alloca. Don't elide copies from the same argument twice.
9565     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9566     const auto *Arg = dyn_cast<Argument>(Val);
9567     if (!Arg || Arg->hasPassPointeeByValueAttr() ||
9568         Arg->getType()->isEmptyTy() ||
9569         DL.getTypeStoreSize(Arg->getType()) !=
9570             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9571         ArgCopyElisionCandidates.count(Arg)) {
9572       *Info = StaticAllocaInfo::Clobbered;
9573       continue;
9574     }
9575 
9576     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9577                       << '\n');
9578 
9579     // Mark this alloca and store for argument copy elision.
9580     *Info = StaticAllocaInfo::Elidable;
9581     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9582 
9583     // Stop scanning if we've seen all arguments. This will happen early in -O0
9584     // builds, which is useful, because -O0 builds have large entry blocks and
9585     // many allocas.
9586     if (ArgCopyElisionCandidates.size() == NumArgs)
9587       break;
9588   }
9589 }
9590 
9591 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9592 /// ArgVal is a load from a suitable fixed stack object.
9593 static void tryToElideArgumentCopy(
9594     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9595     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9596     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9597     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9598     SDValue ArgVal, bool &ArgHasUses) {
9599   // Check if this is a load from a fixed stack object.
9600   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9601   if (!LNode)
9602     return;
9603   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9604   if (!FINode)
9605     return;
9606 
9607   // Check that the fixed stack object is the right size and alignment.
9608   // Look at the alignment that the user wrote on the alloca instead of looking
9609   // at the stack object.
9610   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9611   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9612   const AllocaInst *AI = ArgCopyIter->second.first;
9613   int FixedIndex = FINode->getIndex();
9614   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9615   int OldIndex = AllocaIndex;
9616   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9617   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9618     LLVM_DEBUG(
9619         dbgs() << "  argument copy elision failed due to bad fixed stack "
9620                   "object size\n");
9621     return;
9622   }
9623   Align RequiredAlignment = AI->getAlign();
9624   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9625     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9626                          "greater than stack argument alignment ("
9627                       << DebugStr(RequiredAlignment) << " vs "
9628                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9629     return;
9630   }
9631 
9632   // Perform the elision. Delete the old stack object and replace its only use
9633   // in the variable info map. Mark the stack object as mutable.
9634   LLVM_DEBUG({
9635     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9636            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9637            << '\n';
9638   });
9639   MFI.RemoveStackObject(OldIndex);
9640   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9641   AllocaIndex = FixedIndex;
9642   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9643   Chains.push_back(ArgVal.getValue(1));
9644 
9645   // Avoid emitting code for the store implementing the copy.
9646   const StoreInst *SI = ArgCopyIter->second.second;
9647   ElidedArgCopyInstrs.insert(SI);
9648 
9649   // Check for uses of the argument again so that we can avoid exporting ArgVal
9650   // if it is't used by anything other than the store.
9651   for (const Value *U : Arg.users()) {
9652     if (U != SI) {
9653       ArgHasUses = true;
9654       break;
9655     }
9656   }
9657 }
9658 
9659 void SelectionDAGISel::LowerArguments(const Function &F) {
9660   SelectionDAG &DAG = SDB->DAG;
9661   SDLoc dl = SDB->getCurSDLoc();
9662   const DataLayout &DL = DAG.getDataLayout();
9663   SmallVector<ISD::InputArg, 16> Ins;
9664 
9665   // In Naked functions we aren't going to save any registers.
9666   if (F.hasFnAttribute(Attribute::Naked))
9667     return;
9668 
9669   if (!FuncInfo->CanLowerReturn) {
9670     // Put in an sret pointer parameter before all the other parameters.
9671     SmallVector<EVT, 1> ValueVTs;
9672     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9673                     F.getReturnType()->getPointerTo(
9674                         DAG.getDataLayout().getAllocaAddrSpace()),
9675                     ValueVTs);
9676 
9677     // NOTE: Assuming that a pointer will never break down to more than one VT
9678     // or one register.
9679     ISD::ArgFlagsTy Flags;
9680     Flags.setSRet();
9681     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9682     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9683                          ISD::InputArg::NoArgIndex, 0);
9684     Ins.push_back(RetArg);
9685   }
9686 
9687   // Look for stores of arguments to static allocas. Mark such arguments with a
9688   // flag to ask the target to give us the memory location of that argument if
9689   // available.
9690   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9691   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9692                                     ArgCopyElisionCandidates);
9693 
9694   // Set up the incoming argument description vector.
9695   for (const Argument &Arg : F.args()) {
9696     unsigned ArgNo = Arg.getArgNo();
9697     SmallVector<EVT, 4> ValueVTs;
9698     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9699     bool isArgValueUsed = !Arg.use_empty();
9700     unsigned PartBase = 0;
9701     Type *FinalType = Arg.getType();
9702     if (Arg.hasAttribute(Attribute::ByVal))
9703       FinalType = Arg.getParamByValType();
9704     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9705         FinalType, F.getCallingConv(), F.isVarArg());
9706     for (unsigned Value = 0, NumValues = ValueVTs.size();
9707          Value != NumValues; ++Value) {
9708       EVT VT = ValueVTs[Value];
9709       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9710       ISD::ArgFlagsTy Flags;
9711 
9712       // Certain targets (such as MIPS), may have a different ABI alignment
9713       // for a type depending on the context. Give the target a chance to
9714       // specify the alignment it wants.
9715       const Align OriginalAlignment(
9716           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9717 
9718       if (Arg.getType()->isPointerTy()) {
9719         Flags.setPointer();
9720         Flags.setPointerAddrSpace(
9721             cast<PointerType>(Arg.getType())->getAddressSpace());
9722       }
9723       if (Arg.hasAttribute(Attribute::ZExt))
9724         Flags.setZExt();
9725       if (Arg.hasAttribute(Attribute::SExt))
9726         Flags.setSExt();
9727       if (Arg.hasAttribute(Attribute::InReg)) {
9728         // If we are using vectorcall calling convention, a structure that is
9729         // passed InReg - is surely an HVA
9730         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9731             isa<StructType>(Arg.getType())) {
9732           // The first value of a structure is marked
9733           if (0 == Value)
9734             Flags.setHvaStart();
9735           Flags.setHva();
9736         }
9737         // Set InReg Flag
9738         Flags.setInReg();
9739       }
9740       if (Arg.hasAttribute(Attribute::StructRet))
9741         Flags.setSRet();
9742       if (Arg.hasAttribute(Attribute::SwiftSelf))
9743         Flags.setSwiftSelf();
9744       if (Arg.hasAttribute(Attribute::SwiftError))
9745         Flags.setSwiftError();
9746       if (Arg.hasAttribute(Attribute::ByVal))
9747         Flags.setByVal();
9748       if (Arg.hasAttribute(Attribute::InAlloca)) {
9749         Flags.setInAlloca();
9750         // Set the byval flag for CCAssignFn callbacks that don't know about
9751         // inalloca.  This way we can know how many bytes we should've allocated
9752         // and how many bytes a callee cleanup function will pop.  If we port
9753         // inalloca to more targets, we'll have to add custom inalloca handling
9754         // in the various CC lowering callbacks.
9755         Flags.setByVal();
9756       }
9757       if (Arg.hasAttribute(Attribute::Preallocated)) {
9758         Flags.setPreallocated();
9759         // Set the byval flag for CCAssignFn callbacks that don't know about
9760         // preallocated.  This way we can know how many bytes we should've
9761         // allocated and how many bytes a callee cleanup function will pop.  If
9762         // we port preallocated to more targets, we'll have to add custom
9763         // preallocated handling in the various CC lowering callbacks.
9764         Flags.setByVal();
9765       }
9766       if (F.getCallingConv() == CallingConv::X86_INTR) {
9767         // IA Interrupt passes frame (1st parameter) by value in the stack.
9768         if (ArgNo == 0)
9769           Flags.setByVal();
9770       }
9771       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated()) {
9772         Type *ElementTy = Arg.getParamByValType();
9773 
9774         // For ByVal, size and alignment should be passed from FE.  BE will
9775         // guess if this info is not there but there are cases it cannot get
9776         // right.
9777         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9778         Flags.setByValSize(FrameSize);
9779 
9780         unsigned FrameAlign;
9781         if (Arg.getParamAlignment())
9782           FrameAlign = Arg.getParamAlignment();
9783         else
9784           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9785         Flags.setByValAlign(Align(FrameAlign));
9786       }
9787       if (Arg.hasAttribute(Attribute::Nest))
9788         Flags.setNest();
9789       if (NeedsRegBlock)
9790         Flags.setInConsecutiveRegs();
9791       Flags.setOrigAlign(OriginalAlignment);
9792       if (ArgCopyElisionCandidates.count(&Arg))
9793         Flags.setCopyElisionCandidate();
9794       if (Arg.hasAttribute(Attribute::Returned))
9795         Flags.setReturned();
9796 
9797       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9798           *CurDAG->getContext(), F.getCallingConv(), VT);
9799       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9800           *CurDAG->getContext(), F.getCallingConv(), VT);
9801       for (unsigned i = 0; i != NumRegs; ++i) {
9802         // For scalable vectors, use the minimum size; individual targets
9803         // are responsible for handling scalable vector arguments and
9804         // return values.
9805         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9806                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9807         if (NumRegs > 1 && i == 0)
9808           MyFlags.Flags.setSplit();
9809         // if it isn't first piece, alignment must be 1
9810         else if (i > 0) {
9811           MyFlags.Flags.setOrigAlign(Align(1));
9812           if (i == NumRegs - 1)
9813             MyFlags.Flags.setSplitEnd();
9814         }
9815         Ins.push_back(MyFlags);
9816       }
9817       if (NeedsRegBlock && Value == NumValues - 1)
9818         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9819       PartBase += VT.getStoreSize().getKnownMinSize();
9820     }
9821   }
9822 
9823   // Call the target to set up the argument values.
9824   SmallVector<SDValue, 8> InVals;
9825   SDValue NewRoot = TLI->LowerFormalArguments(
9826       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9827 
9828   // Verify that the target's LowerFormalArguments behaved as expected.
9829   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9830          "LowerFormalArguments didn't return a valid chain!");
9831   assert(InVals.size() == Ins.size() &&
9832          "LowerFormalArguments didn't emit the correct number of values!");
9833   LLVM_DEBUG({
9834     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9835       assert(InVals[i].getNode() &&
9836              "LowerFormalArguments emitted a null value!");
9837       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9838              "LowerFormalArguments emitted a value with the wrong type!");
9839     }
9840   });
9841 
9842   // Update the DAG with the new chain value resulting from argument lowering.
9843   DAG.setRoot(NewRoot);
9844 
9845   // Set up the argument values.
9846   unsigned i = 0;
9847   if (!FuncInfo->CanLowerReturn) {
9848     // Create a virtual register for the sret pointer, and put in a copy
9849     // from the sret argument into it.
9850     SmallVector<EVT, 1> ValueVTs;
9851     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9852                     F.getReturnType()->getPointerTo(
9853                         DAG.getDataLayout().getAllocaAddrSpace()),
9854                     ValueVTs);
9855     MVT VT = ValueVTs[0].getSimpleVT();
9856     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9857     Optional<ISD::NodeType> AssertOp = None;
9858     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9859                                         nullptr, F.getCallingConv(), AssertOp);
9860 
9861     MachineFunction& MF = SDB->DAG.getMachineFunction();
9862     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9863     Register SRetReg =
9864         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9865     FuncInfo->DemoteRegister = SRetReg;
9866     NewRoot =
9867         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9868     DAG.setRoot(NewRoot);
9869 
9870     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9871     ++i;
9872   }
9873 
9874   SmallVector<SDValue, 4> Chains;
9875   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9876   for (const Argument &Arg : F.args()) {
9877     SmallVector<SDValue, 4> ArgValues;
9878     SmallVector<EVT, 4> ValueVTs;
9879     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9880     unsigned NumValues = ValueVTs.size();
9881     if (NumValues == 0)
9882       continue;
9883 
9884     bool ArgHasUses = !Arg.use_empty();
9885 
9886     // Elide the copying store if the target loaded this argument from a
9887     // suitable fixed stack object.
9888     if (Ins[i].Flags.isCopyElisionCandidate()) {
9889       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9890                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9891                              InVals[i], ArgHasUses);
9892     }
9893 
9894     // If this argument is unused then remember its value. It is used to generate
9895     // debugging information.
9896     bool isSwiftErrorArg =
9897         TLI->supportSwiftError() &&
9898         Arg.hasAttribute(Attribute::SwiftError);
9899     if (!ArgHasUses && !isSwiftErrorArg) {
9900       SDB->setUnusedArgValue(&Arg, InVals[i]);
9901 
9902       // Also remember any frame index for use in FastISel.
9903       if (FrameIndexSDNode *FI =
9904           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9905         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9906     }
9907 
9908     for (unsigned Val = 0; Val != NumValues; ++Val) {
9909       EVT VT = ValueVTs[Val];
9910       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9911                                                       F.getCallingConv(), VT);
9912       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9913           *CurDAG->getContext(), F.getCallingConv(), VT);
9914 
9915       // Even an apparent 'unused' swifterror argument needs to be returned. So
9916       // we do generate a copy for it that can be used on return from the
9917       // function.
9918       if (ArgHasUses || isSwiftErrorArg) {
9919         Optional<ISD::NodeType> AssertOp;
9920         if (Arg.hasAttribute(Attribute::SExt))
9921           AssertOp = ISD::AssertSext;
9922         else if (Arg.hasAttribute(Attribute::ZExt))
9923           AssertOp = ISD::AssertZext;
9924 
9925         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9926                                              PartVT, VT, nullptr,
9927                                              F.getCallingConv(), AssertOp));
9928       }
9929 
9930       i += NumParts;
9931     }
9932 
9933     // We don't need to do anything else for unused arguments.
9934     if (ArgValues.empty())
9935       continue;
9936 
9937     // Note down frame index.
9938     if (FrameIndexSDNode *FI =
9939         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9940       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9941 
9942     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9943                                      SDB->getCurSDLoc());
9944 
9945     SDB->setValue(&Arg, Res);
9946     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9947       // We want to associate the argument with the frame index, among
9948       // involved operands, that correspond to the lowest address. The
9949       // getCopyFromParts function, called earlier, is swapping the order of
9950       // the operands to BUILD_PAIR depending on endianness. The result of
9951       // that swapping is that the least significant bits of the argument will
9952       // be in the first operand of the BUILD_PAIR node, and the most
9953       // significant bits will be in the second operand.
9954       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9955       if (LoadSDNode *LNode =
9956           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9957         if (FrameIndexSDNode *FI =
9958             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9959           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9960     }
9961 
9962     // Analyses past this point are naive and don't expect an assertion.
9963     if (Res.getOpcode() == ISD::AssertZext)
9964       Res = Res.getOperand(0);
9965 
9966     // Update the SwiftErrorVRegDefMap.
9967     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9968       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9969       if (Register::isVirtualRegister(Reg))
9970         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9971                                    Reg);
9972     }
9973 
9974     // If this argument is live outside of the entry block, insert a copy from
9975     // wherever we got it to the vreg that other BB's will reference it as.
9976     if (Res.getOpcode() == ISD::CopyFromReg) {
9977       // If we can, though, try to skip creating an unnecessary vreg.
9978       // FIXME: This isn't very clean... it would be nice to make this more
9979       // general.
9980       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9981       if (Register::isVirtualRegister(Reg)) {
9982         FuncInfo->ValueMap[&Arg] = Reg;
9983         continue;
9984       }
9985     }
9986     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9987       FuncInfo->InitializeRegForValue(&Arg);
9988       SDB->CopyToExportRegsIfNeeded(&Arg);
9989     }
9990   }
9991 
9992   if (!Chains.empty()) {
9993     Chains.push_back(NewRoot);
9994     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9995   }
9996 
9997   DAG.setRoot(NewRoot);
9998 
9999   assert(i == InVals.size() && "Argument register count mismatch!");
10000 
10001   // If any argument copy elisions occurred and we have debug info, update the
10002   // stale frame indices used in the dbg.declare variable info table.
10003   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10004   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10005     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10006       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10007       if (I != ArgCopyElisionFrameIndexMap.end())
10008         VI.Slot = I->second;
10009     }
10010   }
10011 
10012   // Finally, if the target has anything special to do, allow it to do so.
10013   emitFunctionEntryCode();
10014 }
10015 
10016 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10017 /// ensure constants are generated when needed.  Remember the virtual registers
10018 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10019 /// directly add them, because expansion might result in multiple MBB's for one
10020 /// BB.  As such, the start of the BB might correspond to a different MBB than
10021 /// the end.
10022 void
10023 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10024   const Instruction *TI = LLVMBB->getTerminator();
10025 
10026   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10027 
10028   // Check PHI nodes in successors that expect a value to be available from this
10029   // block.
10030   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10031     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10032     if (!isa<PHINode>(SuccBB->begin())) continue;
10033     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10034 
10035     // If this terminator has multiple identical successors (common for
10036     // switches), only handle each succ once.
10037     if (!SuccsHandled.insert(SuccMBB).second)
10038       continue;
10039 
10040     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10041 
10042     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10043     // nodes and Machine PHI nodes, but the incoming operands have not been
10044     // emitted yet.
10045     for (const PHINode &PN : SuccBB->phis()) {
10046       // Ignore dead phi's.
10047       if (PN.use_empty())
10048         continue;
10049 
10050       // Skip empty types
10051       if (PN.getType()->isEmptyTy())
10052         continue;
10053 
10054       unsigned Reg;
10055       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10056 
10057       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10058         unsigned &RegOut = ConstantsOut[C];
10059         if (RegOut == 0) {
10060           RegOut = FuncInfo.CreateRegs(C);
10061           CopyValueToVirtualRegister(C, RegOut);
10062         }
10063         Reg = RegOut;
10064       } else {
10065         DenseMap<const Value *, Register>::iterator I =
10066           FuncInfo.ValueMap.find(PHIOp);
10067         if (I != FuncInfo.ValueMap.end())
10068           Reg = I->second;
10069         else {
10070           assert(isa<AllocaInst>(PHIOp) &&
10071                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10072                  "Didn't codegen value into a register!??");
10073           Reg = FuncInfo.CreateRegs(PHIOp);
10074           CopyValueToVirtualRegister(PHIOp, Reg);
10075         }
10076       }
10077 
10078       // Remember that this register needs to added to the machine PHI node as
10079       // the input for this MBB.
10080       SmallVector<EVT, 4> ValueVTs;
10081       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10082       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10083       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10084         EVT VT = ValueVTs[vti];
10085         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10086         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10087           FuncInfo.PHINodesToUpdate.push_back(
10088               std::make_pair(&*MBBI++, Reg + i));
10089         Reg += NumRegisters;
10090       }
10091     }
10092   }
10093 
10094   ConstantsOut.clear();
10095 }
10096 
10097 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10098 /// is 0.
10099 MachineBasicBlock *
10100 SelectionDAGBuilder::StackProtectorDescriptor::
10101 AddSuccessorMBB(const BasicBlock *BB,
10102                 MachineBasicBlock *ParentMBB,
10103                 bool IsLikely,
10104                 MachineBasicBlock *SuccMBB) {
10105   // If SuccBB has not been created yet, create it.
10106   if (!SuccMBB) {
10107     MachineFunction *MF = ParentMBB->getParent();
10108     MachineFunction::iterator BBI(ParentMBB);
10109     SuccMBB = MF->CreateMachineBasicBlock(BB);
10110     MF->insert(++BBI, SuccMBB);
10111   }
10112   // Add it as a successor of ParentMBB.
10113   ParentMBB->addSuccessor(
10114       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10115   return SuccMBB;
10116 }
10117 
10118 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10119   MachineFunction::iterator I(MBB);
10120   if (++I == FuncInfo.MF->end())
10121     return nullptr;
10122   return &*I;
10123 }
10124 
10125 /// During lowering new call nodes can be created (such as memset, etc.).
10126 /// Those will become new roots of the current DAG, but complications arise
10127 /// when they are tail calls. In such cases, the call lowering will update
10128 /// the root, but the builder still needs to know that a tail call has been
10129 /// lowered in order to avoid generating an additional return.
10130 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10131   // If the node is null, we do have a tail call.
10132   if (MaybeTC.getNode() != nullptr)
10133     DAG.setRoot(MaybeTC);
10134   else
10135     HasTailCall = true;
10136 }
10137 
10138 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10139                                         MachineBasicBlock *SwitchMBB,
10140                                         MachineBasicBlock *DefaultMBB) {
10141   MachineFunction *CurMF = FuncInfo.MF;
10142   MachineBasicBlock *NextMBB = nullptr;
10143   MachineFunction::iterator BBI(W.MBB);
10144   if (++BBI != FuncInfo.MF->end())
10145     NextMBB = &*BBI;
10146 
10147   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10148 
10149   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10150 
10151   if (Size == 2 && W.MBB == SwitchMBB) {
10152     // If any two of the cases has the same destination, and if one value
10153     // is the same as the other, but has one bit unset that the other has set,
10154     // use bit manipulation to do two compares at once.  For example:
10155     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10156     // TODO: This could be extended to merge any 2 cases in switches with 3
10157     // cases.
10158     // TODO: Handle cases where W.CaseBB != SwitchBB.
10159     CaseCluster &Small = *W.FirstCluster;
10160     CaseCluster &Big = *W.LastCluster;
10161 
10162     if (Small.Low == Small.High && Big.Low == Big.High &&
10163         Small.MBB == Big.MBB) {
10164       const APInt &SmallValue = Small.Low->getValue();
10165       const APInt &BigValue = Big.Low->getValue();
10166 
10167       // Check that there is only one bit different.
10168       APInt CommonBit = BigValue ^ SmallValue;
10169       if (CommonBit.isPowerOf2()) {
10170         SDValue CondLHS = getValue(Cond);
10171         EVT VT = CondLHS.getValueType();
10172         SDLoc DL = getCurSDLoc();
10173 
10174         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10175                                  DAG.getConstant(CommonBit, DL, VT));
10176         SDValue Cond = DAG.getSetCC(
10177             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10178             ISD::SETEQ);
10179 
10180         // Update successor info.
10181         // Both Small and Big will jump to Small.BB, so we sum up the
10182         // probabilities.
10183         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10184         if (BPI)
10185           addSuccessorWithProb(
10186               SwitchMBB, DefaultMBB,
10187               // The default destination is the first successor in IR.
10188               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10189         else
10190           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10191 
10192         // Insert the true branch.
10193         SDValue BrCond =
10194             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10195                         DAG.getBasicBlock(Small.MBB));
10196         // Insert the false branch.
10197         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10198                              DAG.getBasicBlock(DefaultMBB));
10199 
10200         DAG.setRoot(BrCond);
10201         return;
10202       }
10203     }
10204   }
10205 
10206   if (TM.getOptLevel() != CodeGenOpt::None) {
10207     // Here, we order cases by probability so the most likely case will be
10208     // checked first. However, two clusters can have the same probability in
10209     // which case their relative ordering is non-deterministic. So we use Low
10210     // as a tie-breaker as clusters are guaranteed to never overlap.
10211     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10212                [](const CaseCluster &a, const CaseCluster &b) {
10213       return a.Prob != b.Prob ?
10214              a.Prob > b.Prob :
10215              a.Low->getValue().slt(b.Low->getValue());
10216     });
10217 
10218     // Rearrange the case blocks so that the last one falls through if possible
10219     // without changing the order of probabilities.
10220     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10221       --I;
10222       if (I->Prob > W.LastCluster->Prob)
10223         break;
10224       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10225         std::swap(*I, *W.LastCluster);
10226         break;
10227       }
10228     }
10229   }
10230 
10231   // Compute total probability.
10232   BranchProbability DefaultProb = W.DefaultProb;
10233   BranchProbability UnhandledProbs = DefaultProb;
10234   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10235     UnhandledProbs += I->Prob;
10236 
10237   MachineBasicBlock *CurMBB = W.MBB;
10238   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10239     bool FallthroughUnreachable = false;
10240     MachineBasicBlock *Fallthrough;
10241     if (I == W.LastCluster) {
10242       // For the last cluster, fall through to the default destination.
10243       Fallthrough = DefaultMBB;
10244       FallthroughUnreachable = isa<UnreachableInst>(
10245           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10246     } else {
10247       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10248       CurMF->insert(BBI, Fallthrough);
10249       // Put Cond in a virtual register to make it available from the new blocks.
10250       ExportFromCurrentBlock(Cond);
10251     }
10252     UnhandledProbs -= I->Prob;
10253 
10254     switch (I->Kind) {
10255       case CC_JumpTable: {
10256         // FIXME: Optimize away range check based on pivot comparisons.
10257         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10258         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10259 
10260         // The jump block hasn't been inserted yet; insert it here.
10261         MachineBasicBlock *JumpMBB = JT->MBB;
10262         CurMF->insert(BBI, JumpMBB);
10263 
10264         auto JumpProb = I->Prob;
10265         auto FallthroughProb = UnhandledProbs;
10266 
10267         // If the default statement is a target of the jump table, we evenly
10268         // distribute the default probability to successors of CurMBB. Also
10269         // update the probability on the edge from JumpMBB to Fallthrough.
10270         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10271                                               SE = JumpMBB->succ_end();
10272              SI != SE; ++SI) {
10273           if (*SI == DefaultMBB) {
10274             JumpProb += DefaultProb / 2;
10275             FallthroughProb -= DefaultProb / 2;
10276             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10277             JumpMBB->normalizeSuccProbs();
10278             break;
10279           }
10280         }
10281 
10282         if (FallthroughUnreachable) {
10283           // Skip the range check if the fallthrough block is unreachable.
10284           JTH->OmitRangeCheck = true;
10285         }
10286 
10287         if (!JTH->OmitRangeCheck)
10288           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10289         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10290         CurMBB->normalizeSuccProbs();
10291 
10292         // The jump table header will be inserted in our current block, do the
10293         // range check, and fall through to our fallthrough block.
10294         JTH->HeaderBB = CurMBB;
10295         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10296 
10297         // If we're in the right place, emit the jump table header right now.
10298         if (CurMBB == SwitchMBB) {
10299           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10300           JTH->Emitted = true;
10301         }
10302         break;
10303       }
10304       case CC_BitTests: {
10305         // FIXME: Optimize away range check based on pivot comparisons.
10306         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10307 
10308         // The bit test blocks haven't been inserted yet; insert them here.
10309         for (BitTestCase &BTC : BTB->Cases)
10310           CurMF->insert(BBI, BTC.ThisBB);
10311 
10312         // Fill in fields of the BitTestBlock.
10313         BTB->Parent = CurMBB;
10314         BTB->Default = Fallthrough;
10315 
10316         BTB->DefaultProb = UnhandledProbs;
10317         // If the cases in bit test don't form a contiguous range, we evenly
10318         // distribute the probability on the edge to Fallthrough to two
10319         // successors of CurMBB.
10320         if (!BTB->ContiguousRange) {
10321           BTB->Prob += DefaultProb / 2;
10322           BTB->DefaultProb -= DefaultProb / 2;
10323         }
10324 
10325         if (FallthroughUnreachable) {
10326           // Skip the range check if the fallthrough block is unreachable.
10327           BTB->OmitRangeCheck = true;
10328         }
10329 
10330         // If we're in the right place, emit the bit test header right now.
10331         if (CurMBB == SwitchMBB) {
10332           visitBitTestHeader(*BTB, SwitchMBB);
10333           BTB->Emitted = true;
10334         }
10335         break;
10336       }
10337       case CC_Range: {
10338         const Value *RHS, *LHS, *MHS;
10339         ISD::CondCode CC;
10340         if (I->Low == I->High) {
10341           // Check Cond == I->Low.
10342           CC = ISD::SETEQ;
10343           LHS = Cond;
10344           RHS=I->Low;
10345           MHS = nullptr;
10346         } else {
10347           // Check I->Low <= Cond <= I->High.
10348           CC = ISD::SETLE;
10349           LHS = I->Low;
10350           MHS = Cond;
10351           RHS = I->High;
10352         }
10353 
10354         // If Fallthrough is unreachable, fold away the comparison.
10355         if (FallthroughUnreachable)
10356           CC = ISD::SETTRUE;
10357 
10358         // The false probability is the sum of all unhandled cases.
10359         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10360                      getCurSDLoc(), I->Prob, UnhandledProbs);
10361 
10362         if (CurMBB == SwitchMBB)
10363           visitSwitchCase(CB, SwitchMBB);
10364         else
10365           SL->SwitchCases.push_back(CB);
10366 
10367         break;
10368       }
10369     }
10370     CurMBB = Fallthrough;
10371   }
10372 }
10373 
10374 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10375                                               CaseClusterIt First,
10376                                               CaseClusterIt Last) {
10377   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10378     if (X.Prob != CC.Prob)
10379       return X.Prob > CC.Prob;
10380 
10381     // Ties are broken by comparing the case value.
10382     return X.Low->getValue().slt(CC.Low->getValue());
10383   });
10384 }
10385 
10386 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10387                                         const SwitchWorkListItem &W,
10388                                         Value *Cond,
10389                                         MachineBasicBlock *SwitchMBB) {
10390   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10391          "Clusters not sorted?");
10392 
10393   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10394 
10395   // Balance the tree based on branch probabilities to create a near-optimal (in
10396   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10397   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10398   CaseClusterIt LastLeft = W.FirstCluster;
10399   CaseClusterIt FirstRight = W.LastCluster;
10400   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10401   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10402 
10403   // Move LastLeft and FirstRight towards each other from opposite directions to
10404   // find a partitioning of the clusters which balances the probability on both
10405   // sides. If LeftProb and RightProb are equal, alternate which side is
10406   // taken to ensure 0-probability nodes are distributed evenly.
10407   unsigned I = 0;
10408   while (LastLeft + 1 < FirstRight) {
10409     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10410       LeftProb += (++LastLeft)->Prob;
10411     else
10412       RightProb += (--FirstRight)->Prob;
10413     I++;
10414   }
10415 
10416   while (true) {
10417     // Our binary search tree differs from a typical BST in that ours can have up
10418     // to three values in each leaf. The pivot selection above doesn't take that
10419     // into account, which means the tree might require more nodes and be less
10420     // efficient. We compensate for this here.
10421 
10422     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10423     unsigned NumRight = W.LastCluster - FirstRight + 1;
10424 
10425     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10426       // If one side has less than 3 clusters, and the other has more than 3,
10427       // consider taking a cluster from the other side.
10428 
10429       if (NumLeft < NumRight) {
10430         // Consider moving the first cluster on the right to the left side.
10431         CaseCluster &CC = *FirstRight;
10432         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10433         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10434         if (LeftSideRank <= RightSideRank) {
10435           // Moving the cluster to the left does not demote it.
10436           ++LastLeft;
10437           ++FirstRight;
10438           continue;
10439         }
10440       } else {
10441         assert(NumRight < NumLeft);
10442         // Consider moving the last element on the left to the right side.
10443         CaseCluster &CC = *LastLeft;
10444         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10445         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10446         if (RightSideRank <= LeftSideRank) {
10447           // Moving the cluster to the right does not demot it.
10448           --LastLeft;
10449           --FirstRight;
10450           continue;
10451         }
10452       }
10453     }
10454     break;
10455   }
10456 
10457   assert(LastLeft + 1 == FirstRight);
10458   assert(LastLeft >= W.FirstCluster);
10459   assert(FirstRight <= W.LastCluster);
10460 
10461   // Use the first element on the right as pivot since we will make less-than
10462   // comparisons against it.
10463   CaseClusterIt PivotCluster = FirstRight;
10464   assert(PivotCluster > W.FirstCluster);
10465   assert(PivotCluster <= W.LastCluster);
10466 
10467   CaseClusterIt FirstLeft = W.FirstCluster;
10468   CaseClusterIt LastRight = W.LastCluster;
10469 
10470   const ConstantInt *Pivot = PivotCluster->Low;
10471 
10472   // New blocks will be inserted immediately after the current one.
10473   MachineFunction::iterator BBI(W.MBB);
10474   ++BBI;
10475 
10476   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10477   // we can branch to its destination directly if it's squeezed exactly in
10478   // between the known lower bound and Pivot - 1.
10479   MachineBasicBlock *LeftMBB;
10480   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10481       FirstLeft->Low == W.GE &&
10482       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10483     LeftMBB = FirstLeft->MBB;
10484   } else {
10485     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10486     FuncInfo.MF->insert(BBI, LeftMBB);
10487     WorkList.push_back(
10488         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10489     // Put Cond in a virtual register to make it available from the new blocks.
10490     ExportFromCurrentBlock(Cond);
10491   }
10492 
10493   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10494   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10495   // directly if RHS.High equals the current upper bound.
10496   MachineBasicBlock *RightMBB;
10497   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10498       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10499     RightMBB = FirstRight->MBB;
10500   } else {
10501     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10502     FuncInfo.MF->insert(BBI, RightMBB);
10503     WorkList.push_back(
10504         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10505     // Put Cond in a virtual register to make it available from the new blocks.
10506     ExportFromCurrentBlock(Cond);
10507   }
10508 
10509   // Create the CaseBlock record that will be used to lower the branch.
10510   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10511                getCurSDLoc(), LeftProb, RightProb);
10512 
10513   if (W.MBB == SwitchMBB)
10514     visitSwitchCase(CB, SwitchMBB);
10515   else
10516     SL->SwitchCases.push_back(CB);
10517 }
10518 
10519 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10520 // from the swith statement.
10521 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10522                                             BranchProbability PeeledCaseProb) {
10523   if (PeeledCaseProb == BranchProbability::getOne())
10524     return BranchProbability::getZero();
10525   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10526 
10527   uint32_t Numerator = CaseProb.getNumerator();
10528   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10529   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10530 }
10531 
10532 // Try to peel the top probability case if it exceeds the threshold.
10533 // Return current MachineBasicBlock for the switch statement if the peeling
10534 // does not occur.
10535 // If the peeling is performed, return the newly created MachineBasicBlock
10536 // for the peeled switch statement. Also update Clusters to remove the peeled
10537 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10538 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10539     const SwitchInst &SI, CaseClusterVector &Clusters,
10540     BranchProbability &PeeledCaseProb) {
10541   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10542   // Don't perform if there is only one cluster or optimizing for size.
10543   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10544       TM.getOptLevel() == CodeGenOpt::None ||
10545       SwitchMBB->getParent()->getFunction().hasMinSize())
10546     return SwitchMBB;
10547 
10548   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10549   unsigned PeeledCaseIndex = 0;
10550   bool SwitchPeeled = false;
10551   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10552     CaseCluster &CC = Clusters[Index];
10553     if (CC.Prob < TopCaseProb)
10554       continue;
10555     TopCaseProb = CC.Prob;
10556     PeeledCaseIndex = Index;
10557     SwitchPeeled = true;
10558   }
10559   if (!SwitchPeeled)
10560     return SwitchMBB;
10561 
10562   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10563                     << TopCaseProb << "\n");
10564 
10565   // Record the MBB for the peeled switch statement.
10566   MachineFunction::iterator BBI(SwitchMBB);
10567   ++BBI;
10568   MachineBasicBlock *PeeledSwitchMBB =
10569       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10570   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10571 
10572   ExportFromCurrentBlock(SI.getCondition());
10573   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10574   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10575                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10576   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10577 
10578   Clusters.erase(PeeledCaseIt);
10579   for (CaseCluster &CC : Clusters) {
10580     LLVM_DEBUG(
10581         dbgs() << "Scale the probablity for one cluster, before scaling: "
10582                << CC.Prob << "\n");
10583     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10584     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10585   }
10586   PeeledCaseProb = TopCaseProb;
10587   return PeeledSwitchMBB;
10588 }
10589 
10590 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10591   // Extract cases from the switch.
10592   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10593   CaseClusterVector Clusters;
10594   Clusters.reserve(SI.getNumCases());
10595   for (auto I : SI.cases()) {
10596     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10597     const ConstantInt *CaseVal = I.getCaseValue();
10598     BranchProbability Prob =
10599         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10600             : BranchProbability(1, SI.getNumCases() + 1);
10601     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10602   }
10603 
10604   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10605 
10606   // Cluster adjacent cases with the same destination. We do this at all
10607   // optimization levels because it's cheap to do and will make codegen faster
10608   // if there are many clusters.
10609   sortAndRangeify(Clusters);
10610 
10611   // The branch probablity of the peeled case.
10612   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10613   MachineBasicBlock *PeeledSwitchMBB =
10614       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10615 
10616   // If there is only the default destination, jump there directly.
10617   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10618   if (Clusters.empty()) {
10619     assert(PeeledSwitchMBB == SwitchMBB);
10620     SwitchMBB->addSuccessor(DefaultMBB);
10621     if (DefaultMBB != NextBlock(SwitchMBB)) {
10622       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10623                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10624     }
10625     return;
10626   }
10627 
10628   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10629   SL->findBitTestClusters(Clusters, &SI);
10630 
10631   LLVM_DEBUG({
10632     dbgs() << "Case clusters: ";
10633     for (const CaseCluster &C : Clusters) {
10634       if (C.Kind == CC_JumpTable)
10635         dbgs() << "JT:";
10636       if (C.Kind == CC_BitTests)
10637         dbgs() << "BT:";
10638 
10639       C.Low->getValue().print(dbgs(), true);
10640       if (C.Low != C.High) {
10641         dbgs() << '-';
10642         C.High->getValue().print(dbgs(), true);
10643       }
10644       dbgs() << ' ';
10645     }
10646     dbgs() << '\n';
10647   });
10648 
10649   assert(!Clusters.empty());
10650   SwitchWorkList WorkList;
10651   CaseClusterIt First = Clusters.begin();
10652   CaseClusterIt Last = Clusters.end() - 1;
10653   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10654   // Scale the branchprobability for DefaultMBB if the peel occurs and
10655   // DefaultMBB is not replaced.
10656   if (PeeledCaseProb != BranchProbability::getZero() &&
10657       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10658     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10659   WorkList.push_back(
10660       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10661 
10662   while (!WorkList.empty()) {
10663     SwitchWorkListItem W = WorkList.back();
10664     WorkList.pop_back();
10665     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10666 
10667     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10668         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10669       // For optimized builds, lower large range as a balanced binary tree.
10670       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10671       continue;
10672     }
10673 
10674     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10675   }
10676 }
10677 
10678 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10679   SmallVector<EVT, 4> ValueVTs;
10680   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10681                   ValueVTs);
10682   unsigned NumValues = ValueVTs.size();
10683   if (NumValues == 0) return;
10684 
10685   SmallVector<SDValue, 4> Values(NumValues);
10686   SDValue Op = getValue(I.getOperand(0));
10687 
10688   for (unsigned i = 0; i != NumValues; ++i)
10689     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10690                             SDValue(Op.getNode(), Op.getResNo() + i));
10691 
10692   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10693                            DAG.getVTList(ValueVTs), Values));
10694 }
10695