xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 2750f3ed3155aedccf42e7eccec915d6578d18e4)
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/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/BranchProbabilityInfo.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/Analysis/Loads.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/ProfileSummaryInfo.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Analysis/VectorUtils.h"
37 #include "llvm/CodeGen/Analysis.h"
38 #include "llvm/CodeGen/FunctionLoweringInfo.h"
39 #include "llvm/CodeGen/GCMetadata.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
53 #include "llvm/CodeGen/StackMaps.h"
54 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
55 #include "llvm/CodeGen/TargetFrameLowering.h"
56 #include "llvm/CodeGen/TargetInstrInfo.h"
57 #include "llvm/CodeGen/TargetOpcodes.h"
58 #include "llvm/CodeGen/TargetRegisterInfo.h"
59 #include "llvm/CodeGen/TargetSubtargetInfo.h"
60 #include "llvm/CodeGen/WinEHFuncInfo.h"
61 #include "llvm/IR/Argument.h"
62 #include "llvm/IR/Attributes.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CFG.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/ConstantRange.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DebugInfoMetadata.h"
71 #include "llvm/IR/DerivedTypes.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsWebAssembly.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/Metadata.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Operator.h"
85 #include "llvm/IR/PatternMatch.h"
86 #include "llvm/IR/Statepoint.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/User.h"
89 #include "llvm/IR/Value.h"
90 #include "llvm/MC/MCContext.h"
91 #include "llvm/MC/MCSymbol.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/MathExtras.h"
98 #include "llvm/Support/raw_ostream.h"
99 #include "llvm/Target/TargetIntrinsicInfo.h"
100 #include "llvm/Target/TargetMachine.h"
101 #include "llvm/Target/TargetOptions.h"
102 #include "llvm/Transforms/Utils/Local.h"
103 #include <cstddef>
104 #include <cstring>
105 #include <iterator>
106 #include <limits>
107 #include <numeric>
108 #include <tuple>
109 
110 using namespace llvm;
111 using namespace PatternMatch;
112 using namespace SwitchCG;
113 
114 #define DEBUG_TYPE "isel"
115 
116 /// LimitFloatPrecision - Generate low-precision inline sequences for
117 /// some float libcalls (6, 8 or 12 bits).
118 static unsigned LimitFloatPrecision;
119 
120 static cl::opt<bool>
121     InsertAssertAlign("insert-assert-align", cl::init(true),
122                       cl::desc("Insert the experimental `assertalign` node."),
123                       cl::ReallyHidden);
124 
125 static cl::opt<unsigned, true>
126     LimitFPPrecision("limit-float-precision",
127                      cl::desc("Generate low-precision inline sequences "
128                               "for some float libcalls"),
129                      cl::location(LimitFloatPrecision), cl::Hidden,
130                      cl::init(0));
131 
132 static cl::opt<unsigned> SwitchPeelThreshold(
133     "switch-peel-threshold", cl::Hidden, cl::init(66),
134     cl::desc("Set the case probability threshold for peeling the case from a "
135              "switch statement. A value greater than 100 will void this "
136              "optimization"));
137 
138 // Limit the width of DAG chains. This is important in general to prevent
139 // DAG-based analysis from blowing up. For example, alias analysis and
140 // load clustering may not complete in reasonable time. It is difficult to
141 // recognize and avoid this situation within each individual analysis, and
142 // future analyses are likely to have the same behavior. Limiting DAG width is
143 // the safe approach and will be especially important with global DAGs.
144 //
145 // MaxParallelChains default is arbitrarily high to avoid affecting
146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147 // sequence over this should have been converted to llvm.memcpy by the
148 // frontend. It is easy to induce this behavior with .ll code such as:
149 // %buffer = alloca [4096 x i8]
150 // %data = load [4096 x i8]* %argPtr
151 // store [4096 x i8] %data, [4096 x i8]* %buffer
152 static const unsigned MaxParallelChains = 64;
153 
154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155                                       const SDValue *Parts, unsigned NumParts,
156                                       MVT PartVT, EVT ValueVT, const Value *V,
157                                       Optional<CallingConv::ID> CC);
158 
159 /// getCopyFromParts - Create a value that contains the specified legal parts
160 /// combined into the value they represent.  If the parts combine to a type
161 /// larger than ValueVT then AssertOp can be used to specify whether the extra
162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
163 /// (ISD::AssertSext).
164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
165                                 const SDValue *Parts, unsigned NumParts,
166                                 MVT PartVT, EVT ValueVT, const Value *V,
167                                 Optional<CallingConv::ID> CC = None,
168                                 Optional<ISD::NodeType> AssertOp = None) {
169   // Let the target assemble the parts if it wants to
170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
171   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
172                                                    PartVT, ValueVT, CC))
173     return Val;
174 
175   if (ValueVT.isVector())
176     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
177                                   CC);
178 
179   assert(NumParts > 0 && "No parts to assemble!");
180   SDValue Val = Parts[0];
181 
182   if (NumParts > 1) {
183     // Assemble the value from multiple parts.
184     if (ValueVT.isInteger()) {
185       unsigned PartBits = PartVT.getSizeInBits();
186       unsigned ValueBits = ValueVT.getSizeInBits();
187 
188       // Assemble the power of 2 part.
189       unsigned RoundParts =
190           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
191       unsigned RoundBits = PartBits * RoundParts;
192       EVT RoundVT = RoundBits == ValueBits ?
193         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
194       SDValue Lo, Hi;
195 
196       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
197 
198       if (RoundParts > 2) {
199         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
200                               PartVT, HalfVT, V);
201         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
202                               RoundParts / 2, PartVT, HalfVT, V);
203       } else {
204         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
205         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
206       }
207 
208       if (DAG.getDataLayout().isBigEndian())
209         std::swap(Lo, Hi);
210 
211       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
212 
213       if (RoundParts < NumParts) {
214         // Assemble the trailing non-power-of-2 part.
215         unsigned OddParts = NumParts - RoundParts;
216         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
217         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
218                               OddVT, V, CC);
219 
220         // Combine the round and odd parts.
221         Lo = Val;
222         if (DAG.getDataLayout().isBigEndian())
223           std::swap(Lo, Hi);
224         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
225         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
226         Hi =
227             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
228                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
229                                         TLI.getPointerTy(DAG.getDataLayout())));
230         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
231         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
232       }
233     } else if (PartVT.isFloatingPoint()) {
234       // FP split into multiple FP parts (for ppcf128)
235       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236              "Unexpected split");
237       SDValue Lo, Hi;
238       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
239       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
240       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
241         std::swap(Lo, Hi);
242       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
243     } else {
244       // FP split into integer parts (soft fp)
245       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246              !PartVT.isVector() && "Unexpected split");
247       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
248       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
249     }
250   }
251 
252   // There is now one part, held in Val.  Correct it to match ValueVT.
253   // PartEVT is the type of the register class that holds the value.
254   // ValueVT is the type of the inline asm operation.
255   EVT PartEVT = Val.getValueType();
256 
257   if (PartEVT == ValueVT)
258     return Val;
259 
260   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
261       ValueVT.bitsLT(PartEVT)) {
262     // For an FP value in an integer part, we need to truncate to the right
263     // width first.
264     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
265     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
266   }
267 
268   // Handle types that have the same size.
269   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
270     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
271 
272   // Handle types with different sizes.
273   if (PartEVT.isInteger() && ValueVT.isInteger()) {
274     if (ValueVT.bitsLT(PartEVT)) {
275       // For a truncate, see if we have any information to
276       // indicate whether the truncated bits will always be
277       // zero or sign-extension.
278       if (AssertOp.hasValue())
279         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
280                           DAG.getValueType(ValueVT));
281       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
282     }
283     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
284   }
285 
286   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
287     // FP_ROUND's are always exact here.
288     if (ValueVT.bitsLT(Val.getValueType()))
289       return DAG.getNode(
290           ISD::FP_ROUND, DL, ValueVT, Val,
291           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
292 
293     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
294   }
295 
296   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
297   // then truncating.
298   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
299       ValueVT.bitsLT(PartEVT)) {
300     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
301     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
302   }
303 
304   report_fatal_error("Unknown mismatch in getCopyFromParts!");
305 }
306 
307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
308                                               const Twine &ErrMsg) {
309   const Instruction *I = dyn_cast_or_null<Instruction>(V);
310   if (!V)
311     return Ctx.emitError(ErrMsg);
312 
313   const char *AsmError = ", possible invalid constraint for vector type";
314   if (const CallInst *CI = dyn_cast<CallInst>(I))
315     if (CI->isInlineAsm())
316       return Ctx.emitError(I, ErrMsg + AsmError);
317 
318   return Ctx.emitError(I, ErrMsg);
319 }
320 
321 /// getCopyFromPartsVector - Create a value that contains the specified legal
322 /// parts combined into the value they represent.  If the parts combine to a
323 /// type larger than ValueVT then AssertOp can be used to specify whether the
324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
325 /// ValueVT (ISD::AssertSext).
326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
327                                       const SDValue *Parts, unsigned NumParts,
328                                       MVT PartVT, EVT ValueVT, const Value *V,
329                                       Optional<CallingConv::ID> CallConv) {
330   assert(ValueVT.isVector() && "Not a vector value");
331   assert(NumParts > 0 && "No parts to assemble!");
332   const bool IsABIRegCopy = CallConv.hasValue();
333 
334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
335   SDValue Val = Parts[0];
336 
337   // Handle a multi-element vector.
338   if (NumParts > 1) {
339     EVT IntermediateVT;
340     MVT RegisterVT;
341     unsigned NumIntermediates;
342     unsigned NumRegs;
343 
344     if (IsABIRegCopy) {
345       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
346           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
347           NumIntermediates, RegisterVT);
348     } else {
349       NumRegs =
350           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
351                                      NumIntermediates, RegisterVT);
352     }
353 
354     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
355     NumParts = NumRegs; // Silence a compiler warning.
356     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
357     assert(RegisterVT.getSizeInBits() ==
358            Parts[0].getSimpleValueType().getSizeInBits() &&
359            "Part type sizes don't match!");
360 
361     // Assemble the parts into intermediate operands.
362     SmallVector<SDValue, 8> Ops(NumIntermediates);
363     if (NumIntermediates == NumParts) {
364       // If the register was not expanded, truncate or copy the value,
365       // as appropriate.
366       for (unsigned i = 0; i != NumParts; ++i)
367         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
368                                   PartVT, IntermediateVT, V, CallConv);
369     } else if (NumParts > 0) {
370       // If the intermediate type was expanded, build the intermediate
371       // operands from the parts.
372       assert(NumParts % NumIntermediates == 0 &&
373              "Must expand into a divisible number of parts!");
374       unsigned Factor = NumParts / NumIntermediates;
375       for (unsigned i = 0; i != NumIntermediates; ++i)
376         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
377                                   PartVT, IntermediateVT, V, CallConv);
378     }
379 
380     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
381     // intermediate operands.
382     EVT BuiltVectorTy =
383         IntermediateVT.isVector()
384             ? EVT::getVectorVT(
385                   *DAG.getContext(), IntermediateVT.getScalarType(),
386                   IntermediateVT.getVectorElementCount() * NumParts)
387             : EVT::getVectorVT(*DAG.getContext(),
388                                IntermediateVT.getScalarType(),
389                                NumIntermediates);
390     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
391                                                 : ISD::BUILD_VECTOR,
392                       DL, BuiltVectorTy, Ops);
393   }
394 
395   // There is now one part, held in Val.  Correct it to match ValueVT.
396   EVT PartEVT = Val.getValueType();
397 
398   if (PartEVT == ValueVT)
399     return Val;
400 
401   if (PartEVT.isVector()) {
402     // If the element type of the source/dest vectors are the same, but the
403     // parts vector has more elements than the value vector, then we have a
404     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
405     // elements we want.
406     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
407       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
408               ValueVT.getVectorElementCount().getKnownMinValue()) &&
409              (PartEVT.getVectorElementCount().isScalable() ==
410               ValueVT.getVectorElementCount().isScalable()) &&
411              "Cannot narrow, it would be a lossy transformation");
412       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
413                          DAG.getVectorIdxConstant(0, DL));
414     }
415 
416     // Vector/Vector bitcast.
417     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
418       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 
420     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
421       "Cannot handle this kind of promotion");
422     // Promoted vector extract
423     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
424 
425   }
426 
427   // Trivial bitcast if the types are the same size and the destination
428   // vector type is legal.
429   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
430       TLI.isTypeLegal(ValueVT))
431     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
432 
433   if (ValueVT.getVectorNumElements() != 1) {
434      // Certain ABIs require that vectors are passed as integers. For vectors
435      // are the same size, this is an obvious bitcast.
436      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
437        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438      } else if (ValueVT.bitsLT(PartEVT)) {
439        // Bitcast Val back the original type and extract the corresponding
440        // vector we want.
441        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
442        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
443                                            ValueVT.getVectorElementType(), Elts);
444        Val = DAG.getBitcast(WiderVecType, Val);
445        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
446                           DAG.getVectorIdxConstant(0, DL));
447      }
448 
449      diagnosePossiblyInvalidConstraint(
450          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
451      return DAG.getUNDEF(ValueVT);
452   }
453 
454   // Handle cases such as i8 -> <1 x i1>
455   EVT ValueSVT = ValueVT.getVectorElementType();
456   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
457     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
458       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
459     else
460       Val = ValueVT.isFloatingPoint()
461                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
462                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
463   }
464 
465   return DAG.getBuildVector(ValueVT, DL, Val);
466 }
467 
468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
469                                  SDValue Val, SDValue *Parts, unsigned NumParts,
470                                  MVT PartVT, const Value *V,
471                                  Optional<CallingConv::ID> CallConv);
472 
473 /// getCopyToParts - Create a series of nodes that contain the specified value
474 /// split into legal parts.  If the parts contain more bits than Val, then, for
475 /// integers, ExtendKind can be used to specify how to generate the extra bits.
476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
477                            SDValue *Parts, unsigned NumParts, MVT PartVT,
478                            const Value *V,
479                            Optional<CallingConv::ID> CallConv = None,
480                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
481   // Let the target split the parts if it wants to
482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
483   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
484                                       CallConv))
485     return;
486   EVT ValueVT = Val.getValueType();
487 
488   // Handle the vector case separately.
489   if (ValueVT.isVector())
490     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
491                                 CallConv);
492 
493   unsigned PartBits = PartVT.getSizeInBits();
494   unsigned OrigNumParts = NumParts;
495   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
496          "Copying to an illegal type!");
497 
498   if (NumParts == 0)
499     return;
500 
501   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
502   EVT PartEVT = PartVT;
503   if (PartEVT == ValueVT) {
504     assert(NumParts == 1 && "No-op copy with multiple parts!");
505     Parts[0] = Val;
506     return;
507   }
508 
509   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
510     // If the parts cover more bits than the value has, promote the value.
511     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
512       assert(NumParts == 1 && "Do not know what to promote to!");
513       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
514     } else {
515       if (ValueVT.isFloatingPoint()) {
516         // FP values need to be bitcast, then extended if they are being put
517         // into a larger container.
518         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
519         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
520       }
521       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
522              ValueVT.isInteger() &&
523              "Unknown mismatch!");
524       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
525       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
526       if (PartVT == MVT::x86mmx)
527         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
528     }
529   } else if (PartBits == ValueVT.getSizeInBits()) {
530     // Different types of the same size.
531     assert(NumParts == 1 && PartEVT != ValueVT);
532     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
534     // If the parts cover less bits than value has, truncate the value.
535     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
536            ValueVT.isInteger() &&
537            "Unknown mismatch!");
538     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
539     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
540     if (PartVT == MVT::x86mmx)
541       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
542   }
543 
544   // The value may have changed - recompute ValueVT.
545   ValueVT = Val.getValueType();
546   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
547          "Failed to tile the value with PartVT!");
548 
549   if (NumParts == 1) {
550     if (PartEVT != ValueVT) {
551       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
552                                         "scalar-to-vector conversion failed");
553       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554     }
555 
556     Parts[0] = Val;
557     return;
558   }
559 
560   // Expand the value into multiple parts.
561   if (NumParts & (NumParts - 1)) {
562     // The number of parts is not a power of 2.  Split off and copy the tail.
563     assert(PartVT.isInteger() && ValueVT.isInteger() &&
564            "Do not know what to expand to!");
565     unsigned RoundParts = 1 << Log2_32(NumParts);
566     unsigned RoundBits = RoundParts * PartBits;
567     unsigned OddParts = NumParts - RoundParts;
568     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
569       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
570 
571     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
572                    CallConv);
573 
574     if (DAG.getDataLayout().isBigEndian())
575       // The odd parts were reversed by getCopyToParts - unreverse them.
576       std::reverse(Parts + RoundParts, Parts + NumParts);
577 
578     NumParts = RoundParts;
579     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
580     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
581   }
582 
583   // The number of parts is a power of 2.  Repeatedly bisect the value using
584   // EXTRACT_ELEMENT.
585   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
586                          EVT::getIntegerVT(*DAG.getContext(),
587                                            ValueVT.getSizeInBits()),
588                          Val);
589 
590   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
591     for (unsigned i = 0; i < NumParts; i += StepSize) {
592       unsigned ThisBits = StepSize * PartBits / 2;
593       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
594       SDValue &Part0 = Parts[i];
595       SDValue &Part1 = Parts[i+StepSize/2];
596 
597       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
598                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
599       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
600                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
601 
602       if (ThisBits == PartBits && ThisVT != PartVT) {
603         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
604         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
605       }
606     }
607   }
608 
609   if (DAG.getDataLayout().isBigEndian())
610     std::reverse(Parts, Parts + OrigNumParts);
611 }
612 
613 static SDValue widenVectorToPartType(SelectionDAG &DAG,
614                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
615   if (!PartVT.isFixedLengthVector())
616     return SDValue();
617 
618   EVT ValueVT = Val.getValueType();
619   unsigned PartNumElts = PartVT.getVectorNumElements();
620   unsigned ValueNumElts = ValueVT.getVectorNumElements();
621   if (PartNumElts > ValueNumElts &&
622       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
623     EVT ElementVT = PartVT.getVectorElementType();
624     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
625     // undef elements.
626     SmallVector<SDValue, 16> Ops;
627     DAG.ExtractVectorElements(Val, Ops);
628     SDValue EltUndef = DAG.getUNDEF(ElementVT);
629     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
630       Ops.push_back(EltUndef);
631 
632     // FIXME: Use CONCAT for 2x -> 4x.
633     return DAG.getBuildVector(PartVT, DL, Ops);
634   }
635 
636   return SDValue();
637 }
638 
639 /// getCopyToPartsVector - Create a series of nodes that contain the specified
640 /// value split into legal parts.
641 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
642                                  SDValue Val, SDValue *Parts, unsigned NumParts,
643                                  MVT PartVT, const Value *V,
644                                  Optional<CallingConv::ID> CallConv) {
645   EVT ValueVT = Val.getValueType();
646   assert(ValueVT.isVector() && "Not a vector");
647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
648   const bool IsABIRegCopy = CallConv.hasValue();
649 
650   if (NumParts == 1) {
651     EVT PartEVT = PartVT;
652     if (PartEVT == ValueVT) {
653       // Nothing to do.
654     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
655       // Bitconvert vector->vector case.
656       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
657     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
658       Val = Widened;
659     } else if (PartVT.isVector() &&
660                PartEVT.getVectorElementType().bitsGE(
661                    ValueVT.getVectorElementType()) &&
662                PartEVT.getVectorElementCount() ==
663                    ValueVT.getVectorElementCount()) {
664 
665       // Promoted vector extract
666       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
667     } else {
668       if (ValueVT.getVectorElementCount().isScalar()) {
669         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
670                           DAG.getVectorIdxConstant(0, DL));
671       } else {
672         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
673         assert(PartVT.getFixedSizeInBits() > ValueSize &&
674                "lossy conversion of vector to scalar type");
675         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
676         Val = DAG.getBitcast(IntermediateType, Val);
677         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
678       }
679     }
680 
681     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
682     Parts[0] = Val;
683     return;
684   }
685 
686   // Handle a multi-element vector.
687   EVT IntermediateVT;
688   MVT RegisterVT;
689   unsigned NumIntermediates;
690   unsigned NumRegs;
691   if (IsABIRegCopy) {
692     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
693         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
694         NumIntermediates, RegisterVT);
695   } else {
696     NumRegs =
697         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
698                                    NumIntermediates, RegisterVT);
699   }
700 
701   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
702   NumParts = NumRegs; // Silence a compiler warning.
703   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
704 
705   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
706          "Mixing scalable and fixed vectors when copying in parts");
707 
708   Optional<ElementCount> DestEltCnt;
709 
710   if (IntermediateVT.isVector())
711     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
712   else
713     DestEltCnt = ElementCount::getFixed(NumIntermediates);
714 
715   EVT BuiltVectorTy = EVT::getVectorVT(
716       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
717   if (ValueVT != BuiltVectorTy) {
718     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
719       Val = Widened;
720 
721     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
722   }
723 
724   // Split the vector into intermediate operands.
725   SmallVector<SDValue, 8> Ops(NumIntermediates);
726   for (unsigned i = 0; i != NumIntermediates; ++i) {
727     if (IntermediateVT.isVector()) {
728       // This does something sensible for scalable vectors - see the
729       // definition of EXTRACT_SUBVECTOR for further details.
730       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
731       Ops[i] =
732           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
733                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
734     } else {
735       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
736                            DAG.getVectorIdxConstant(i, DL));
737     }
738   }
739 
740   // Split the intermediate operands into legal parts.
741   if (NumParts == NumIntermediates) {
742     // If the register was not expanded, promote or copy the value,
743     // as appropriate.
744     for (unsigned i = 0; i != NumParts; ++i)
745       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
746   } else if (NumParts > 0) {
747     // If the intermediate type was expanded, split each the value into
748     // legal parts.
749     assert(NumIntermediates != 0 && "division by zero");
750     assert(NumParts % NumIntermediates == 0 &&
751            "Must expand into a divisible number of parts!");
752     unsigned Factor = NumParts / NumIntermediates;
753     for (unsigned i = 0; i != NumIntermediates; ++i)
754       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
755                      CallConv);
756   }
757 }
758 
759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
760                            EVT valuevt, Optional<CallingConv::ID> CC)
761     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
762       RegCount(1, regs.size()), CallConv(CC) {}
763 
764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
765                            const DataLayout &DL, unsigned Reg, Type *Ty,
766                            Optional<CallingConv::ID> CC) {
767   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
768 
769   CallConv = CC;
770 
771   for (EVT ValueVT : ValueVTs) {
772     unsigned NumRegs =
773         isABIMangled()
774             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
775             : TLI.getNumRegisters(Context, ValueVT);
776     MVT RegisterVT =
777         isABIMangled()
778             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
779             : TLI.getRegisterType(Context, ValueVT);
780     for (unsigned i = 0; i != NumRegs; ++i)
781       Regs.push_back(Reg + i);
782     RegVTs.push_back(RegisterVT);
783     RegCount.push_back(NumRegs);
784     Reg += NumRegs;
785   }
786 }
787 
788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
789                                       FunctionLoweringInfo &FuncInfo,
790                                       const SDLoc &dl, SDValue &Chain,
791                                       SDValue *Flag, const Value *V) const {
792   // A Value with type {} or [0 x %t] needs no registers.
793   if (ValueVTs.empty())
794     return SDValue();
795 
796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
797 
798   // Assemble the legal parts into the final values.
799   SmallVector<SDValue, 4> Values(ValueVTs.size());
800   SmallVector<SDValue, 8> Parts;
801   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
802     // Copy the legal parts from the registers.
803     EVT ValueVT = ValueVTs[Value];
804     unsigned NumRegs = RegCount[Value];
805     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
806                                           *DAG.getContext(),
807                                           CallConv.getValue(), RegVTs[Value])
808                                     : RegVTs[Value];
809 
810     Parts.resize(NumRegs);
811     for (unsigned i = 0; i != NumRegs; ++i) {
812       SDValue P;
813       if (!Flag) {
814         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
815       } else {
816         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
817         *Flag = P.getValue(2);
818       }
819 
820       Chain = P.getValue(1);
821       Parts[i] = P;
822 
823       // If the source register was virtual and if we know something about it,
824       // add an assert node.
825       if (!Register::isVirtualRegister(Regs[Part + i]) ||
826           !RegisterVT.isInteger())
827         continue;
828 
829       const FunctionLoweringInfo::LiveOutInfo *LOI =
830         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
831       if (!LOI)
832         continue;
833 
834       unsigned RegSize = RegisterVT.getScalarSizeInBits();
835       unsigned NumSignBits = LOI->NumSignBits;
836       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
837 
838       if (NumZeroBits == RegSize) {
839         // The current value is a zero.
840         // Explicitly express that as it would be easier for
841         // optimizations to kick in.
842         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
843         continue;
844       }
845 
846       // FIXME: We capture more information than the dag can represent.  For
847       // now, just use the tightest assertzext/assertsext possible.
848       bool isSExt;
849       EVT FromVT(MVT::Other);
850       if (NumZeroBits) {
851         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
852         isSExt = false;
853       } else if (NumSignBits > 1) {
854         FromVT =
855             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
856         isSExt = true;
857       } else {
858         continue;
859       }
860       // Add an assertion node.
861       assert(FromVT != MVT::Other);
862       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
863                              RegisterVT, P, DAG.getValueType(FromVT));
864     }
865 
866     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
867                                      RegisterVT, ValueVT, V, CallConv);
868     Part += NumRegs;
869     Parts.clear();
870   }
871 
872   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
873 }
874 
875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
876                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
877                                  const Value *V,
878                                  ISD::NodeType PreferredExtendType) const {
879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
880   ISD::NodeType ExtendKind = PreferredExtendType;
881 
882   // Get the list of the values's legal parts.
883   unsigned NumRegs = Regs.size();
884   SmallVector<SDValue, 8> Parts(NumRegs);
885   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
886     unsigned NumParts = RegCount[Value];
887 
888     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
889                                           *DAG.getContext(),
890                                           CallConv.getValue(), RegVTs[Value])
891                                     : RegVTs[Value];
892 
893     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
894       ExtendKind = ISD::ZERO_EXTEND;
895 
896     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
897                    NumParts, RegisterVT, V, CallConv, ExtendKind);
898     Part += NumParts;
899   }
900 
901   // Copy the parts into the registers.
902   SmallVector<SDValue, 8> Chains(NumRegs);
903   for (unsigned i = 0; i != NumRegs; ++i) {
904     SDValue Part;
905     if (!Flag) {
906       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
907     } else {
908       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
909       *Flag = Part.getValue(1);
910     }
911 
912     Chains[i] = Part.getValue(0);
913   }
914 
915   if (NumRegs == 1 || Flag)
916     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
917     // flagged to it. That is the CopyToReg nodes and the user are considered
918     // a single scheduling unit. If we create a TokenFactor and return it as
919     // chain, then the TokenFactor is both a predecessor (operand) of the
920     // user as well as a successor (the TF operands are flagged to the user).
921     // c1, f1 = CopyToReg
922     // c2, f2 = CopyToReg
923     // c3     = TokenFactor c1, c2
924     // ...
925     //        = op c3, ..., f2
926     Chain = Chains[NumRegs-1];
927   else
928     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
929 }
930 
931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
932                                         unsigned MatchingIdx, const SDLoc &dl,
933                                         SelectionDAG &DAG,
934                                         std::vector<SDValue> &Ops) const {
935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
936 
937   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
938   if (HasMatching)
939     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
940   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
941     // Put the register class of the virtual registers in the flag word.  That
942     // way, later passes can recompute register class constraints for inline
943     // assembly as well as normal instructions.
944     // Don't do this for tied operands that can use the regclass information
945     // from the def.
946     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
947     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
948     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
949   }
950 
951   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
952   Ops.push_back(Res);
953 
954   if (Code == InlineAsm::Kind_Clobber) {
955     // Clobbers should always have a 1:1 mapping with registers, and may
956     // reference registers that have illegal (e.g. vector) types. Hence, we
957     // shouldn't try to apply any sort of splitting logic to them.
958     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
959            "No 1:1 mapping from clobbers to regs?");
960     Register SP = TLI.getStackPointerRegisterToSaveRestore();
961     (void)SP;
962     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
963       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
964       assert(
965           (Regs[I] != SP ||
966            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
967           "If we clobbered the stack pointer, MFI should know about it.");
968     }
969     return;
970   }
971 
972   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
973     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
974     MVT RegisterVT = RegVTs[Value];
975     for (unsigned i = 0; i != NumRegs; ++i) {
976       assert(Reg < Regs.size() && "Mismatch in # registers expected");
977       unsigned TheReg = Regs[Reg++];
978       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
979     }
980   }
981 }
982 
983 SmallVector<std::pair<unsigned, TypeSize>, 4>
984 RegsForValue::getRegsAndSizes() const {
985   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
986   unsigned I = 0;
987   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
988     unsigned RegCount = std::get<0>(CountAndVT);
989     MVT RegisterVT = std::get<1>(CountAndVT);
990     TypeSize RegisterSize = RegisterVT.getSizeInBits();
991     for (unsigned E = I + RegCount; I != E; ++I)
992       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
993   }
994   return OutVec;
995 }
996 
997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
998                                const TargetLibraryInfo *li) {
999   AA = aa;
1000   GFI = gfi;
1001   LibInfo = li;
1002   DL = &DAG.getDataLayout();
1003   Context = DAG.getContext();
1004   LPadToCallSiteMap.clear();
1005   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1006 }
1007 
1008 void SelectionDAGBuilder::clear() {
1009   NodeMap.clear();
1010   UnusedArgNodeMap.clear();
1011   PendingLoads.clear();
1012   PendingExports.clear();
1013   PendingConstrainedFP.clear();
1014   PendingConstrainedFPStrict.clear();
1015   CurInst = nullptr;
1016   HasTailCall = false;
1017   SDNodeOrder = LowestSDNodeOrder;
1018   StatepointLowering.clear();
1019 }
1020 
1021 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1022   DanglingDebugInfoMap.clear();
1023 }
1024 
1025 // Update DAG root to include dependencies on Pending chains.
1026 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1027   SDValue Root = DAG.getRoot();
1028 
1029   if (Pending.empty())
1030     return Root;
1031 
1032   // Add current root to PendingChains, unless we already indirectly
1033   // depend on it.
1034   if (Root.getOpcode() != ISD::EntryToken) {
1035     unsigned i = 0, e = Pending.size();
1036     for (; i != e; ++i) {
1037       assert(Pending[i].getNode()->getNumOperands() > 1);
1038       if (Pending[i].getNode()->getOperand(0) == Root)
1039         break;  // Don't add the root if we already indirectly depend on it.
1040     }
1041 
1042     if (i == e)
1043       Pending.push_back(Root);
1044   }
1045 
1046   if (Pending.size() == 1)
1047     Root = Pending[0];
1048   else
1049     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1050 
1051   DAG.setRoot(Root);
1052   Pending.clear();
1053   return Root;
1054 }
1055 
1056 SDValue SelectionDAGBuilder::getMemoryRoot() {
1057   return updateRoot(PendingLoads);
1058 }
1059 
1060 SDValue SelectionDAGBuilder::getRoot() {
1061   // Chain up all pending constrained intrinsics together with all
1062   // pending loads, by simply appending them to PendingLoads and
1063   // then calling getMemoryRoot().
1064   PendingLoads.reserve(PendingLoads.size() +
1065                        PendingConstrainedFP.size() +
1066                        PendingConstrainedFPStrict.size());
1067   PendingLoads.append(PendingConstrainedFP.begin(),
1068                       PendingConstrainedFP.end());
1069   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1070                       PendingConstrainedFPStrict.end());
1071   PendingConstrainedFP.clear();
1072   PendingConstrainedFPStrict.clear();
1073   return getMemoryRoot();
1074 }
1075 
1076 SDValue SelectionDAGBuilder::getControlRoot() {
1077   // We need to emit pending fpexcept.strict constrained intrinsics,
1078   // so append them to the PendingExports list.
1079   PendingExports.append(PendingConstrainedFPStrict.begin(),
1080                         PendingConstrainedFPStrict.end());
1081   PendingConstrainedFPStrict.clear();
1082   return updateRoot(PendingExports);
1083 }
1084 
1085 void SelectionDAGBuilder::visit(const Instruction &I) {
1086   // Set up outgoing PHI node register values before emitting the terminator.
1087   if (I.isTerminator()) {
1088     HandlePHINodesInSuccessorBlocks(I.getParent());
1089   }
1090 
1091   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1092   if (!isa<DbgInfoIntrinsic>(I))
1093     ++SDNodeOrder;
1094 
1095   CurInst = &I;
1096 
1097   visit(I.getOpcode(), I);
1098 
1099   if (!I.isTerminator() && !HasTailCall &&
1100       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1101     CopyToExportRegsIfNeeded(&I);
1102 
1103   CurInst = nullptr;
1104 }
1105 
1106 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1107   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1108 }
1109 
1110 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1111   // Note: this doesn't use InstVisitor, because it has to work with
1112   // ConstantExpr's in addition to instructions.
1113   switch (Opcode) {
1114   default: llvm_unreachable("Unknown instruction type encountered!");
1115     // Build the switch statement using the Instruction.def file.
1116 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1117     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1118 #include "llvm/IR/Instruction.def"
1119   }
1120 }
1121 
1122 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1123                                                DebugLoc DL, unsigned Order) {
1124   // We treat variadic dbg_values differently at this stage.
1125   if (DI->hasArgList()) {
1126     // For variadic dbg_values we will now insert an undef.
1127     // FIXME: We can potentially recover these!
1128     SmallVector<SDDbgOperand, 2> Locs;
1129     for (const Value *V : DI->getValues()) {
1130       auto Undef = UndefValue::get(V->getType());
1131       Locs.push_back(SDDbgOperand::fromConst(Undef));
1132     }
1133     SDDbgValue *SDV = DAG.getDbgValueList(
1134         DI->getVariable(), DI->getExpression(), Locs, {},
1135         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1136     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1137   } else {
1138     // TODO: Dangling debug info will eventually either be resolved or produce
1139     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1140     // between the original dbg.value location and its resolved DBG_VALUE,
1141     // which we should ideally fill with an extra Undef DBG_VALUE.
1142     assert(DI->getNumVariableLocationOps() == 1 &&
1143            "DbgValueInst without an ArgList should have a single location "
1144            "operand.");
1145     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1146   }
1147 }
1148 
1149 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1150                                                 const DIExpression *Expr) {
1151   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1152     const DbgValueInst *DI = DDI.getDI();
1153     DIVariable *DanglingVariable = DI->getVariable();
1154     DIExpression *DanglingExpr = DI->getExpression();
1155     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1156       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1157       return true;
1158     }
1159     return false;
1160   };
1161 
1162   for (auto &DDIMI : DanglingDebugInfoMap) {
1163     DanglingDebugInfoVector &DDIV = DDIMI.second;
1164 
1165     // If debug info is to be dropped, run it through final checks to see
1166     // whether it can be salvaged.
1167     for (auto &DDI : DDIV)
1168       if (isMatchingDbgValue(DDI))
1169         salvageUnresolvedDbgValue(DDI);
1170 
1171     erase_if(DDIV, isMatchingDbgValue);
1172   }
1173 }
1174 
1175 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1176 // generate the debug data structures now that we've seen its definition.
1177 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1178                                                    SDValue Val) {
1179   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1180   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1181     return;
1182 
1183   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1184   for (auto &DDI : DDIV) {
1185     const DbgValueInst *DI = DDI.getDI();
1186     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1187     assert(DI && "Ill-formed DanglingDebugInfo");
1188     DebugLoc dl = DDI.getdl();
1189     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1190     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1191     DILocalVariable *Variable = DI->getVariable();
1192     DIExpression *Expr = DI->getExpression();
1193     assert(Variable->isValidLocationForIntrinsic(dl) &&
1194            "Expected inlined-at fields to agree");
1195     SDDbgValue *SDV;
1196     if (Val.getNode()) {
1197       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1198       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1199       // we couldn't resolve it directly when examining the DbgValue intrinsic
1200       // in the first place we should not be more successful here). Unless we
1201       // have some test case that prove this to be correct we should avoid
1202       // calling EmitFuncArgumentDbgValue here.
1203       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1204         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1205                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1206         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1207         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1208         // inserted after the definition of Val when emitting the instructions
1209         // after ISel. An alternative could be to teach
1210         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1211         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1212                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1213                    << ValSDNodeOrder << "\n");
1214         SDV = getDbgValue(Val, Variable, Expr, dl,
1215                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1216         DAG.AddDbgValue(SDV, false);
1217       } else
1218         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1219                           << "in EmitFuncArgumentDbgValue\n");
1220     } else {
1221       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1222       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1223       auto SDV =
1224           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1225       DAG.AddDbgValue(SDV, false);
1226     }
1227   }
1228   DDIV.clear();
1229 }
1230 
1231 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1232   assert(!DDI.getDI()->hasArgList() &&
1233          "Not implemented for variadic dbg_values");
1234   Value *V = DDI.getDI()->getValue(0);
1235   DILocalVariable *Var = DDI.getDI()->getVariable();
1236   DIExpression *Expr = DDI.getDI()->getExpression();
1237   DebugLoc DL = DDI.getdl();
1238   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1239   unsigned SDOrder = DDI.getSDNodeOrder();
1240   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1241   // that DW_OP_stack_value is desired.
1242   assert(isa<DbgValueInst>(DDI.getDI()));
1243   bool StackValue = true;
1244 
1245   // Can this Value can be encoded without any further work?
1246   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1247     return;
1248 
1249   // Attempt to salvage back through as many instructions as possible. Bail if
1250   // a non-instruction is seen, such as a constant expression or global
1251   // variable. FIXME: Further work could recover those too.
1252   while (isa<Instruction>(V)) {
1253     Instruction &VAsInst = *cast<Instruction>(V);
1254     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1255 
1256     // If we cannot salvage any further, and haven't yet found a suitable debug
1257     // expression, bail out.
1258     if (!NewExpr)
1259       break;
1260 
1261     // New value and expr now represent this debuginfo.
1262     V = VAsInst.getOperand(0);
1263     Expr = NewExpr;
1264 
1265     // Some kind of simplification occurred: check whether the operand of the
1266     // salvaged debug expression can be encoded in this DAG.
1267     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1268                          /*IsVariadic=*/false)) {
1269       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1270                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1271       return;
1272     }
1273   }
1274 
1275   // This was the final opportunity to salvage this debug information, and it
1276   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1277   // any earlier variable location.
1278   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1279   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1280   DAG.AddDbgValue(SDV, false);
1281 
1282   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1283                     << "\n");
1284   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1285                     << "\n");
1286 }
1287 
1288 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1289                                            DILocalVariable *Var,
1290                                            DIExpression *Expr, DebugLoc dl,
1291                                            DebugLoc InstDL, unsigned Order,
1292                                            bool IsVariadic) {
1293   if (Values.empty())
1294     return true;
1295   SDDbgValue::LocOpVector LocationOps;
1296   SDDbgValue::SDNodeVector Dependencies;
1297   for (const Value *V : Values) {
1298     // Constant value.
1299     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1300         isa<ConstantPointerNull>(V)) {
1301       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1302       continue;
1303     }
1304 
1305     // If the Value is a frame index, we can create a FrameIndex debug value
1306     // without relying on the DAG at all.
1307     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1308       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1309       if (SI != FuncInfo.StaticAllocaMap.end()) {
1310         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1311         continue;
1312       }
1313     }
1314 
1315     // Do not use getValue() in here; we don't want to generate code at
1316     // this point if it hasn't been done yet.
1317     SDValue N = NodeMap[V];
1318     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1319       N = UnusedArgNodeMap[V];
1320     if (N.getNode()) {
1321       // Only emit func arg dbg value for non-variadic dbg.values for now.
1322       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1323         return true;
1324       Dependencies.push_back(N.getNode());
1325       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1326         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1327         // describe stack slot locations.
1328         //
1329         // Consider "int x = 0; int *px = &x;". There are two kinds of
1330         // interesting debug values here after optimization:
1331         //
1332         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1333         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1334         //
1335         // Both describe the direct values of their associated variables.
1336         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1337         continue;
1338       }
1339       LocationOps.emplace_back(
1340           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1341       continue;
1342     }
1343 
1344     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1345     // Special rules apply for the first dbg.values of parameter variables in a
1346     // function. Identify them by the fact they reference Argument Values, that
1347     // they're parameters, and they are parameters of the current function. We
1348     // need to let them dangle until they get an SDNode.
1349     bool IsParamOfFunc =
1350         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1351     if (IsParamOfFunc)
1352       return false;
1353 
1354     // The value is not used in this block yet (or it would have an SDNode).
1355     // We still want the value to appear for the user if possible -- if it has
1356     // an associated VReg, we can refer to that instead.
1357     auto VMI = FuncInfo.ValueMap.find(V);
1358     if (VMI != FuncInfo.ValueMap.end()) {
1359       unsigned Reg = VMI->second;
1360       // If this is a PHI node, it may be split up into several MI PHI nodes
1361       // (in FunctionLoweringInfo::set).
1362       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1363                        V->getType(), None);
1364       if (RFV.occupiesMultipleRegs()) {
1365         // FIXME: We could potentially support variadic dbg_values here.
1366         if (IsVariadic)
1367           return false;
1368         unsigned Offset = 0;
1369         unsigned BitsToDescribe = 0;
1370         if (auto VarSize = Var->getSizeInBits())
1371           BitsToDescribe = *VarSize;
1372         if (auto Fragment = Expr->getFragmentInfo())
1373           BitsToDescribe = Fragment->SizeInBits;
1374         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1375           // Bail out if all bits are described already.
1376           if (Offset >= BitsToDescribe)
1377             break;
1378           // TODO: handle scalable vectors.
1379           unsigned RegisterSize = RegAndSize.second;
1380           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1381                                       ? BitsToDescribe - Offset
1382                                       : RegisterSize;
1383           auto FragmentExpr = DIExpression::createFragmentExpression(
1384               Expr, Offset, FragmentSize);
1385           if (!FragmentExpr)
1386             continue;
1387           SDDbgValue *SDV = DAG.getVRegDbgValue(
1388               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1389           DAG.AddDbgValue(SDV, false);
1390           Offset += RegisterSize;
1391         }
1392         return true;
1393       }
1394       // We can use simple vreg locations for variadic dbg_values as well.
1395       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1396       continue;
1397     }
1398     // We failed to create a SDDbgOperand for V.
1399     return false;
1400   }
1401 
1402   // We have created a SDDbgOperand for each Value in Values.
1403   // Should use Order instead of SDNodeOrder?
1404   assert(!LocationOps.empty());
1405   SDDbgValue *SDV =
1406       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1407                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1408   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1409   return true;
1410 }
1411 
1412 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1413   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1414   for (auto &Pair : DanglingDebugInfoMap)
1415     for (auto &DDI : Pair.second)
1416       salvageUnresolvedDbgValue(DDI);
1417   clearDanglingDebugInfo();
1418 }
1419 
1420 /// getCopyFromRegs - If there was virtual register allocated for the value V
1421 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1422 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1423   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1424   SDValue Result;
1425 
1426   if (It != FuncInfo.ValueMap.end()) {
1427     Register InReg = It->second;
1428 
1429     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1430                      DAG.getDataLayout(), InReg, Ty,
1431                      None); // This is not an ABI copy.
1432     SDValue Chain = DAG.getEntryNode();
1433     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1434                                  V);
1435     resolveDanglingDebugInfo(V, Result);
1436   }
1437 
1438   return Result;
1439 }
1440 
1441 /// getValue - Return an SDValue for the given Value.
1442 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1443   // If we already have an SDValue for this value, use it. It's important
1444   // to do this first, so that we don't create a CopyFromReg if we already
1445   // have a regular SDValue.
1446   SDValue &N = NodeMap[V];
1447   if (N.getNode()) return N;
1448 
1449   // If there's a virtual register allocated and initialized for this
1450   // value, use it.
1451   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1452     return copyFromReg;
1453 
1454   // Otherwise create a new SDValue and remember it.
1455   SDValue Val = getValueImpl(V);
1456   NodeMap[V] = Val;
1457   resolveDanglingDebugInfo(V, Val);
1458   return Val;
1459 }
1460 
1461 /// getNonRegisterValue - Return an SDValue for the given Value, but
1462 /// don't look in FuncInfo.ValueMap for a virtual register.
1463 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1464   // If we already have an SDValue for this value, use it.
1465   SDValue &N = NodeMap[V];
1466   if (N.getNode()) {
1467     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1468       // Remove the debug location from the node as the node is about to be used
1469       // in a location which may differ from the original debug location.  This
1470       // is relevant to Constant and ConstantFP nodes because they can appear
1471       // as constant expressions inside PHI nodes.
1472       N->setDebugLoc(DebugLoc());
1473     }
1474     return N;
1475   }
1476 
1477   // Otherwise create a new SDValue and remember it.
1478   SDValue Val = getValueImpl(V);
1479   NodeMap[V] = Val;
1480   resolveDanglingDebugInfo(V, Val);
1481   return Val;
1482 }
1483 
1484 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1485 /// Create an SDValue for the given value.
1486 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1487   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1488 
1489   if (const Constant *C = dyn_cast<Constant>(V)) {
1490     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1491 
1492     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1493       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1494 
1495     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1496       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1497 
1498     if (isa<ConstantPointerNull>(C)) {
1499       unsigned AS = V->getType()->getPointerAddressSpace();
1500       return DAG.getConstant(0, getCurSDLoc(),
1501                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1502     }
1503 
1504     if (match(C, m_VScale(DAG.getDataLayout())))
1505       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1506 
1507     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1508       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1509 
1510     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1511       return DAG.getUNDEF(VT);
1512 
1513     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1514       visit(CE->getOpcode(), *CE);
1515       SDValue N1 = NodeMap[V];
1516       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1517       return N1;
1518     }
1519 
1520     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1521       SmallVector<SDValue, 4> Constants;
1522       for (const Use &U : C->operands()) {
1523         SDNode *Val = getValue(U).getNode();
1524         // If the operand is an empty aggregate, there are no values.
1525         if (!Val) continue;
1526         // Add each leaf value from the operand to the Constants list
1527         // to form a flattened list of all the values.
1528         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1529           Constants.push_back(SDValue(Val, i));
1530       }
1531 
1532       return DAG.getMergeValues(Constants, getCurSDLoc());
1533     }
1534 
1535     if (const ConstantDataSequential *CDS =
1536           dyn_cast<ConstantDataSequential>(C)) {
1537       SmallVector<SDValue, 4> Ops;
1538       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1539         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1540         // Add each leaf value from the operand to the Constants list
1541         // to form a flattened list of all the values.
1542         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1543           Ops.push_back(SDValue(Val, i));
1544       }
1545 
1546       if (isa<ArrayType>(CDS->getType()))
1547         return DAG.getMergeValues(Ops, getCurSDLoc());
1548       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1549     }
1550 
1551     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1552       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1553              "Unknown struct or array constant!");
1554 
1555       SmallVector<EVT, 4> ValueVTs;
1556       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1557       unsigned NumElts = ValueVTs.size();
1558       if (NumElts == 0)
1559         return SDValue(); // empty struct
1560       SmallVector<SDValue, 4> Constants(NumElts);
1561       for (unsigned i = 0; i != NumElts; ++i) {
1562         EVT EltVT = ValueVTs[i];
1563         if (isa<UndefValue>(C))
1564           Constants[i] = DAG.getUNDEF(EltVT);
1565         else if (EltVT.isFloatingPoint())
1566           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1567         else
1568           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1569       }
1570 
1571       return DAG.getMergeValues(Constants, getCurSDLoc());
1572     }
1573 
1574     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1575       return DAG.getBlockAddress(BA, VT);
1576 
1577     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1578       return getValue(Equiv->getGlobalValue());
1579 
1580     VectorType *VecTy = cast<VectorType>(V->getType());
1581 
1582     // Now that we know the number and type of the elements, get that number of
1583     // elements into the Ops array based on what kind of constant it is.
1584     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1585       SmallVector<SDValue, 16> Ops;
1586       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1587       for (unsigned i = 0; i != NumElements; ++i)
1588         Ops.push_back(getValue(CV->getOperand(i)));
1589 
1590       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1591     } else if (isa<ConstantAggregateZero>(C)) {
1592       EVT EltVT =
1593           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1594 
1595       SDValue Op;
1596       if (EltVT.isFloatingPoint())
1597         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1598       else
1599         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1600 
1601       if (isa<ScalableVectorType>(VecTy))
1602         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1603       else {
1604         SmallVector<SDValue, 16> Ops;
1605         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1606         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1607       }
1608     }
1609     llvm_unreachable("Unknown vector constant");
1610   }
1611 
1612   // If this is a static alloca, generate it as the frameindex instead of
1613   // computation.
1614   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1615     DenseMap<const AllocaInst*, int>::iterator SI =
1616       FuncInfo.StaticAllocaMap.find(AI);
1617     if (SI != FuncInfo.StaticAllocaMap.end())
1618       return DAG.getFrameIndex(SI->second,
1619                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1620   }
1621 
1622   // If this is an instruction which fast-isel has deferred, select it now.
1623   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1624     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1625 
1626     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1627                      Inst->getType(), None);
1628     SDValue Chain = DAG.getEntryNode();
1629     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1630   }
1631 
1632   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1633     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1634   }
1635   llvm_unreachable("Can't get register for value!");
1636 }
1637 
1638 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1639   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1640   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1641   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1642   bool IsSEH = isAsynchronousEHPersonality(Pers);
1643   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1644   if (!IsSEH)
1645     CatchPadMBB->setIsEHScopeEntry();
1646   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1647   if (IsMSVCCXX || IsCoreCLR)
1648     CatchPadMBB->setIsEHFuncletEntry();
1649 }
1650 
1651 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1652   // Update machine-CFG edge.
1653   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1654   FuncInfo.MBB->addSuccessor(TargetMBB);
1655   TargetMBB->setIsEHCatchretTarget(true);
1656   DAG.getMachineFunction().setHasEHCatchret(true);
1657 
1658   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1659   bool IsSEH = isAsynchronousEHPersonality(Pers);
1660   if (IsSEH) {
1661     // If this is not a fall-through branch or optimizations are switched off,
1662     // emit the branch.
1663     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1664         TM.getOptLevel() == CodeGenOpt::None)
1665       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1666                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1667     return;
1668   }
1669 
1670   // Figure out the funclet membership for the catchret's successor.
1671   // This will be used by the FuncletLayout pass to determine how to order the
1672   // BB's.
1673   // A 'catchret' returns to the outer scope's color.
1674   Value *ParentPad = I.getCatchSwitchParentPad();
1675   const BasicBlock *SuccessorColor;
1676   if (isa<ConstantTokenNone>(ParentPad))
1677     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1678   else
1679     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1680   assert(SuccessorColor && "No parent funclet for catchret!");
1681   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1682   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1683 
1684   // Create the terminator node.
1685   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1686                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1687                             DAG.getBasicBlock(SuccessorColorMBB));
1688   DAG.setRoot(Ret);
1689 }
1690 
1691 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1692   // Don't emit any special code for the cleanuppad instruction. It just marks
1693   // the start of an EH scope/funclet.
1694   FuncInfo.MBB->setIsEHScopeEntry();
1695   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1696   if (Pers != EHPersonality::Wasm_CXX) {
1697     FuncInfo.MBB->setIsEHFuncletEntry();
1698     FuncInfo.MBB->setIsCleanupFuncletEntry();
1699   }
1700 }
1701 
1702 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1703 // not match, it is OK to add only the first unwind destination catchpad to the
1704 // successors, because there will be at least one invoke instruction within the
1705 // catch scope that points to the next unwind destination, if one exists, so
1706 // CFGSort cannot mess up with BB sorting order.
1707 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1708 // call within them, and catchpads only consisting of 'catch (...)' have a
1709 // '__cxa_end_catch' call within them, both of which generate invokes in case
1710 // the next unwind destination exists, i.e., the next unwind destination is not
1711 // the caller.)
1712 //
1713 // Having at most one EH pad successor is also simpler and helps later
1714 // transformations.
1715 //
1716 // For example,
1717 // current:
1718 //   invoke void @foo to ... unwind label %catch.dispatch
1719 // catch.dispatch:
1720 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1721 // catch.start:
1722 //   ...
1723 //   ... in this BB or some other child BB dominated by this BB there will be an
1724 //   invoke that points to 'next' BB as an unwind destination
1725 //
1726 // next: ; We don't need to add this to 'current' BB's successor
1727 //   ...
1728 static void findWasmUnwindDestinations(
1729     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1730     BranchProbability Prob,
1731     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1732         &UnwindDests) {
1733   while (EHPadBB) {
1734     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1735     if (isa<CleanupPadInst>(Pad)) {
1736       // Stop on cleanup pads.
1737       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1738       UnwindDests.back().first->setIsEHScopeEntry();
1739       break;
1740     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1741       // Add the catchpad handlers to the possible destinations. We don't
1742       // continue to the unwind destination of the catchswitch for wasm.
1743       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1744         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1745         UnwindDests.back().first->setIsEHScopeEntry();
1746       }
1747       break;
1748     } else {
1749       continue;
1750     }
1751   }
1752 }
1753 
1754 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1755 /// many places it could ultimately go. In the IR, we have a single unwind
1756 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1757 /// This function skips over imaginary basic blocks that hold catchswitch
1758 /// instructions, and finds all the "real" machine
1759 /// basic block destinations. As those destinations may not be successors of
1760 /// EHPadBB, here we also calculate the edge probability to those destinations.
1761 /// The passed-in Prob is the edge probability to EHPadBB.
1762 static void findUnwindDestinations(
1763     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1764     BranchProbability Prob,
1765     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1766         &UnwindDests) {
1767   EHPersonality Personality =
1768     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1769   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1770   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1771   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1772   bool IsSEH = isAsynchronousEHPersonality(Personality);
1773 
1774   if (IsWasmCXX) {
1775     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1776     assert(UnwindDests.size() <= 1 &&
1777            "There should be at most one unwind destination for wasm");
1778     return;
1779   }
1780 
1781   while (EHPadBB) {
1782     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1783     BasicBlock *NewEHPadBB = nullptr;
1784     if (isa<LandingPadInst>(Pad)) {
1785       // Stop on landingpads. They are not funclets.
1786       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1787       break;
1788     } else if (isa<CleanupPadInst>(Pad)) {
1789       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1790       // personalities.
1791       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1792       UnwindDests.back().first->setIsEHScopeEntry();
1793       UnwindDests.back().first->setIsEHFuncletEntry();
1794       break;
1795     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1796       // Add the catchpad handlers to the possible destinations.
1797       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1798         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1799         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1800         if (IsMSVCCXX || IsCoreCLR)
1801           UnwindDests.back().first->setIsEHFuncletEntry();
1802         if (!IsSEH)
1803           UnwindDests.back().first->setIsEHScopeEntry();
1804       }
1805       NewEHPadBB = CatchSwitch->getUnwindDest();
1806     } else {
1807       continue;
1808     }
1809 
1810     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1811     if (BPI && NewEHPadBB)
1812       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1813     EHPadBB = NewEHPadBB;
1814   }
1815 }
1816 
1817 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1818   // Update successor info.
1819   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1820   auto UnwindDest = I.getUnwindDest();
1821   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1822   BranchProbability UnwindDestProb =
1823       (BPI && UnwindDest)
1824           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1825           : BranchProbability::getZero();
1826   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1827   for (auto &UnwindDest : UnwindDests) {
1828     UnwindDest.first->setIsEHPad();
1829     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1830   }
1831   FuncInfo.MBB->normalizeSuccProbs();
1832 
1833   // Create the terminator node.
1834   SDValue Ret =
1835       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1836   DAG.setRoot(Ret);
1837 }
1838 
1839 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1840   report_fatal_error("visitCatchSwitch not yet implemented!");
1841 }
1842 
1843 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1844   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1845   auto &DL = DAG.getDataLayout();
1846   SDValue Chain = getControlRoot();
1847   SmallVector<ISD::OutputArg, 8> Outs;
1848   SmallVector<SDValue, 8> OutVals;
1849 
1850   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1851   // lower
1852   //
1853   //   %val = call <ty> @llvm.experimental.deoptimize()
1854   //   ret <ty> %val
1855   //
1856   // differently.
1857   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1858     LowerDeoptimizingReturn();
1859     return;
1860   }
1861 
1862   if (!FuncInfo.CanLowerReturn) {
1863     unsigned DemoteReg = FuncInfo.DemoteRegister;
1864     const Function *F = I.getParent()->getParent();
1865 
1866     // Emit a store of the return value through the virtual register.
1867     // Leave Outs empty so that LowerReturn won't try to load return
1868     // registers the usual way.
1869     SmallVector<EVT, 1> PtrValueVTs;
1870     ComputeValueVTs(TLI, DL,
1871                     F->getReturnType()->getPointerTo(
1872                         DAG.getDataLayout().getAllocaAddrSpace()),
1873                     PtrValueVTs);
1874 
1875     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1876                                         DemoteReg, PtrValueVTs[0]);
1877     SDValue RetOp = getValue(I.getOperand(0));
1878 
1879     SmallVector<EVT, 4> ValueVTs, MemVTs;
1880     SmallVector<uint64_t, 4> Offsets;
1881     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1882                     &Offsets);
1883     unsigned NumValues = ValueVTs.size();
1884 
1885     SmallVector<SDValue, 4> Chains(NumValues);
1886     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1887     for (unsigned i = 0; i != NumValues; ++i) {
1888       // An aggregate return value cannot wrap around the address space, so
1889       // offsets to its parts don't wrap either.
1890       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1891                                            TypeSize::Fixed(Offsets[i]));
1892 
1893       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1894       if (MemVTs[i] != ValueVTs[i])
1895         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1896       Chains[i] = DAG.getStore(
1897           Chain, getCurSDLoc(), Val,
1898           // FIXME: better loc info would be nice.
1899           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1900           commonAlignment(BaseAlign, Offsets[i]));
1901     }
1902 
1903     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1904                         MVT::Other, Chains);
1905   } else if (I.getNumOperands() != 0) {
1906     SmallVector<EVT, 4> ValueVTs;
1907     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1908     unsigned NumValues = ValueVTs.size();
1909     if (NumValues) {
1910       SDValue RetOp = getValue(I.getOperand(0));
1911 
1912       const Function *F = I.getParent()->getParent();
1913 
1914       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1915           I.getOperand(0)->getType(), F->getCallingConv(),
1916           /*IsVarArg*/ false);
1917 
1918       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1919       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1920                                           Attribute::SExt))
1921         ExtendKind = ISD::SIGN_EXTEND;
1922       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1923                                                Attribute::ZExt))
1924         ExtendKind = ISD::ZERO_EXTEND;
1925 
1926       LLVMContext &Context = F->getContext();
1927       bool RetInReg = F->getAttributes().hasAttribute(
1928           AttributeList::ReturnIndex, Attribute::InReg);
1929 
1930       for (unsigned j = 0; j != NumValues; ++j) {
1931         EVT VT = ValueVTs[j];
1932 
1933         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1934           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1935 
1936         CallingConv::ID CC = F->getCallingConv();
1937 
1938         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1939         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1940         SmallVector<SDValue, 4> Parts(NumParts);
1941         getCopyToParts(DAG, getCurSDLoc(),
1942                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1943                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1944 
1945         // 'inreg' on function refers to return value
1946         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1947         if (RetInReg)
1948           Flags.setInReg();
1949 
1950         if (I.getOperand(0)->getType()->isPointerTy()) {
1951           Flags.setPointer();
1952           Flags.setPointerAddrSpace(
1953               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1954         }
1955 
1956         if (NeedsRegBlock) {
1957           Flags.setInConsecutiveRegs();
1958           if (j == NumValues - 1)
1959             Flags.setInConsecutiveRegsLast();
1960         }
1961 
1962         // Propagate extension type if any
1963         if (ExtendKind == ISD::SIGN_EXTEND)
1964           Flags.setSExt();
1965         else if (ExtendKind == ISD::ZERO_EXTEND)
1966           Flags.setZExt();
1967 
1968         for (unsigned i = 0; i < NumParts; ++i) {
1969           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1970                                         VT, /*isfixed=*/true, 0, 0));
1971           OutVals.push_back(Parts[i]);
1972         }
1973       }
1974     }
1975   }
1976 
1977   // Push in swifterror virtual register as the last element of Outs. This makes
1978   // sure swifterror virtual register will be returned in the swifterror
1979   // physical register.
1980   const Function *F = I.getParent()->getParent();
1981   if (TLI.supportSwiftError() &&
1982       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1983     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1984     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1985     Flags.setSwiftError();
1986     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1987                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1988                                   true /*isfixed*/, 1 /*origidx*/,
1989                                   0 /*partOffs*/));
1990     // Create SDNode for the swifterror virtual register.
1991     OutVals.push_back(
1992         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1993                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1994                         EVT(TLI.getPointerTy(DL))));
1995   }
1996 
1997   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1998   CallingConv::ID CallConv =
1999     DAG.getMachineFunction().getFunction().getCallingConv();
2000   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2001       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2002 
2003   // Verify that the target's LowerReturn behaved as expected.
2004   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2005          "LowerReturn didn't return a valid chain!");
2006 
2007   // Update the DAG with the new chain value resulting from return lowering.
2008   DAG.setRoot(Chain);
2009 }
2010 
2011 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2012 /// created for it, emit nodes to copy the value into the virtual
2013 /// registers.
2014 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2015   // Skip empty types
2016   if (V->getType()->isEmptyTy())
2017     return;
2018 
2019   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2020   if (VMI != FuncInfo.ValueMap.end()) {
2021     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2022     CopyValueToVirtualRegister(V, VMI->second);
2023   }
2024 }
2025 
2026 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2027 /// the current basic block, add it to ValueMap now so that we'll get a
2028 /// CopyTo/FromReg.
2029 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2030   // No need to export constants.
2031   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2032 
2033   // Already exported?
2034   if (FuncInfo.isExportedInst(V)) return;
2035 
2036   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2037   CopyValueToVirtualRegister(V, Reg);
2038 }
2039 
2040 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2041                                                      const BasicBlock *FromBB) {
2042   // The operands of the setcc have to be in this block.  We don't know
2043   // how to export them from some other block.
2044   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2045     // Can export from current BB.
2046     if (VI->getParent() == FromBB)
2047       return true;
2048 
2049     // Is already exported, noop.
2050     return FuncInfo.isExportedInst(V);
2051   }
2052 
2053   // If this is an argument, we can export it if the BB is the entry block or
2054   // if it is already exported.
2055   if (isa<Argument>(V)) {
2056     if (FromBB == &FromBB->getParent()->getEntryBlock())
2057       return true;
2058 
2059     // Otherwise, can only export this if it is already exported.
2060     return FuncInfo.isExportedInst(V);
2061   }
2062 
2063   // Otherwise, constants can always be exported.
2064   return true;
2065 }
2066 
2067 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2068 BranchProbability
2069 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2070                                         const MachineBasicBlock *Dst) const {
2071   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2072   const BasicBlock *SrcBB = Src->getBasicBlock();
2073   const BasicBlock *DstBB = Dst->getBasicBlock();
2074   if (!BPI) {
2075     // If BPI is not available, set the default probability as 1 / N, where N is
2076     // the number of successors.
2077     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2078     return BranchProbability(1, SuccSize);
2079   }
2080   return BPI->getEdgeProbability(SrcBB, DstBB);
2081 }
2082 
2083 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2084                                                MachineBasicBlock *Dst,
2085                                                BranchProbability Prob) {
2086   if (!FuncInfo.BPI)
2087     Src->addSuccessorWithoutProb(Dst);
2088   else {
2089     if (Prob.isUnknown())
2090       Prob = getEdgeProbability(Src, Dst);
2091     Src->addSuccessor(Dst, Prob);
2092   }
2093 }
2094 
2095 static bool InBlock(const Value *V, const BasicBlock *BB) {
2096   if (const Instruction *I = dyn_cast<Instruction>(V))
2097     return I->getParent() == BB;
2098   return true;
2099 }
2100 
2101 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2102 /// This function emits a branch and is used at the leaves of an OR or an
2103 /// AND operator tree.
2104 void
2105 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2106                                                   MachineBasicBlock *TBB,
2107                                                   MachineBasicBlock *FBB,
2108                                                   MachineBasicBlock *CurBB,
2109                                                   MachineBasicBlock *SwitchBB,
2110                                                   BranchProbability TProb,
2111                                                   BranchProbability FProb,
2112                                                   bool InvertCond) {
2113   const BasicBlock *BB = CurBB->getBasicBlock();
2114 
2115   // If the leaf of the tree is a comparison, merge the condition into
2116   // the caseblock.
2117   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2118     // The operands of the cmp have to be in this block.  We don't know
2119     // how to export them from some other block.  If this is the first block
2120     // of the sequence, no exporting is needed.
2121     if (CurBB == SwitchBB ||
2122         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2123          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2124       ISD::CondCode Condition;
2125       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2126         ICmpInst::Predicate Pred =
2127             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2128         Condition = getICmpCondCode(Pred);
2129       } else {
2130         const FCmpInst *FC = cast<FCmpInst>(Cond);
2131         FCmpInst::Predicate Pred =
2132             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2133         Condition = getFCmpCondCode(Pred);
2134         if (TM.Options.NoNaNsFPMath)
2135           Condition = getFCmpCodeWithoutNaN(Condition);
2136       }
2137 
2138       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2139                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2140       SL->SwitchCases.push_back(CB);
2141       return;
2142     }
2143   }
2144 
2145   // Create a CaseBlock record representing this branch.
2146   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2147   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2148                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2149   SL->SwitchCases.push_back(CB);
2150 }
2151 
2152 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2153                                                MachineBasicBlock *TBB,
2154                                                MachineBasicBlock *FBB,
2155                                                MachineBasicBlock *CurBB,
2156                                                MachineBasicBlock *SwitchBB,
2157                                                Instruction::BinaryOps Opc,
2158                                                BranchProbability TProb,
2159                                                BranchProbability FProb,
2160                                                bool InvertCond) {
2161   // Skip over not part of the tree and remember to invert op and operands at
2162   // next level.
2163   Value *NotCond;
2164   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2165       InBlock(NotCond, CurBB->getBasicBlock())) {
2166     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2167                          !InvertCond);
2168     return;
2169   }
2170 
2171   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2172   const Value *BOpOp0, *BOpOp1;
2173   // Compute the effective opcode for Cond, taking into account whether it needs
2174   // to be inverted, e.g.
2175   //   and (not (or A, B)), C
2176   // gets lowered as
2177   //   and (and (not A, not B), C)
2178   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2179   if (BOp) {
2180     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2181                ? Instruction::And
2182                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2183                       ? Instruction::Or
2184                       : (Instruction::BinaryOps)0);
2185     if (InvertCond) {
2186       if (BOpc == Instruction::And)
2187         BOpc = Instruction::Or;
2188       else if (BOpc == Instruction::Or)
2189         BOpc = Instruction::And;
2190     }
2191   }
2192 
2193   // If this node is not part of the or/and tree, emit it as a branch.
2194   // Note that all nodes in the tree should have same opcode.
2195   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2196   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2197       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2198       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2199     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2200                                  TProb, FProb, InvertCond);
2201     return;
2202   }
2203 
2204   //  Create TmpBB after CurBB.
2205   MachineFunction::iterator BBI(CurBB);
2206   MachineFunction &MF = DAG.getMachineFunction();
2207   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2208   CurBB->getParent()->insert(++BBI, TmpBB);
2209 
2210   if (Opc == Instruction::Or) {
2211     // Codegen X | Y as:
2212     // BB1:
2213     //   jmp_if_X TBB
2214     //   jmp TmpBB
2215     // TmpBB:
2216     //   jmp_if_Y TBB
2217     //   jmp FBB
2218     //
2219 
2220     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2221     // The requirement is that
2222     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2223     //     = TrueProb for original BB.
2224     // Assuming the original probabilities are A and B, one choice is to set
2225     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2226     // A/(1+B) and 2B/(1+B). This choice assumes that
2227     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2228     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2229     // TmpBB, but the math is more complicated.
2230 
2231     auto NewTrueProb = TProb / 2;
2232     auto NewFalseProb = TProb / 2 + FProb;
2233     // Emit the LHS condition.
2234     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2235                          NewFalseProb, InvertCond);
2236 
2237     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2238     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2239     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2240     // Emit the RHS condition into TmpBB.
2241     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2242                          Probs[1], InvertCond);
2243   } else {
2244     assert(Opc == Instruction::And && "Unknown merge op!");
2245     // Codegen X & Y as:
2246     // BB1:
2247     //   jmp_if_X TmpBB
2248     //   jmp FBB
2249     // TmpBB:
2250     //   jmp_if_Y TBB
2251     //   jmp FBB
2252     //
2253     //  This requires creation of TmpBB after CurBB.
2254 
2255     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2256     // The requirement is that
2257     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2258     //     = FalseProb for original BB.
2259     // Assuming the original probabilities are A and B, one choice is to set
2260     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2261     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2262     // TrueProb for BB1 * FalseProb for TmpBB.
2263 
2264     auto NewTrueProb = TProb + FProb / 2;
2265     auto NewFalseProb = FProb / 2;
2266     // Emit the LHS condition.
2267     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2268                          NewFalseProb, InvertCond);
2269 
2270     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2271     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2272     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2273     // Emit the RHS condition into TmpBB.
2274     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2275                          Probs[1], InvertCond);
2276   }
2277 }
2278 
2279 /// If the set of cases should be emitted as a series of branches, return true.
2280 /// If we should emit this as a bunch of and/or'd together conditions, return
2281 /// false.
2282 bool
2283 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2284   if (Cases.size() != 2) return true;
2285 
2286   // If this is two comparisons of the same values or'd or and'd together, they
2287   // will get folded into a single comparison, so don't emit two blocks.
2288   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2289        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2290       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2291        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2292     return false;
2293   }
2294 
2295   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2296   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2297   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2298       Cases[0].CC == Cases[1].CC &&
2299       isa<Constant>(Cases[0].CmpRHS) &&
2300       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2301     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2302       return false;
2303     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2304       return false;
2305   }
2306 
2307   return true;
2308 }
2309 
2310 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2311   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2312 
2313   // Update machine-CFG edges.
2314   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2315 
2316   if (I.isUnconditional()) {
2317     // Update machine-CFG edges.
2318     BrMBB->addSuccessor(Succ0MBB);
2319 
2320     // If this is not a fall-through branch or optimizations are switched off,
2321     // emit the branch.
2322     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2323       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2324                               MVT::Other, getControlRoot(),
2325                               DAG.getBasicBlock(Succ0MBB)));
2326 
2327     return;
2328   }
2329 
2330   // If this condition is one of the special cases we handle, do special stuff
2331   // now.
2332   const Value *CondVal = I.getCondition();
2333   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2334 
2335   // If this is a series of conditions that are or'd or and'd together, emit
2336   // this as a sequence of branches instead of setcc's with and/or operations.
2337   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2338   // unpredictable branches, and vector extracts because those jumps are likely
2339   // expensive for any target), this should improve performance.
2340   // For example, instead of something like:
2341   //     cmp A, B
2342   //     C = seteq
2343   //     cmp D, E
2344   //     F = setle
2345   //     or C, F
2346   //     jnz foo
2347   // Emit:
2348   //     cmp A, B
2349   //     je foo
2350   //     cmp D, E
2351   //     jle foo
2352   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2353   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2354       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2355     Value *Vec;
2356     const Value *BOp0, *BOp1;
2357     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2358     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2359       Opcode = Instruction::And;
2360     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2361       Opcode = Instruction::Or;
2362 
2363     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2364                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2365       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2366                            getEdgeProbability(BrMBB, Succ0MBB),
2367                            getEdgeProbability(BrMBB, Succ1MBB),
2368                            /*InvertCond=*/false);
2369       // If the compares in later blocks need to use values not currently
2370       // exported from this block, export them now.  This block should always
2371       // be the first entry.
2372       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2373 
2374       // Allow some cases to be rejected.
2375       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2376         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2377           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2378           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2379         }
2380 
2381         // Emit the branch for this block.
2382         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2383         SL->SwitchCases.erase(SL->SwitchCases.begin());
2384         return;
2385       }
2386 
2387       // Okay, we decided not to do this, remove any inserted MBB's and clear
2388       // SwitchCases.
2389       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2390         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2391 
2392       SL->SwitchCases.clear();
2393     }
2394   }
2395 
2396   // Create a CaseBlock record representing this branch.
2397   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2398                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2399 
2400   // Use visitSwitchCase to actually insert the fast branch sequence for this
2401   // cond branch.
2402   visitSwitchCase(CB, BrMBB);
2403 }
2404 
2405 /// visitSwitchCase - Emits the necessary code to represent a single node in
2406 /// the binary search tree resulting from lowering a switch instruction.
2407 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2408                                           MachineBasicBlock *SwitchBB) {
2409   SDValue Cond;
2410   SDValue CondLHS = getValue(CB.CmpLHS);
2411   SDLoc dl = CB.DL;
2412 
2413   if (CB.CC == ISD::SETTRUE) {
2414     // Branch or fall through to TrueBB.
2415     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2416     SwitchBB->normalizeSuccProbs();
2417     if (CB.TrueBB != NextBlock(SwitchBB)) {
2418       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2419                               DAG.getBasicBlock(CB.TrueBB)));
2420     }
2421     return;
2422   }
2423 
2424   auto &TLI = DAG.getTargetLoweringInfo();
2425   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2426 
2427   // Build the setcc now.
2428   if (!CB.CmpMHS) {
2429     // Fold "(X == true)" to X and "(X == false)" to !X to
2430     // handle common cases produced by branch lowering.
2431     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2432         CB.CC == ISD::SETEQ)
2433       Cond = CondLHS;
2434     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2435              CB.CC == ISD::SETEQ) {
2436       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2437       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2438     } else {
2439       SDValue CondRHS = getValue(CB.CmpRHS);
2440 
2441       // If a pointer's DAG type is larger than its memory type then the DAG
2442       // values are zero-extended. This breaks signed comparisons so truncate
2443       // back to the underlying type before doing the compare.
2444       if (CondLHS.getValueType() != MemVT) {
2445         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2446         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2447       }
2448       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2449     }
2450   } else {
2451     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2452 
2453     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2454     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2455 
2456     SDValue CmpOp = getValue(CB.CmpMHS);
2457     EVT VT = CmpOp.getValueType();
2458 
2459     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2460       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2461                           ISD::SETLE);
2462     } else {
2463       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2464                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2465       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2466                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2467     }
2468   }
2469 
2470   // Update successor info
2471   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2472   // TrueBB and FalseBB are always different unless the incoming IR is
2473   // degenerate. This only happens when running llc on weird IR.
2474   if (CB.TrueBB != CB.FalseBB)
2475     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2476   SwitchBB->normalizeSuccProbs();
2477 
2478   // If the lhs block is the next block, invert the condition so that we can
2479   // fall through to the lhs instead of the rhs block.
2480   if (CB.TrueBB == NextBlock(SwitchBB)) {
2481     std::swap(CB.TrueBB, CB.FalseBB);
2482     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2483     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2484   }
2485 
2486   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2487                                MVT::Other, getControlRoot(), Cond,
2488                                DAG.getBasicBlock(CB.TrueBB));
2489 
2490   // Insert the false branch. Do this even if it's a fall through branch,
2491   // this makes it easier to do DAG optimizations which require inverting
2492   // the branch condition.
2493   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2494                        DAG.getBasicBlock(CB.FalseBB));
2495 
2496   DAG.setRoot(BrCond);
2497 }
2498 
2499 /// visitJumpTable - Emit JumpTable node in the current MBB
2500 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2501   // Emit the code for the jump table
2502   assert(JT.Reg != -1U && "Should lower JT Header first!");
2503   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2504   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2505                                      JT.Reg, PTy);
2506   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2507   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2508                                     MVT::Other, Index.getValue(1),
2509                                     Table, Index);
2510   DAG.setRoot(BrJumpTable);
2511 }
2512 
2513 /// visitJumpTableHeader - This function emits necessary code to produce index
2514 /// in the JumpTable from switch case.
2515 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2516                                                JumpTableHeader &JTH,
2517                                                MachineBasicBlock *SwitchBB) {
2518   SDLoc dl = getCurSDLoc();
2519 
2520   // Subtract the lowest switch case value from the value being switched on.
2521   SDValue SwitchOp = getValue(JTH.SValue);
2522   EVT VT = SwitchOp.getValueType();
2523   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2524                             DAG.getConstant(JTH.First, dl, VT));
2525 
2526   // The SDNode we just created, which holds the value being switched on minus
2527   // the smallest case value, needs to be copied to a virtual register so it
2528   // can be used as an index into the jump table in a subsequent basic block.
2529   // This value may be smaller or larger than the target's pointer type, and
2530   // therefore require extension or truncating.
2531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2532   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2533 
2534   unsigned JumpTableReg =
2535       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2536   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2537                                     JumpTableReg, SwitchOp);
2538   JT.Reg = JumpTableReg;
2539 
2540   if (!JTH.OmitRangeCheck) {
2541     // Emit the range check for the jump table, and branch to the default block
2542     // for the switch statement if the value being switched on exceeds the
2543     // largest case in the switch.
2544     SDValue CMP = DAG.getSetCC(
2545         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2546                                    Sub.getValueType()),
2547         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2548 
2549     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2550                                  MVT::Other, CopyTo, CMP,
2551                                  DAG.getBasicBlock(JT.Default));
2552 
2553     // Avoid emitting unnecessary branches to the next block.
2554     if (JT.MBB != NextBlock(SwitchBB))
2555       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2556                            DAG.getBasicBlock(JT.MBB));
2557 
2558     DAG.setRoot(BrCond);
2559   } else {
2560     // Avoid emitting unnecessary branches to the next block.
2561     if (JT.MBB != NextBlock(SwitchBB))
2562       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2563                               DAG.getBasicBlock(JT.MBB)));
2564     else
2565       DAG.setRoot(CopyTo);
2566   }
2567 }
2568 
2569 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2570 /// variable if there exists one.
2571 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2572                                  SDValue &Chain) {
2573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2574   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2575   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2576   MachineFunction &MF = DAG.getMachineFunction();
2577   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2578   MachineSDNode *Node =
2579       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2580   if (Global) {
2581     MachinePointerInfo MPInfo(Global);
2582     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2583                  MachineMemOperand::MODereferenceable;
2584     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2585         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2586     DAG.setNodeMemRefs(Node, {MemRef});
2587   }
2588   if (PtrTy != PtrMemTy)
2589     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2590   return SDValue(Node, 0);
2591 }
2592 
2593 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2594 /// tail spliced into a stack protector check success bb.
2595 ///
2596 /// For a high level explanation of how this fits into the stack protector
2597 /// generation see the comment on the declaration of class
2598 /// StackProtectorDescriptor.
2599 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2600                                                   MachineBasicBlock *ParentBB) {
2601 
2602   // First create the loads to the guard/stack slot for the comparison.
2603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2604   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2605   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2606 
2607   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2608   int FI = MFI.getStackProtectorIndex();
2609 
2610   SDValue Guard;
2611   SDLoc dl = getCurSDLoc();
2612   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2613   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2614   Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2615 
2616   // Generate code to load the content of the guard slot.
2617   SDValue GuardVal = DAG.getLoad(
2618       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2619       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2620       MachineMemOperand::MOVolatile);
2621 
2622   if (TLI.useStackGuardXorFP())
2623     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2624 
2625   // Retrieve guard check function, nullptr if instrumentation is inlined.
2626   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2627     // The target provides a guard check function to validate the guard value.
2628     // Generate a call to that function with the content of the guard slot as
2629     // argument.
2630     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2631     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2632 
2633     TargetLowering::ArgListTy Args;
2634     TargetLowering::ArgListEntry Entry;
2635     Entry.Node = GuardVal;
2636     Entry.Ty = FnTy->getParamType(0);
2637     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2638       Entry.IsInReg = true;
2639     Args.push_back(Entry);
2640 
2641     TargetLowering::CallLoweringInfo CLI(DAG);
2642     CLI.setDebugLoc(getCurSDLoc())
2643         .setChain(DAG.getEntryNode())
2644         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2645                    getValue(GuardCheckFn), std::move(Args));
2646 
2647     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2648     DAG.setRoot(Result.second);
2649     return;
2650   }
2651 
2652   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2653   // Otherwise, emit a volatile load to retrieve the stack guard value.
2654   SDValue Chain = DAG.getEntryNode();
2655   if (TLI.useLoadStackGuardNode()) {
2656     Guard = getLoadStackGuard(DAG, dl, Chain);
2657   } else {
2658     const Value *IRGuard = TLI.getSDagStackGuard(M);
2659     SDValue GuardPtr = getValue(IRGuard);
2660 
2661     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2662                         MachinePointerInfo(IRGuard, 0), Align,
2663                         MachineMemOperand::MOVolatile);
2664   }
2665 
2666   // Perform the comparison via a getsetcc.
2667   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2668                                                         *DAG.getContext(),
2669                                                         Guard.getValueType()),
2670                              Guard, GuardVal, ISD::SETNE);
2671 
2672   // If the guard/stackslot do not equal, branch to failure MBB.
2673   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2674                                MVT::Other, GuardVal.getOperand(0),
2675                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2676   // Otherwise branch to success MBB.
2677   SDValue Br = DAG.getNode(ISD::BR, dl,
2678                            MVT::Other, BrCond,
2679                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2680 
2681   DAG.setRoot(Br);
2682 }
2683 
2684 /// Codegen the failure basic block for a stack protector check.
2685 ///
2686 /// A failure stack protector machine basic block consists simply of a call to
2687 /// __stack_chk_fail().
2688 ///
2689 /// For a high level explanation of how this fits into the stack protector
2690 /// generation see the comment on the declaration of class
2691 /// StackProtectorDescriptor.
2692 void
2693 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2695   TargetLowering::MakeLibCallOptions CallOptions;
2696   CallOptions.setDiscardResult(true);
2697   SDValue Chain =
2698       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2699                       None, CallOptions, getCurSDLoc()).second;
2700   // On PS4, the "return address" must still be within the calling function,
2701   // even if it's at the very end, so emit an explicit TRAP here.
2702   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2703   if (TM.getTargetTriple().isPS4CPU())
2704     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2705   // WebAssembly needs an unreachable instruction after a non-returning call,
2706   // because the function return type can be different from __stack_chk_fail's
2707   // return type (void).
2708   if (TM.getTargetTriple().isWasm())
2709     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2710 
2711   DAG.setRoot(Chain);
2712 }
2713 
2714 /// visitBitTestHeader - This function emits necessary code to produce value
2715 /// suitable for "bit tests"
2716 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2717                                              MachineBasicBlock *SwitchBB) {
2718   SDLoc dl = getCurSDLoc();
2719 
2720   // Subtract the minimum value.
2721   SDValue SwitchOp = getValue(B.SValue);
2722   EVT VT = SwitchOp.getValueType();
2723   SDValue RangeSub =
2724       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2725 
2726   // Determine the type of the test operands.
2727   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2728   bool UsePtrType = false;
2729   if (!TLI.isTypeLegal(VT)) {
2730     UsePtrType = true;
2731   } else {
2732     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2733       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2734         // Switch table case range are encoded into series of masks.
2735         // Just use pointer type, it's guaranteed to fit.
2736         UsePtrType = true;
2737         break;
2738       }
2739   }
2740   SDValue Sub = RangeSub;
2741   if (UsePtrType) {
2742     VT = TLI.getPointerTy(DAG.getDataLayout());
2743     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2744   }
2745 
2746   B.RegVT = VT.getSimpleVT();
2747   B.Reg = FuncInfo.CreateReg(B.RegVT);
2748   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2749 
2750   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2751 
2752   if (!B.OmitRangeCheck)
2753     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2754   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2755   SwitchBB->normalizeSuccProbs();
2756 
2757   SDValue Root = CopyTo;
2758   if (!B.OmitRangeCheck) {
2759     // Conditional branch to the default block.
2760     SDValue RangeCmp = DAG.getSetCC(dl,
2761         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2762                                RangeSub.getValueType()),
2763         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2764         ISD::SETUGT);
2765 
2766     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2767                        DAG.getBasicBlock(B.Default));
2768   }
2769 
2770   // Avoid emitting unnecessary branches to the next block.
2771   if (MBB != NextBlock(SwitchBB))
2772     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2773 
2774   DAG.setRoot(Root);
2775 }
2776 
2777 /// visitBitTestCase - this function produces one "bit test"
2778 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2779                                            MachineBasicBlock* NextMBB,
2780                                            BranchProbability BranchProbToNext,
2781                                            unsigned Reg,
2782                                            BitTestCase &B,
2783                                            MachineBasicBlock *SwitchBB) {
2784   SDLoc dl = getCurSDLoc();
2785   MVT VT = BB.RegVT;
2786   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2787   SDValue Cmp;
2788   unsigned PopCount = countPopulation(B.Mask);
2789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2790   if (PopCount == 1) {
2791     // Testing for a single bit; just compare the shift count with what it
2792     // would need to be to shift a 1 bit in that position.
2793     Cmp = DAG.getSetCC(
2794         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2795         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2796         ISD::SETEQ);
2797   } else if (PopCount == BB.Range) {
2798     // There is only one zero bit in the range, test for it directly.
2799     Cmp = DAG.getSetCC(
2800         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2801         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2802         ISD::SETNE);
2803   } else {
2804     // Make desired shift
2805     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2806                                     DAG.getConstant(1, dl, VT), ShiftOp);
2807 
2808     // Emit bit tests and jumps
2809     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2810                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2811     Cmp = DAG.getSetCC(
2812         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2813         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2814   }
2815 
2816   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2817   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2818   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2819   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2820   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2821   // one as they are relative probabilities (and thus work more like weights),
2822   // and hence we need to normalize them to let the sum of them become one.
2823   SwitchBB->normalizeSuccProbs();
2824 
2825   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2826                               MVT::Other, getControlRoot(),
2827                               Cmp, DAG.getBasicBlock(B.TargetBB));
2828 
2829   // Avoid emitting unnecessary branches to the next block.
2830   if (NextMBB != NextBlock(SwitchBB))
2831     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2832                         DAG.getBasicBlock(NextMBB));
2833 
2834   DAG.setRoot(BrAnd);
2835 }
2836 
2837 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2838   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2839 
2840   // Retrieve successors. Look through artificial IR level blocks like
2841   // catchswitch for successors.
2842   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2843   const BasicBlock *EHPadBB = I.getSuccessor(1);
2844 
2845   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2846   // have to do anything here to lower funclet bundles.
2847   assert(!I.hasOperandBundlesOtherThan(
2848              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2849               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2850               LLVMContext::OB_cfguardtarget,
2851               LLVMContext::OB_clang_arc_attachedcall}) &&
2852          "Cannot lower invokes with arbitrary operand bundles yet!");
2853 
2854   const Value *Callee(I.getCalledOperand());
2855   const Function *Fn = dyn_cast<Function>(Callee);
2856   if (isa<InlineAsm>(Callee))
2857     visitInlineAsm(I);
2858   else if (Fn && Fn->isIntrinsic()) {
2859     switch (Fn->getIntrinsicID()) {
2860     default:
2861       llvm_unreachable("Cannot invoke this intrinsic");
2862     case Intrinsic::donothing:
2863       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2864       break;
2865     case Intrinsic::experimental_patchpoint_void:
2866     case Intrinsic::experimental_patchpoint_i64:
2867       visitPatchpoint(I, EHPadBB);
2868       break;
2869     case Intrinsic::experimental_gc_statepoint:
2870       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2871       break;
2872     case Intrinsic::wasm_rethrow: {
2873       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2874       // special because it can be invoked, so we manually lower it to a DAG
2875       // node here.
2876       SmallVector<SDValue, 8> Ops;
2877       Ops.push_back(getRoot()); // inchain
2878       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2879       Ops.push_back(
2880           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2881                                 TLI.getPointerTy(DAG.getDataLayout())));
2882       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2883       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2884       break;
2885     }
2886     }
2887   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2888     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2889     // Eventually we will support lowering the @llvm.experimental.deoptimize
2890     // intrinsic, and right now there are no plans to support other intrinsics
2891     // with deopt state.
2892     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2893   } else {
2894     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2895   }
2896 
2897   // If the value of the invoke is used outside of its defining block, make it
2898   // available as a virtual register.
2899   // We already took care of the exported value for the statepoint instruction
2900   // during call to the LowerStatepoint.
2901   if (!isa<GCStatepointInst>(I)) {
2902     CopyToExportRegsIfNeeded(&I);
2903   }
2904 
2905   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2906   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2907   BranchProbability EHPadBBProb =
2908       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2909           : BranchProbability::getZero();
2910   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2911 
2912   // Update successor info.
2913   addSuccessorWithProb(InvokeMBB, Return);
2914   for (auto &UnwindDest : UnwindDests) {
2915     UnwindDest.first->setIsEHPad();
2916     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2917   }
2918   InvokeMBB->normalizeSuccProbs();
2919 
2920   // Drop into normal successor.
2921   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2922                           DAG.getBasicBlock(Return)));
2923 }
2924 
2925 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2926   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2927 
2928   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2929   // have to do anything here to lower funclet bundles.
2930   assert(!I.hasOperandBundlesOtherThan(
2931              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2932          "Cannot lower callbrs with arbitrary operand bundles yet!");
2933 
2934   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2935   visitInlineAsm(I);
2936   CopyToExportRegsIfNeeded(&I);
2937 
2938   // Retrieve successors.
2939   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2940 
2941   // Update successor info.
2942   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2943   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2944     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2945     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2946     Target->setIsInlineAsmBrIndirectTarget();
2947   }
2948   CallBrMBB->normalizeSuccProbs();
2949 
2950   // Drop into default successor.
2951   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2952                           MVT::Other, getControlRoot(),
2953                           DAG.getBasicBlock(Return)));
2954 }
2955 
2956 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2957   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2958 }
2959 
2960 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2961   assert(FuncInfo.MBB->isEHPad() &&
2962          "Call to landingpad not in landing pad!");
2963 
2964   // If there aren't registers to copy the values into (e.g., during SjLj
2965   // exceptions), then don't bother to create these DAG nodes.
2966   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2967   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2968   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2969       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2970     return;
2971 
2972   // If landingpad's return type is token type, we don't create DAG nodes
2973   // for its exception pointer and selector value. The extraction of exception
2974   // pointer or selector value from token type landingpads is not currently
2975   // supported.
2976   if (LP.getType()->isTokenTy())
2977     return;
2978 
2979   SmallVector<EVT, 2> ValueVTs;
2980   SDLoc dl = getCurSDLoc();
2981   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2982   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2983 
2984   // Get the two live-in registers as SDValues. The physregs have already been
2985   // copied into virtual registers.
2986   SDValue Ops[2];
2987   if (FuncInfo.ExceptionPointerVirtReg) {
2988     Ops[0] = DAG.getZExtOrTrunc(
2989         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2990                            FuncInfo.ExceptionPointerVirtReg,
2991                            TLI.getPointerTy(DAG.getDataLayout())),
2992         dl, ValueVTs[0]);
2993   } else {
2994     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2995   }
2996   Ops[1] = DAG.getZExtOrTrunc(
2997       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2998                          FuncInfo.ExceptionSelectorVirtReg,
2999                          TLI.getPointerTy(DAG.getDataLayout())),
3000       dl, ValueVTs[1]);
3001 
3002   // Merge into one.
3003   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3004                             DAG.getVTList(ValueVTs), Ops);
3005   setValue(&LP, Res);
3006 }
3007 
3008 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3009                                            MachineBasicBlock *Last) {
3010   // Update JTCases.
3011   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
3012     if (SL->JTCases[i].first.HeaderBB == First)
3013       SL->JTCases[i].first.HeaderBB = Last;
3014 
3015   // Update BitTestCases.
3016   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
3017     if (SL->BitTestCases[i].Parent == First)
3018       SL->BitTestCases[i].Parent = Last;
3019 }
3020 
3021 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3022   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3023 
3024   // Update machine-CFG edges with unique successors.
3025   SmallSet<BasicBlock*, 32> Done;
3026   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3027     BasicBlock *BB = I.getSuccessor(i);
3028     bool Inserted = Done.insert(BB).second;
3029     if (!Inserted)
3030         continue;
3031 
3032     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3033     addSuccessorWithProb(IndirectBrMBB, Succ);
3034   }
3035   IndirectBrMBB->normalizeSuccProbs();
3036 
3037   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3038                           MVT::Other, getControlRoot(),
3039                           getValue(I.getAddress())));
3040 }
3041 
3042 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3043   if (!DAG.getTarget().Options.TrapUnreachable)
3044     return;
3045 
3046   // We may be able to ignore unreachable behind a noreturn call.
3047   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3048     const BasicBlock &BB = *I.getParent();
3049     if (&I != &BB.front()) {
3050       BasicBlock::const_iterator PredI =
3051         std::prev(BasicBlock::const_iterator(&I));
3052       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3053         if (Call->doesNotReturn())
3054           return;
3055       }
3056     }
3057   }
3058 
3059   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3060 }
3061 
3062 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3063   SDNodeFlags Flags;
3064 
3065   SDValue Op = getValue(I.getOperand(0));
3066   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3067                                     Op, Flags);
3068   setValue(&I, UnNodeValue);
3069 }
3070 
3071 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3072   SDNodeFlags Flags;
3073   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3074     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3075     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3076   }
3077   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3078     Flags.setExact(ExactOp->isExact());
3079   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3080     Flags.copyFMF(*FPOp);
3081 
3082   SDValue Op1 = getValue(I.getOperand(0));
3083   SDValue Op2 = getValue(I.getOperand(1));
3084   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3085                                      Op1, Op2, Flags);
3086   setValue(&I, BinNodeValue);
3087 }
3088 
3089 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3090   SDValue Op1 = getValue(I.getOperand(0));
3091   SDValue Op2 = getValue(I.getOperand(1));
3092 
3093   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3094       Op1.getValueType(), DAG.getDataLayout());
3095 
3096   // Coerce the shift amount to the right type if we can.
3097   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3098     unsigned ShiftSize = ShiftTy.getSizeInBits();
3099     unsigned Op2Size = Op2.getValueSizeInBits();
3100     SDLoc DL = getCurSDLoc();
3101 
3102     // If the operand is smaller than the shift count type, promote it.
3103     if (ShiftSize > Op2Size)
3104       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3105 
3106     // If the operand is larger than the shift count type but the shift
3107     // count type has enough bits to represent any shift value, truncate
3108     // it now. This is a common case and it exposes the truncate to
3109     // optimization early.
3110     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3111       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3112     // Otherwise we'll need to temporarily settle for some other convenient
3113     // type.  Type legalization will make adjustments once the shiftee is split.
3114     else
3115       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3116   }
3117 
3118   bool nuw = false;
3119   bool nsw = false;
3120   bool exact = false;
3121 
3122   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3123 
3124     if (const OverflowingBinaryOperator *OFBinOp =
3125             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3126       nuw = OFBinOp->hasNoUnsignedWrap();
3127       nsw = OFBinOp->hasNoSignedWrap();
3128     }
3129     if (const PossiblyExactOperator *ExactOp =
3130             dyn_cast<const PossiblyExactOperator>(&I))
3131       exact = ExactOp->isExact();
3132   }
3133   SDNodeFlags Flags;
3134   Flags.setExact(exact);
3135   Flags.setNoSignedWrap(nsw);
3136   Flags.setNoUnsignedWrap(nuw);
3137   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3138                             Flags);
3139   setValue(&I, Res);
3140 }
3141 
3142 void SelectionDAGBuilder::visitSDiv(const User &I) {
3143   SDValue Op1 = getValue(I.getOperand(0));
3144   SDValue Op2 = getValue(I.getOperand(1));
3145 
3146   SDNodeFlags Flags;
3147   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3148                  cast<PossiblyExactOperator>(&I)->isExact());
3149   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3150                            Op2, Flags));
3151 }
3152 
3153 void SelectionDAGBuilder::visitICmp(const User &I) {
3154   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3155   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3156     predicate = IC->getPredicate();
3157   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3158     predicate = ICmpInst::Predicate(IC->getPredicate());
3159   SDValue Op1 = getValue(I.getOperand(0));
3160   SDValue Op2 = getValue(I.getOperand(1));
3161   ISD::CondCode Opcode = getICmpCondCode(predicate);
3162 
3163   auto &TLI = DAG.getTargetLoweringInfo();
3164   EVT MemVT =
3165       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3166 
3167   // If a pointer's DAG type is larger than its memory type then the DAG values
3168   // are zero-extended. This breaks signed comparisons so truncate back to the
3169   // underlying type before doing the compare.
3170   if (Op1.getValueType() != MemVT) {
3171     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3172     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3173   }
3174 
3175   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3176                                                         I.getType());
3177   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3178 }
3179 
3180 void SelectionDAGBuilder::visitFCmp(const User &I) {
3181   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3182   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3183     predicate = FC->getPredicate();
3184   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3185     predicate = FCmpInst::Predicate(FC->getPredicate());
3186   SDValue Op1 = getValue(I.getOperand(0));
3187   SDValue Op2 = getValue(I.getOperand(1));
3188 
3189   ISD::CondCode Condition = getFCmpCondCode(predicate);
3190   auto *FPMO = cast<FPMathOperator>(&I);
3191   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3192     Condition = getFCmpCodeWithoutNaN(Condition);
3193 
3194   SDNodeFlags Flags;
3195   Flags.copyFMF(*FPMO);
3196   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3197 
3198   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3199                                                         I.getType());
3200   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3201 }
3202 
3203 // Check if the condition of the select has one use or two users that are both
3204 // selects with the same condition.
3205 static bool hasOnlySelectUsers(const Value *Cond) {
3206   return llvm::all_of(Cond->users(), [](const Value *V) {
3207     return isa<SelectInst>(V);
3208   });
3209 }
3210 
3211 void SelectionDAGBuilder::visitSelect(const User &I) {
3212   SmallVector<EVT, 4> ValueVTs;
3213   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3214                   ValueVTs);
3215   unsigned NumValues = ValueVTs.size();
3216   if (NumValues == 0) return;
3217 
3218   SmallVector<SDValue, 4> Values(NumValues);
3219   SDValue Cond     = getValue(I.getOperand(0));
3220   SDValue LHSVal   = getValue(I.getOperand(1));
3221   SDValue RHSVal   = getValue(I.getOperand(2));
3222   SmallVector<SDValue, 1> BaseOps(1, Cond);
3223   ISD::NodeType OpCode =
3224       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3225 
3226   bool IsUnaryAbs = false;
3227   bool Negate = false;
3228 
3229   SDNodeFlags Flags;
3230   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3231     Flags.copyFMF(*FPOp);
3232 
3233   // Min/max matching is only viable if all output VTs are the same.
3234   if (is_splat(ValueVTs)) {
3235     EVT VT = ValueVTs[0];
3236     LLVMContext &Ctx = *DAG.getContext();
3237     auto &TLI = DAG.getTargetLoweringInfo();
3238 
3239     // We care about the legality of the operation after it has been type
3240     // legalized.
3241     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3242       VT = TLI.getTypeToTransformTo(Ctx, VT);
3243 
3244     // If the vselect is legal, assume we want to leave this as a vector setcc +
3245     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3246     // min/max is legal on the scalar type.
3247     bool UseScalarMinMax = VT.isVector() &&
3248       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3249 
3250     Value *LHS, *RHS;
3251     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3252     ISD::NodeType Opc = ISD::DELETED_NODE;
3253     switch (SPR.Flavor) {
3254     case SPF_UMAX:    Opc = ISD::UMAX; break;
3255     case SPF_UMIN:    Opc = ISD::UMIN; break;
3256     case SPF_SMAX:    Opc = ISD::SMAX; break;
3257     case SPF_SMIN:    Opc = ISD::SMIN; break;
3258     case SPF_FMINNUM:
3259       switch (SPR.NaNBehavior) {
3260       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3261       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3262       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3263       case SPNB_RETURNS_ANY: {
3264         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3265           Opc = ISD::FMINNUM;
3266         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3267           Opc = ISD::FMINIMUM;
3268         else if (UseScalarMinMax)
3269           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3270             ISD::FMINNUM : ISD::FMINIMUM;
3271         break;
3272       }
3273       }
3274       break;
3275     case SPF_FMAXNUM:
3276       switch (SPR.NaNBehavior) {
3277       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3278       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3279       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3280       case SPNB_RETURNS_ANY:
3281 
3282         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3283           Opc = ISD::FMAXNUM;
3284         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3285           Opc = ISD::FMAXIMUM;
3286         else if (UseScalarMinMax)
3287           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3288             ISD::FMAXNUM : ISD::FMAXIMUM;
3289         break;
3290       }
3291       break;
3292     case SPF_NABS:
3293       Negate = true;
3294       LLVM_FALLTHROUGH;
3295     case SPF_ABS:
3296       IsUnaryAbs = true;
3297       Opc = ISD::ABS;
3298       break;
3299     default: break;
3300     }
3301 
3302     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3303         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3304          (UseScalarMinMax &&
3305           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3306         // If the underlying comparison instruction is used by any other
3307         // instruction, the consumed instructions won't be destroyed, so it is
3308         // not profitable to convert to a min/max.
3309         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3310       OpCode = Opc;
3311       LHSVal = getValue(LHS);
3312       RHSVal = getValue(RHS);
3313       BaseOps.clear();
3314     }
3315 
3316     if (IsUnaryAbs) {
3317       OpCode = Opc;
3318       LHSVal = getValue(LHS);
3319       BaseOps.clear();
3320     }
3321   }
3322 
3323   if (IsUnaryAbs) {
3324     for (unsigned i = 0; i != NumValues; ++i) {
3325       SDLoc dl = getCurSDLoc();
3326       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3327       Values[i] =
3328           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3329       if (Negate)
3330         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3331                                 Values[i]);
3332     }
3333   } else {
3334     for (unsigned i = 0; i != NumValues; ++i) {
3335       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3336       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3337       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3338       Values[i] = DAG.getNode(
3339           OpCode, getCurSDLoc(),
3340           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3341     }
3342   }
3343 
3344   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3345                            DAG.getVTList(ValueVTs), Values));
3346 }
3347 
3348 void SelectionDAGBuilder::visitTrunc(const User &I) {
3349   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3350   SDValue N = getValue(I.getOperand(0));
3351   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3352                                                         I.getType());
3353   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3354 }
3355 
3356 void SelectionDAGBuilder::visitZExt(const User &I) {
3357   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3358   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3359   SDValue N = getValue(I.getOperand(0));
3360   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3361                                                         I.getType());
3362   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3363 }
3364 
3365 void SelectionDAGBuilder::visitSExt(const User &I) {
3366   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3367   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3368   SDValue N = getValue(I.getOperand(0));
3369   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3370                                                         I.getType());
3371   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3372 }
3373 
3374 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3375   // FPTrunc is never a no-op cast, no need to check
3376   SDValue N = getValue(I.getOperand(0));
3377   SDLoc dl = getCurSDLoc();
3378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3379   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3380   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3381                            DAG.getTargetConstant(
3382                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3383 }
3384 
3385 void SelectionDAGBuilder::visitFPExt(const User &I) {
3386   // FPExt is never a no-op cast, no need to check
3387   SDValue N = getValue(I.getOperand(0));
3388   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3389                                                         I.getType());
3390   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3391 }
3392 
3393 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3394   // FPToUI is never a no-op cast, no need to check
3395   SDValue N = getValue(I.getOperand(0));
3396   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3397                                                         I.getType());
3398   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3399 }
3400 
3401 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3402   // FPToSI is never a no-op cast, no need to check
3403   SDValue N = getValue(I.getOperand(0));
3404   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3405                                                         I.getType());
3406   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3407 }
3408 
3409 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3410   // UIToFP is never a no-op cast, no need to check
3411   SDValue N = getValue(I.getOperand(0));
3412   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3413                                                         I.getType());
3414   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3415 }
3416 
3417 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3418   // SIToFP is never a no-op cast, no need to check
3419   SDValue N = getValue(I.getOperand(0));
3420   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3421                                                         I.getType());
3422   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3423 }
3424 
3425 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3426   // What to do depends on the size of the integer and the size of the pointer.
3427   // We can either truncate, zero extend, or no-op, accordingly.
3428   SDValue N = getValue(I.getOperand(0));
3429   auto &TLI = DAG.getTargetLoweringInfo();
3430   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3431                                                         I.getType());
3432   EVT PtrMemVT =
3433       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3434   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3435   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3436   setValue(&I, N);
3437 }
3438 
3439 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3440   // What to do depends on the size of the integer and the size of the pointer.
3441   // We can either truncate, zero extend, or no-op, accordingly.
3442   SDValue N = getValue(I.getOperand(0));
3443   auto &TLI = DAG.getTargetLoweringInfo();
3444   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3445   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3446   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3447   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3448   setValue(&I, N);
3449 }
3450 
3451 void SelectionDAGBuilder::visitBitCast(const User &I) {
3452   SDValue N = getValue(I.getOperand(0));
3453   SDLoc dl = getCurSDLoc();
3454   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3455                                                         I.getType());
3456 
3457   // BitCast assures us that source and destination are the same size so this is
3458   // either a BITCAST or a no-op.
3459   if (DestVT != N.getValueType())
3460     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3461                              DestVT, N)); // convert types.
3462   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3463   // might fold any kind of constant expression to an integer constant and that
3464   // is not what we are looking for. Only recognize a bitcast of a genuine
3465   // constant integer as an opaque constant.
3466   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3467     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3468                                  /*isOpaque*/true));
3469   else
3470     setValue(&I, N);            // noop cast.
3471 }
3472 
3473 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3474   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3475   const Value *SV = I.getOperand(0);
3476   SDValue N = getValue(SV);
3477   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3478 
3479   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3480   unsigned DestAS = I.getType()->getPointerAddressSpace();
3481 
3482   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3483     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3484 
3485   setValue(&I, N);
3486 }
3487 
3488 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3490   SDValue InVec = getValue(I.getOperand(0));
3491   SDValue InVal = getValue(I.getOperand(1));
3492   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3493                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3494   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3495                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3496                            InVec, InVal, InIdx));
3497 }
3498 
3499 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3501   SDValue InVec = getValue(I.getOperand(0));
3502   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3503                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3504   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3505                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3506                            InVec, InIdx));
3507 }
3508 
3509 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3510   SDValue Src1 = getValue(I.getOperand(0));
3511   SDValue Src2 = getValue(I.getOperand(1));
3512   ArrayRef<int> Mask;
3513   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3514     Mask = SVI->getShuffleMask();
3515   else
3516     Mask = cast<ConstantExpr>(I).getShuffleMask();
3517   SDLoc DL = getCurSDLoc();
3518   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3519   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3520   EVT SrcVT = Src1.getValueType();
3521 
3522   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3523       VT.isScalableVector()) {
3524     // Canonical splat form of first element of first input vector.
3525     SDValue FirstElt =
3526         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3527                     DAG.getVectorIdxConstant(0, DL));
3528     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3529     return;
3530   }
3531 
3532   // For now, we only handle splats for scalable vectors.
3533   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3534   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3535   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3536 
3537   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3538   unsigned MaskNumElts = Mask.size();
3539 
3540   if (SrcNumElts == MaskNumElts) {
3541     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3542     return;
3543   }
3544 
3545   // Normalize the shuffle vector since mask and vector length don't match.
3546   if (SrcNumElts < MaskNumElts) {
3547     // Mask is longer than the source vectors. We can use concatenate vector to
3548     // make the mask and vectors lengths match.
3549 
3550     if (MaskNumElts % SrcNumElts == 0) {
3551       // Mask length is a multiple of the source vector length.
3552       // Check if the shuffle is some kind of concatenation of the input
3553       // vectors.
3554       unsigned NumConcat = MaskNumElts / SrcNumElts;
3555       bool IsConcat = true;
3556       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3557       for (unsigned i = 0; i != MaskNumElts; ++i) {
3558         int Idx = Mask[i];
3559         if (Idx < 0)
3560           continue;
3561         // Ensure the indices in each SrcVT sized piece are sequential and that
3562         // the same source is used for the whole piece.
3563         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3564             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3565              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3566           IsConcat = false;
3567           break;
3568         }
3569         // Remember which source this index came from.
3570         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3571       }
3572 
3573       // The shuffle is concatenating multiple vectors together. Just emit
3574       // a CONCAT_VECTORS operation.
3575       if (IsConcat) {
3576         SmallVector<SDValue, 8> ConcatOps;
3577         for (auto Src : ConcatSrcs) {
3578           if (Src < 0)
3579             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3580           else if (Src == 0)
3581             ConcatOps.push_back(Src1);
3582           else
3583             ConcatOps.push_back(Src2);
3584         }
3585         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3586         return;
3587       }
3588     }
3589 
3590     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3591     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3592     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3593                                     PaddedMaskNumElts);
3594 
3595     // Pad both vectors with undefs to make them the same length as the mask.
3596     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3597 
3598     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3599     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3600     MOps1[0] = Src1;
3601     MOps2[0] = Src2;
3602 
3603     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3604     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3605 
3606     // Readjust mask for new input vector length.
3607     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3608     for (unsigned i = 0; i != MaskNumElts; ++i) {
3609       int Idx = Mask[i];
3610       if (Idx >= (int)SrcNumElts)
3611         Idx -= SrcNumElts - PaddedMaskNumElts;
3612       MappedOps[i] = Idx;
3613     }
3614 
3615     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3616 
3617     // If the concatenated vector was padded, extract a subvector with the
3618     // correct number of elements.
3619     if (MaskNumElts != PaddedMaskNumElts)
3620       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3621                            DAG.getVectorIdxConstant(0, DL));
3622 
3623     setValue(&I, Result);
3624     return;
3625   }
3626 
3627   if (SrcNumElts > MaskNumElts) {
3628     // Analyze the access pattern of the vector to see if we can extract
3629     // two subvectors and do the shuffle.
3630     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3631     bool CanExtract = true;
3632     for (int Idx : Mask) {
3633       unsigned Input = 0;
3634       if (Idx < 0)
3635         continue;
3636 
3637       if (Idx >= (int)SrcNumElts) {
3638         Input = 1;
3639         Idx -= SrcNumElts;
3640       }
3641 
3642       // If all the indices come from the same MaskNumElts sized portion of
3643       // the sources we can use extract. Also make sure the extract wouldn't
3644       // extract past the end of the source.
3645       int NewStartIdx = alignDown(Idx, MaskNumElts);
3646       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3647           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3648         CanExtract = false;
3649       // Make sure we always update StartIdx as we use it to track if all
3650       // elements are undef.
3651       StartIdx[Input] = NewStartIdx;
3652     }
3653 
3654     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3655       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3656       return;
3657     }
3658     if (CanExtract) {
3659       // Extract appropriate subvector and generate a vector shuffle
3660       for (unsigned Input = 0; Input < 2; ++Input) {
3661         SDValue &Src = Input == 0 ? Src1 : Src2;
3662         if (StartIdx[Input] < 0)
3663           Src = DAG.getUNDEF(VT);
3664         else {
3665           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3666                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3667         }
3668       }
3669 
3670       // Calculate new mask.
3671       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3672       for (int &Idx : MappedOps) {
3673         if (Idx >= (int)SrcNumElts)
3674           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3675         else if (Idx >= 0)
3676           Idx -= StartIdx[0];
3677       }
3678 
3679       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3680       return;
3681     }
3682   }
3683 
3684   // We can't use either concat vectors or extract subvectors so fall back to
3685   // replacing the shuffle with extract and build vector.
3686   // to insert and build vector.
3687   EVT EltVT = VT.getVectorElementType();
3688   SmallVector<SDValue,8> Ops;
3689   for (int Idx : Mask) {
3690     SDValue Res;
3691 
3692     if (Idx < 0) {
3693       Res = DAG.getUNDEF(EltVT);
3694     } else {
3695       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3696       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3697 
3698       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3699                         DAG.getVectorIdxConstant(Idx, DL));
3700     }
3701 
3702     Ops.push_back(Res);
3703   }
3704 
3705   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3706 }
3707 
3708 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3709   ArrayRef<unsigned> Indices;
3710   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3711     Indices = IV->getIndices();
3712   else
3713     Indices = cast<ConstantExpr>(&I)->getIndices();
3714 
3715   const Value *Op0 = I.getOperand(0);
3716   const Value *Op1 = I.getOperand(1);
3717   Type *AggTy = I.getType();
3718   Type *ValTy = Op1->getType();
3719   bool IntoUndef = isa<UndefValue>(Op0);
3720   bool FromUndef = isa<UndefValue>(Op1);
3721 
3722   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3723 
3724   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3725   SmallVector<EVT, 4> AggValueVTs;
3726   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3727   SmallVector<EVT, 4> ValValueVTs;
3728   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3729 
3730   unsigned NumAggValues = AggValueVTs.size();
3731   unsigned NumValValues = ValValueVTs.size();
3732   SmallVector<SDValue, 4> Values(NumAggValues);
3733 
3734   // Ignore an insertvalue that produces an empty object
3735   if (!NumAggValues) {
3736     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3737     return;
3738   }
3739 
3740   SDValue Agg = getValue(Op0);
3741   unsigned i = 0;
3742   // Copy the beginning value(s) from the original aggregate.
3743   for (; i != LinearIndex; ++i)
3744     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3745                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3746   // Copy values from the inserted value(s).
3747   if (NumValValues) {
3748     SDValue Val = getValue(Op1);
3749     for (; i != LinearIndex + NumValValues; ++i)
3750       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3751                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3752   }
3753   // Copy remaining value(s) from the original aggregate.
3754   for (; i != NumAggValues; ++i)
3755     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3756                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3757 
3758   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3759                            DAG.getVTList(AggValueVTs), Values));
3760 }
3761 
3762 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3763   ArrayRef<unsigned> Indices;
3764   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3765     Indices = EV->getIndices();
3766   else
3767     Indices = cast<ConstantExpr>(&I)->getIndices();
3768 
3769   const Value *Op0 = I.getOperand(0);
3770   Type *AggTy = Op0->getType();
3771   Type *ValTy = I.getType();
3772   bool OutOfUndef = isa<UndefValue>(Op0);
3773 
3774   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3775 
3776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3777   SmallVector<EVT, 4> ValValueVTs;
3778   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3779 
3780   unsigned NumValValues = ValValueVTs.size();
3781 
3782   // Ignore a extractvalue that produces an empty object
3783   if (!NumValValues) {
3784     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3785     return;
3786   }
3787 
3788   SmallVector<SDValue, 4> Values(NumValValues);
3789 
3790   SDValue Agg = getValue(Op0);
3791   // Copy out the selected value(s).
3792   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3793     Values[i - LinearIndex] =
3794       OutOfUndef ?
3795         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3796         SDValue(Agg.getNode(), Agg.getResNo() + i);
3797 
3798   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3799                            DAG.getVTList(ValValueVTs), Values));
3800 }
3801 
3802 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3803   Value *Op0 = I.getOperand(0);
3804   // Note that the pointer operand may be a vector of pointers. Take the scalar
3805   // element which holds a pointer.
3806   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3807   SDValue N = getValue(Op0);
3808   SDLoc dl = getCurSDLoc();
3809   auto &TLI = DAG.getTargetLoweringInfo();
3810 
3811   // Normalize Vector GEP - all scalar operands should be converted to the
3812   // splat vector.
3813   bool IsVectorGEP = I.getType()->isVectorTy();
3814   ElementCount VectorElementCount =
3815       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3816                   : ElementCount::getFixed(0);
3817 
3818   if (IsVectorGEP && !N.getValueType().isVector()) {
3819     LLVMContext &Context = *DAG.getContext();
3820     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3821     if (VectorElementCount.isScalable())
3822       N = DAG.getSplatVector(VT, dl, N);
3823     else
3824       N = DAG.getSplatBuildVector(VT, dl, N);
3825   }
3826 
3827   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3828        GTI != E; ++GTI) {
3829     const Value *Idx = GTI.getOperand();
3830     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3831       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3832       if (Field) {
3833         // N = N + Offset
3834         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3835 
3836         // In an inbounds GEP with an offset that is nonnegative even when
3837         // interpreted as signed, assume there is no unsigned overflow.
3838         SDNodeFlags Flags;
3839         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3840           Flags.setNoUnsignedWrap(true);
3841 
3842         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3843                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3844       }
3845     } else {
3846       // IdxSize is the width of the arithmetic according to IR semantics.
3847       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3848       // (and fix up the result later).
3849       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3850       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3851       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3852       // We intentionally mask away the high bits here; ElementSize may not
3853       // fit in IdxTy.
3854       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3855       bool ElementScalable = ElementSize.isScalable();
3856 
3857       // If this is a scalar constant or a splat vector of constants,
3858       // handle it quickly.
3859       const auto *C = dyn_cast<Constant>(Idx);
3860       if (C && isa<VectorType>(C->getType()))
3861         C = C->getSplatValue();
3862 
3863       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3864       if (CI && CI->isZero())
3865         continue;
3866       if (CI && !ElementScalable) {
3867         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3868         LLVMContext &Context = *DAG.getContext();
3869         SDValue OffsVal;
3870         if (IsVectorGEP)
3871           OffsVal = DAG.getConstant(
3872               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3873         else
3874           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3875 
3876         // In an inbounds GEP with an offset that is nonnegative even when
3877         // interpreted as signed, assume there is no unsigned overflow.
3878         SDNodeFlags Flags;
3879         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3880           Flags.setNoUnsignedWrap(true);
3881 
3882         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3883 
3884         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3885         continue;
3886       }
3887 
3888       // N = N + Idx * ElementMul;
3889       SDValue IdxN = getValue(Idx);
3890 
3891       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3892         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3893                                   VectorElementCount);
3894         if (VectorElementCount.isScalable())
3895           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3896         else
3897           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3898       }
3899 
3900       // If the index is smaller or larger than intptr_t, truncate or extend
3901       // it.
3902       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3903 
3904       if (ElementScalable) {
3905         EVT VScaleTy = N.getValueType().getScalarType();
3906         SDValue VScale = DAG.getNode(
3907             ISD::VSCALE, dl, VScaleTy,
3908             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3909         if (IsVectorGEP)
3910           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3911         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3912       } else {
3913         // If this is a multiply by a power of two, turn it into a shl
3914         // immediately.  This is a very common case.
3915         if (ElementMul != 1) {
3916           if (ElementMul.isPowerOf2()) {
3917             unsigned Amt = ElementMul.logBase2();
3918             IdxN = DAG.getNode(ISD::SHL, dl,
3919                                N.getValueType(), IdxN,
3920                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3921           } else {
3922             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3923                                             IdxN.getValueType());
3924             IdxN = DAG.getNode(ISD::MUL, dl,
3925                                N.getValueType(), IdxN, Scale);
3926           }
3927         }
3928       }
3929 
3930       N = DAG.getNode(ISD::ADD, dl,
3931                       N.getValueType(), N, IdxN);
3932     }
3933   }
3934 
3935   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3936   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3937   if (IsVectorGEP) {
3938     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3939     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3940   }
3941 
3942   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3943     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3944 
3945   setValue(&I, N);
3946 }
3947 
3948 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3949   // If this is a fixed sized alloca in the entry block of the function,
3950   // allocate it statically on the stack.
3951   if (FuncInfo.StaticAllocaMap.count(&I))
3952     return;   // getValue will auto-populate this.
3953 
3954   SDLoc dl = getCurSDLoc();
3955   Type *Ty = I.getAllocatedType();
3956   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3957   auto &DL = DAG.getDataLayout();
3958   uint64_t TySize = DL.getTypeAllocSize(Ty);
3959   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3960 
3961   SDValue AllocSize = getValue(I.getArraySize());
3962 
3963   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3964   if (AllocSize.getValueType() != IntPtr)
3965     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3966 
3967   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3968                           AllocSize,
3969                           DAG.getConstant(TySize, dl, IntPtr));
3970 
3971   // Handle alignment.  If the requested alignment is less than or equal to
3972   // the stack alignment, ignore it.  If the size is greater than or equal to
3973   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3974   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3975   if (*Alignment <= StackAlign)
3976     Alignment = None;
3977 
3978   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3979   // Round the size of the allocation up to the stack alignment size
3980   // by add SA-1 to the size. This doesn't overflow because we're computing
3981   // an address inside an alloca.
3982   SDNodeFlags Flags;
3983   Flags.setNoUnsignedWrap(true);
3984   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3985                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3986 
3987   // Mask out the low bits for alignment purposes.
3988   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3989                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3990 
3991   SDValue Ops[] = {
3992       getRoot(), AllocSize,
3993       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3994   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3995   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3996   setValue(&I, DSA);
3997   DAG.setRoot(DSA.getValue(1));
3998 
3999   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4000 }
4001 
4002 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4003   if (I.isAtomic())
4004     return visitAtomicLoad(I);
4005 
4006   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4007   const Value *SV = I.getOperand(0);
4008   if (TLI.supportSwiftError()) {
4009     // Swifterror values can come from either a function parameter with
4010     // swifterror attribute or an alloca with swifterror attribute.
4011     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4012       if (Arg->hasSwiftErrorAttr())
4013         return visitLoadFromSwiftError(I);
4014     }
4015 
4016     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4017       if (Alloca->isSwiftError())
4018         return visitLoadFromSwiftError(I);
4019     }
4020   }
4021 
4022   SDValue Ptr = getValue(SV);
4023 
4024   Type *Ty = I.getType();
4025   Align Alignment = I.getAlign();
4026 
4027   AAMDNodes AAInfo;
4028   I.getAAMetadata(AAInfo);
4029   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4030 
4031   SmallVector<EVT, 4> ValueVTs, MemVTs;
4032   SmallVector<uint64_t, 4> Offsets;
4033   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4034   unsigned NumValues = ValueVTs.size();
4035   if (NumValues == 0)
4036     return;
4037 
4038   bool isVolatile = I.isVolatile();
4039 
4040   SDValue Root;
4041   bool ConstantMemory = false;
4042   if (isVolatile)
4043     // Serialize volatile loads with other side effects.
4044     Root = getRoot();
4045   else if (NumValues > MaxParallelChains)
4046     Root = getMemoryRoot();
4047   else if (AA &&
4048            AA->pointsToConstantMemory(MemoryLocation(
4049                SV,
4050                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4051                AAInfo))) {
4052     // Do not serialize (non-volatile) loads of constant memory with anything.
4053     Root = DAG.getEntryNode();
4054     ConstantMemory = true;
4055   } else {
4056     // Do not serialize non-volatile loads against each other.
4057     Root = DAG.getRoot();
4058   }
4059 
4060   SDLoc dl = getCurSDLoc();
4061 
4062   if (isVolatile)
4063     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4064 
4065   // An aggregate load cannot wrap around the address space, so offsets to its
4066   // parts don't wrap either.
4067   SDNodeFlags Flags;
4068   Flags.setNoUnsignedWrap(true);
4069 
4070   SmallVector<SDValue, 4> Values(NumValues);
4071   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4072   EVT PtrVT = Ptr.getValueType();
4073 
4074   MachineMemOperand::Flags MMOFlags
4075     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4076 
4077   unsigned ChainI = 0;
4078   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4079     // Serializing loads here may result in excessive register pressure, and
4080     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4081     // could recover a bit by hoisting nodes upward in the chain by recognizing
4082     // they are side-effect free or do not alias. The optimizer should really
4083     // avoid this case by converting large object/array copies to llvm.memcpy
4084     // (MaxParallelChains should always remain as failsafe).
4085     if (ChainI == MaxParallelChains) {
4086       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4087       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4088                                   makeArrayRef(Chains.data(), ChainI));
4089       Root = Chain;
4090       ChainI = 0;
4091     }
4092     SDValue A = DAG.getNode(ISD::ADD, dl,
4093                             PtrVT, Ptr,
4094                             DAG.getConstant(Offsets[i], dl, PtrVT),
4095                             Flags);
4096 
4097     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4098                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4099                             MMOFlags, AAInfo, Ranges);
4100     Chains[ChainI] = L.getValue(1);
4101 
4102     if (MemVTs[i] != ValueVTs[i])
4103       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4104 
4105     Values[i] = L;
4106   }
4107 
4108   if (!ConstantMemory) {
4109     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4110                                 makeArrayRef(Chains.data(), ChainI));
4111     if (isVolatile)
4112       DAG.setRoot(Chain);
4113     else
4114       PendingLoads.push_back(Chain);
4115   }
4116 
4117   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4118                            DAG.getVTList(ValueVTs), Values));
4119 }
4120 
4121 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4122   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4123          "call visitStoreToSwiftError when backend supports swifterror");
4124 
4125   SmallVector<EVT, 4> ValueVTs;
4126   SmallVector<uint64_t, 4> Offsets;
4127   const Value *SrcV = I.getOperand(0);
4128   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4129                   SrcV->getType(), ValueVTs, &Offsets);
4130   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4131          "expect a single EVT for swifterror");
4132 
4133   SDValue Src = getValue(SrcV);
4134   // Create a virtual register, then update the virtual register.
4135   Register VReg =
4136       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4137   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4138   // Chain can be getRoot or getControlRoot.
4139   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4140                                       SDValue(Src.getNode(), Src.getResNo()));
4141   DAG.setRoot(CopyNode);
4142 }
4143 
4144 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4145   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4146          "call visitLoadFromSwiftError when backend supports swifterror");
4147 
4148   assert(!I.isVolatile() &&
4149          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4150          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4151          "Support volatile, non temporal, invariant for load_from_swift_error");
4152 
4153   const Value *SV = I.getOperand(0);
4154   Type *Ty = I.getType();
4155   AAMDNodes AAInfo;
4156   I.getAAMetadata(AAInfo);
4157   assert(
4158       (!AA ||
4159        !AA->pointsToConstantMemory(MemoryLocation(
4160            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4161            AAInfo))) &&
4162       "load_from_swift_error should not be constant memory");
4163 
4164   SmallVector<EVT, 4> ValueVTs;
4165   SmallVector<uint64_t, 4> Offsets;
4166   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4167                   ValueVTs, &Offsets);
4168   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4169          "expect a single EVT for swifterror");
4170 
4171   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4172   SDValue L = DAG.getCopyFromReg(
4173       getRoot(), getCurSDLoc(),
4174       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4175 
4176   setValue(&I, L);
4177 }
4178 
4179 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4180   if (I.isAtomic())
4181     return visitAtomicStore(I);
4182 
4183   const Value *SrcV = I.getOperand(0);
4184   const Value *PtrV = I.getOperand(1);
4185 
4186   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4187   if (TLI.supportSwiftError()) {
4188     // Swifterror values can come from either a function parameter with
4189     // swifterror attribute or an alloca with swifterror attribute.
4190     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4191       if (Arg->hasSwiftErrorAttr())
4192         return visitStoreToSwiftError(I);
4193     }
4194 
4195     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4196       if (Alloca->isSwiftError())
4197         return visitStoreToSwiftError(I);
4198     }
4199   }
4200 
4201   SmallVector<EVT, 4> ValueVTs, MemVTs;
4202   SmallVector<uint64_t, 4> Offsets;
4203   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4204                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4205   unsigned NumValues = ValueVTs.size();
4206   if (NumValues == 0)
4207     return;
4208 
4209   // Get the lowered operands. Note that we do this after
4210   // checking if NumResults is zero, because with zero results
4211   // the operands won't have values in the map.
4212   SDValue Src = getValue(SrcV);
4213   SDValue Ptr = getValue(PtrV);
4214 
4215   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4216   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4217   SDLoc dl = getCurSDLoc();
4218   Align Alignment = I.getAlign();
4219   AAMDNodes AAInfo;
4220   I.getAAMetadata(AAInfo);
4221 
4222   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4223 
4224   // An aggregate load cannot wrap around the address space, so offsets to its
4225   // parts don't wrap either.
4226   SDNodeFlags Flags;
4227   Flags.setNoUnsignedWrap(true);
4228 
4229   unsigned ChainI = 0;
4230   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4231     // See visitLoad comments.
4232     if (ChainI == MaxParallelChains) {
4233       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4234                                   makeArrayRef(Chains.data(), ChainI));
4235       Root = Chain;
4236       ChainI = 0;
4237     }
4238     SDValue Add =
4239         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4240     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4241     if (MemVTs[i] != ValueVTs[i])
4242       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4243     SDValue St =
4244         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4245                      Alignment, MMOFlags, AAInfo);
4246     Chains[ChainI] = St;
4247   }
4248 
4249   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4250                                   makeArrayRef(Chains.data(), ChainI));
4251   DAG.setRoot(StoreNode);
4252 }
4253 
4254 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4255                                            bool IsCompressing) {
4256   SDLoc sdl = getCurSDLoc();
4257 
4258   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4259                                MaybeAlign &Alignment) {
4260     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4261     Src0 = I.getArgOperand(0);
4262     Ptr = I.getArgOperand(1);
4263     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4264     Mask = I.getArgOperand(3);
4265   };
4266   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4267                                     MaybeAlign &Alignment) {
4268     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4269     Src0 = I.getArgOperand(0);
4270     Ptr = I.getArgOperand(1);
4271     Mask = I.getArgOperand(2);
4272     Alignment = None;
4273   };
4274 
4275   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4276   MaybeAlign Alignment;
4277   if (IsCompressing)
4278     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4279   else
4280     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4281 
4282   SDValue Ptr = getValue(PtrOperand);
4283   SDValue Src0 = getValue(Src0Operand);
4284   SDValue Mask = getValue(MaskOperand);
4285   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4286 
4287   EVT VT = Src0.getValueType();
4288   if (!Alignment)
4289     Alignment = DAG.getEVTAlign(VT);
4290 
4291   AAMDNodes AAInfo;
4292   I.getAAMetadata(AAInfo);
4293 
4294   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4295       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4296       // TODO: Make MachineMemOperands aware of scalable
4297       // vectors.
4298       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4299   SDValue StoreNode =
4300       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4301                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4302   DAG.setRoot(StoreNode);
4303   setValue(&I, StoreNode);
4304 }
4305 
4306 // Get a uniform base for the Gather/Scatter intrinsic.
4307 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4308 // We try to represent it as a base pointer + vector of indices.
4309 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4310 // The first operand of the GEP may be a single pointer or a vector of pointers
4311 // Example:
4312 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4313 //  or
4314 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4315 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4316 //
4317 // When the first GEP operand is a single pointer - it is the uniform base we
4318 // are looking for. If first operand of the GEP is a splat vector - we
4319 // extract the splat value and use it as a uniform base.
4320 // In all other cases the function returns 'false'.
4321 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4322                            ISD::MemIndexType &IndexType, SDValue &Scale,
4323                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4324   SelectionDAG& DAG = SDB->DAG;
4325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4326   const DataLayout &DL = DAG.getDataLayout();
4327 
4328   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4329 
4330   // Handle splat constant pointer.
4331   if (auto *C = dyn_cast<Constant>(Ptr)) {
4332     C = C->getSplatValue();
4333     if (!C)
4334       return false;
4335 
4336     Base = SDB->getValue(C);
4337 
4338     unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
4339     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4340     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4341     IndexType = ISD::SIGNED_SCALED;
4342     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4343     return true;
4344   }
4345 
4346   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4347   if (!GEP || GEP->getParent() != CurBB)
4348     return false;
4349 
4350   if (GEP->getNumOperands() != 2)
4351     return false;
4352 
4353   const Value *BasePtr = GEP->getPointerOperand();
4354   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4355 
4356   // Make sure the base is scalar and the index is a vector.
4357   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4358     return false;
4359 
4360   Base = SDB->getValue(BasePtr);
4361   Index = SDB->getValue(IndexVal);
4362   IndexType = ISD::SIGNED_SCALED;
4363   Scale = DAG.getTargetConstant(
4364               DL.getTypeAllocSize(GEP->getResultElementType()),
4365               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4366   return true;
4367 }
4368 
4369 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4370   SDLoc sdl = getCurSDLoc();
4371 
4372   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4373   const Value *Ptr = I.getArgOperand(1);
4374   SDValue Src0 = getValue(I.getArgOperand(0));
4375   SDValue Mask = getValue(I.getArgOperand(3));
4376   EVT VT = Src0.getValueType();
4377   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4378                         ->getMaybeAlignValue()
4379                         .getValueOr(DAG.getEVTAlign(VT));
4380   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4381 
4382   AAMDNodes AAInfo;
4383   I.getAAMetadata(AAInfo);
4384 
4385   SDValue Base;
4386   SDValue Index;
4387   ISD::MemIndexType IndexType;
4388   SDValue Scale;
4389   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4390                                     I.getParent());
4391 
4392   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4393   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4394       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4395       // TODO: Make MachineMemOperands aware of scalable
4396       // vectors.
4397       MemoryLocation::UnknownSize, Alignment, AAInfo);
4398   if (!UniformBase) {
4399     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4400     Index = getValue(Ptr);
4401     IndexType = ISD::SIGNED_UNSCALED;
4402     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4403   }
4404 
4405   EVT IdxVT = Index.getValueType();
4406   EVT EltTy = IdxVT.getVectorElementType();
4407   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4408     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4409     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4410   }
4411 
4412   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4413   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4414                                          Ops, MMO, IndexType, false);
4415   DAG.setRoot(Scatter);
4416   setValue(&I, Scatter);
4417 }
4418 
4419 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4420   SDLoc sdl = getCurSDLoc();
4421 
4422   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4423                               MaybeAlign &Alignment) {
4424     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4425     Ptr = I.getArgOperand(0);
4426     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4427     Mask = I.getArgOperand(2);
4428     Src0 = I.getArgOperand(3);
4429   };
4430   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4431                                  MaybeAlign &Alignment) {
4432     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4433     Ptr = I.getArgOperand(0);
4434     Alignment = None;
4435     Mask = I.getArgOperand(1);
4436     Src0 = I.getArgOperand(2);
4437   };
4438 
4439   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4440   MaybeAlign Alignment;
4441   if (IsExpanding)
4442     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4443   else
4444     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4445 
4446   SDValue Ptr = getValue(PtrOperand);
4447   SDValue Src0 = getValue(Src0Operand);
4448   SDValue Mask = getValue(MaskOperand);
4449   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4450 
4451   EVT VT = Src0.getValueType();
4452   if (!Alignment)
4453     Alignment = DAG.getEVTAlign(VT);
4454 
4455   AAMDNodes AAInfo;
4456   I.getAAMetadata(AAInfo);
4457   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4458 
4459   // Do not serialize masked loads of constant memory with anything.
4460   MemoryLocation ML;
4461   if (VT.isScalableVector())
4462     ML = MemoryLocation::getAfter(PtrOperand);
4463   else
4464     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4465                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4466                            AAInfo);
4467   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4468 
4469   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4470 
4471   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4472       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4473       // TODO: Make MachineMemOperands aware of scalable
4474       // vectors.
4475       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4476 
4477   SDValue Load =
4478       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4479                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4480   if (AddToChain)
4481     PendingLoads.push_back(Load.getValue(1));
4482   setValue(&I, Load);
4483 }
4484 
4485 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4486   SDLoc sdl = getCurSDLoc();
4487 
4488   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4489   const Value *Ptr = I.getArgOperand(0);
4490   SDValue Src0 = getValue(I.getArgOperand(3));
4491   SDValue Mask = getValue(I.getArgOperand(2));
4492 
4493   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4494   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4495   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4496                         ->getMaybeAlignValue()
4497                         .getValueOr(DAG.getEVTAlign(VT));
4498 
4499   AAMDNodes AAInfo;
4500   I.getAAMetadata(AAInfo);
4501   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4502 
4503   SDValue Root = DAG.getRoot();
4504   SDValue Base;
4505   SDValue Index;
4506   ISD::MemIndexType IndexType;
4507   SDValue Scale;
4508   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4509                                     I.getParent());
4510   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4511   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4512       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4513       // TODO: Make MachineMemOperands aware of scalable
4514       // vectors.
4515       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4516 
4517   if (!UniformBase) {
4518     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4519     Index = getValue(Ptr);
4520     IndexType = ISD::SIGNED_UNSCALED;
4521     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4522   }
4523 
4524   EVT IdxVT = Index.getValueType();
4525   EVT EltTy = IdxVT.getVectorElementType();
4526   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4527     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4528     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4529   }
4530 
4531   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4532   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4533                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4534 
4535   PendingLoads.push_back(Gather.getValue(1));
4536   setValue(&I, Gather);
4537 }
4538 
4539 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4540   SDLoc dl = getCurSDLoc();
4541   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4542   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4543   SyncScope::ID SSID = I.getSyncScopeID();
4544 
4545   SDValue InChain = getRoot();
4546 
4547   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4548   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4549 
4550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4551   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4552 
4553   MachineFunction &MF = DAG.getMachineFunction();
4554   MachineMemOperand *MMO = MF.getMachineMemOperand(
4555       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4556       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4557       FailureOrdering);
4558 
4559   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4560                                    dl, MemVT, VTs, InChain,
4561                                    getValue(I.getPointerOperand()),
4562                                    getValue(I.getCompareOperand()),
4563                                    getValue(I.getNewValOperand()), MMO);
4564 
4565   SDValue OutChain = L.getValue(2);
4566 
4567   setValue(&I, L);
4568   DAG.setRoot(OutChain);
4569 }
4570 
4571 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4572   SDLoc dl = getCurSDLoc();
4573   ISD::NodeType NT;
4574   switch (I.getOperation()) {
4575   default: llvm_unreachable("Unknown atomicrmw operation");
4576   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4577   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4578   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4579   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4580   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4581   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4582   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4583   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4584   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4585   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4586   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4587   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4588   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4589   }
4590   AtomicOrdering Ordering = I.getOrdering();
4591   SyncScope::ID SSID = I.getSyncScopeID();
4592 
4593   SDValue InChain = getRoot();
4594 
4595   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4596   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4597   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4598 
4599   MachineFunction &MF = DAG.getMachineFunction();
4600   MachineMemOperand *MMO = MF.getMachineMemOperand(
4601       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4602       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4603 
4604   SDValue L =
4605     DAG.getAtomic(NT, dl, MemVT, InChain,
4606                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4607                   MMO);
4608 
4609   SDValue OutChain = L.getValue(1);
4610 
4611   setValue(&I, L);
4612   DAG.setRoot(OutChain);
4613 }
4614 
4615 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4616   SDLoc dl = getCurSDLoc();
4617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4618   SDValue Ops[3];
4619   Ops[0] = getRoot();
4620   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4621                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4622   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4623                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4624   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4625 }
4626 
4627 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4628   SDLoc dl = getCurSDLoc();
4629   AtomicOrdering Order = I.getOrdering();
4630   SyncScope::ID SSID = I.getSyncScopeID();
4631 
4632   SDValue InChain = getRoot();
4633 
4634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4635   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4636   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4637 
4638   if (!TLI.supportsUnalignedAtomics() &&
4639       I.getAlignment() < MemVT.getSizeInBits() / 8)
4640     report_fatal_error("Cannot generate unaligned atomic load");
4641 
4642   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4643 
4644   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4645       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4646       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4647 
4648   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4649 
4650   SDValue Ptr = getValue(I.getPointerOperand());
4651 
4652   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4653     // TODO: Once this is better exercised by tests, it should be merged with
4654     // the normal path for loads to prevent future divergence.
4655     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4656     if (MemVT != VT)
4657       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4658 
4659     setValue(&I, L);
4660     SDValue OutChain = L.getValue(1);
4661     if (!I.isUnordered())
4662       DAG.setRoot(OutChain);
4663     else
4664       PendingLoads.push_back(OutChain);
4665     return;
4666   }
4667 
4668   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4669                             Ptr, MMO);
4670 
4671   SDValue OutChain = L.getValue(1);
4672   if (MemVT != VT)
4673     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4674 
4675   setValue(&I, L);
4676   DAG.setRoot(OutChain);
4677 }
4678 
4679 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4680   SDLoc dl = getCurSDLoc();
4681 
4682   AtomicOrdering Ordering = I.getOrdering();
4683   SyncScope::ID SSID = I.getSyncScopeID();
4684 
4685   SDValue InChain = getRoot();
4686 
4687   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4688   EVT MemVT =
4689       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4690 
4691   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4692     report_fatal_error("Cannot generate unaligned atomic store");
4693 
4694   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4695 
4696   MachineFunction &MF = DAG.getMachineFunction();
4697   MachineMemOperand *MMO = MF.getMachineMemOperand(
4698       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4699       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4700 
4701   SDValue Val = getValue(I.getValueOperand());
4702   if (Val.getValueType() != MemVT)
4703     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4704   SDValue Ptr = getValue(I.getPointerOperand());
4705 
4706   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4707     // TODO: Once this is better exercised by tests, it should be merged with
4708     // the normal path for stores to prevent future divergence.
4709     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4710     DAG.setRoot(S);
4711     return;
4712   }
4713   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4714                                    Ptr, Val, MMO);
4715 
4716 
4717   DAG.setRoot(OutChain);
4718 }
4719 
4720 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4721 /// node.
4722 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4723                                                unsigned Intrinsic) {
4724   // Ignore the callsite's attributes. A specific call site may be marked with
4725   // readnone, but the lowering code will expect the chain based on the
4726   // definition.
4727   const Function *F = I.getCalledFunction();
4728   bool HasChain = !F->doesNotAccessMemory();
4729   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4730 
4731   // Build the operand list.
4732   SmallVector<SDValue, 8> Ops;
4733   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4734     if (OnlyLoad) {
4735       // We don't need to serialize loads against other loads.
4736       Ops.push_back(DAG.getRoot());
4737     } else {
4738       Ops.push_back(getRoot());
4739     }
4740   }
4741 
4742   // Info is set by getTgtMemInstrinsic
4743   TargetLowering::IntrinsicInfo Info;
4744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4745   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4746                                                DAG.getMachineFunction(),
4747                                                Intrinsic);
4748 
4749   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4750   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4751       Info.opc == ISD::INTRINSIC_W_CHAIN)
4752     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4753                                         TLI.getPointerTy(DAG.getDataLayout())));
4754 
4755   // Add all operands of the call to the operand list.
4756   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4757     const Value *Arg = I.getArgOperand(i);
4758     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4759       Ops.push_back(getValue(Arg));
4760       continue;
4761     }
4762 
4763     // Use TargetConstant instead of a regular constant for immarg.
4764     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4765     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4766       assert(CI->getBitWidth() <= 64 &&
4767              "large intrinsic immediates not handled");
4768       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4769     } else {
4770       Ops.push_back(
4771           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4772     }
4773   }
4774 
4775   SmallVector<EVT, 4> ValueVTs;
4776   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4777 
4778   if (HasChain)
4779     ValueVTs.push_back(MVT::Other);
4780 
4781   SDVTList VTs = DAG.getVTList(ValueVTs);
4782 
4783   // Create the node.
4784   SDValue Result;
4785   if (IsTgtIntrinsic) {
4786     // This is target intrinsic that touches memory
4787     AAMDNodes AAInfo;
4788     I.getAAMetadata(AAInfo);
4789     Result =
4790         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4791                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4792                                 Info.align, Info.flags, Info.size, AAInfo);
4793   } else if (!HasChain) {
4794     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4795   } else if (!I.getType()->isVoidTy()) {
4796     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4797   } else {
4798     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4799   }
4800 
4801   if (HasChain) {
4802     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4803     if (OnlyLoad)
4804       PendingLoads.push_back(Chain);
4805     else
4806       DAG.setRoot(Chain);
4807   }
4808 
4809   if (!I.getType()->isVoidTy()) {
4810     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4811       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4812       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4813     } else
4814       Result = lowerRangeToAssertZExt(DAG, I, Result);
4815 
4816     MaybeAlign Alignment = I.getRetAlign();
4817     if (!Alignment)
4818       Alignment = F->getAttributes().getRetAlignment();
4819     // Insert `assertalign` node if there's an alignment.
4820     if (InsertAssertAlign && Alignment) {
4821       Result =
4822           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4823     }
4824 
4825     setValue(&I, Result);
4826   }
4827 }
4828 
4829 /// GetSignificand - Get the significand and build it into a floating-point
4830 /// number with exponent of 1:
4831 ///
4832 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4833 ///
4834 /// where Op is the hexadecimal representation of floating point value.
4835 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4836   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4837                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4838   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4839                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4840   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4841 }
4842 
4843 /// GetExponent - Get the exponent:
4844 ///
4845 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4846 ///
4847 /// where Op is the hexadecimal representation of floating point value.
4848 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4849                            const TargetLowering &TLI, const SDLoc &dl) {
4850   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4851                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4852   SDValue t1 = DAG.getNode(
4853       ISD::SRL, dl, MVT::i32, t0,
4854       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4855   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4856                            DAG.getConstant(127, dl, MVT::i32));
4857   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4858 }
4859 
4860 /// getF32Constant - Get 32-bit floating point constant.
4861 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4862                               const SDLoc &dl) {
4863   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4864                            MVT::f32);
4865 }
4866 
4867 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4868                                        SelectionDAG &DAG) {
4869   // TODO: What fast-math-flags should be set on the floating-point nodes?
4870 
4871   //   IntegerPartOfX = ((int32_t)(t0);
4872   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4873 
4874   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4875   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4876   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4877 
4878   //   IntegerPartOfX <<= 23;
4879   IntegerPartOfX = DAG.getNode(
4880       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4881       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4882                                   DAG.getDataLayout())));
4883 
4884   SDValue TwoToFractionalPartOfX;
4885   if (LimitFloatPrecision <= 6) {
4886     // For floating-point precision of 6:
4887     //
4888     //   TwoToFractionalPartOfX =
4889     //     0.997535578f +
4890     //       (0.735607626f + 0.252464424f * x) * x;
4891     //
4892     // error 0.0144103317, which is 6 bits
4893     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4894                              getF32Constant(DAG, 0x3e814304, dl));
4895     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4896                              getF32Constant(DAG, 0x3f3c50c8, dl));
4897     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4898     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4899                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4900   } else if (LimitFloatPrecision <= 12) {
4901     // For floating-point precision of 12:
4902     //
4903     //   TwoToFractionalPartOfX =
4904     //     0.999892986f +
4905     //       (0.696457318f +
4906     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4907     //
4908     // error 0.000107046256, which is 13 to 14 bits
4909     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4910                              getF32Constant(DAG, 0x3da235e3, dl));
4911     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4912                              getF32Constant(DAG, 0x3e65b8f3, dl));
4913     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4914     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4915                              getF32Constant(DAG, 0x3f324b07, dl));
4916     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4917     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4918                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4919   } else { // LimitFloatPrecision <= 18
4920     // For floating-point precision of 18:
4921     //
4922     //   TwoToFractionalPartOfX =
4923     //     0.999999982f +
4924     //       (0.693148872f +
4925     //         (0.240227044f +
4926     //           (0.554906021e-1f +
4927     //             (0.961591928e-2f +
4928     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4929     // error 2.47208000*10^(-7), which is better than 18 bits
4930     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4931                              getF32Constant(DAG, 0x3924b03e, dl));
4932     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4933                              getF32Constant(DAG, 0x3ab24b87, dl));
4934     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4935     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4936                              getF32Constant(DAG, 0x3c1d8c17, dl));
4937     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4938     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4939                              getF32Constant(DAG, 0x3d634a1d, dl));
4940     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4941     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4942                              getF32Constant(DAG, 0x3e75fe14, dl));
4943     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4944     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4945                               getF32Constant(DAG, 0x3f317234, dl));
4946     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4947     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4948                                          getF32Constant(DAG, 0x3f800000, dl));
4949   }
4950 
4951   // Add the exponent into the result in integer domain.
4952   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4953   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4954                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4955 }
4956 
4957 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4958 /// limited-precision mode.
4959 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4960                          const TargetLowering &TLI, SDNodeFlags Flags) {
4961   if (Op.getValueType() == MVT::f32 &&
4962       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4963 
4964     // Put the exponent in the right bit position for later addition to the
4965     // final result:
4966     //
4967     // t0 = Op * log2(e)
4968 
4969     // TODO: What fast-math-flags should be set here?
4970     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4971                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4972     return getLimitedPrecisionExp2(t0, dl, DAG);
4973   }
4974 
4975   // No special expansion.
4976   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
4977 }
4978 
4979 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4980 /// limited-precision mode.
4981 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4982                          const TargetLowering &TLI, SDNodeFlags Flags) {
4983   // TODO: What fast-math-flags should be set on the floating-point nodes?
4984 
4985   if (Op.getValueType() == MVT::f32 &&
4986       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4987     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4988 
4989     // Scale the exponent by log(2).
4990     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4991     SDValue LogOfExponent =
4992         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4993                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4994 
4995     // Get the significand and build it into a floating-point number with
4996     // exponent of 1.
4997     SDValue X = GetSignificand(DAG, Op1, dl);
4998 
4999     SDValue LogOfMantissa;
5000     if (LimitFloatPrecision <= 6) {
5001       // For floating-point precision of 6:
5002       //
5003       //   LogofMantissa =
5004       //     -1.1609546f +
5005       //       (1.4034025f - 0.23903021f * x) * x;
5006       //
5007       // error 0.0034276066, which is better than 8 bits
5008       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5009                                getF32Constant(DAG, 0xbe74c456, dl));
5010       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5011                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5012       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5013       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5014                                   getF32Constant(DAG, 0x3f949a29, dl));
5015     } else if (LimitFloatPrecision <= 12) {
5016       // For floating-point precision of 12:
5017       //
5018       //   LogOfMantissa =
5019       //     -1.7417939f +
5020       //       (2.8212026f +
5021       //         (-1.4699568f +
5022       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5023       //
5024       // error 0.000061011436, which is 14 bits
5025       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5026                                getF32Constant(DAG, 0xbd67b6d6, dl));
5027       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5028                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5029       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5030       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5031                                getF32Constant(DAG, 0x3fbc278b, dl));
5032       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5033       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5034                                getF32Constant(DAG, 0x40348e95, dl));
5035       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5036       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5037                                   getF32Constant(DAG, 0x3fdef31a, dl));
5038     } else { // LimitFloatPrecision <= 18
5039       // For floating-point precision of 18:
5040       //
5041       //   LogOfMantissa =
5042       //     -2.1072184f +
5043       //       (4.2372794f +
5044       //         (-3.7029485f +
5045       //           (2.2781945f +
5046       //             (-0.87823314f +
5047       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5048       //
5049       // error 0.0000023660568, which is better than 18 bits
5050       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5051                                getF32Constant(DAG, 0xbc91e5ac, dl));
5052       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5053                                getF32Constant(DAG, 0x3e4350aa, dl));
5054       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5055       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5056                                getF32Constant(DAG, 0x3f60d3e3, dl));
5057       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5058       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5059                                getF32Constant(DAG, 0x4011cdf0, dl));
5060       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5061       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5062                                getF32Constant(DAG, 0x406cfd1c, dl));
5063       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5064       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5065                                getF32Constant(DAG, 0x408797cb, dl));
5066       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5067       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5068                                   getF32Constant(DAG, 0x4006dcab, dl));
5069     }
5070 
5071     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5072   }
5073 
5074   // No special expansion.
5075   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5076 }
5077 
5078 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5079 /// limited-precision mode.
5080 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5081                           const TargetLowering &TLI, SDNodeFlags Flags) {
5082   // TODO: What fast-math-flags should be set on the floating-point nodes?
5083 
5084   if (Op.getValueType() == MVT::f32 &&
5085       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5086     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5087 
5088     // Get the exponent.
5089     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5090 
5091     // Get the significand and build it into a floating-point number with
5092     // exponent of 1.
5093     SDValue X = GetSignificand(DAG, Op1, dl);
5094 
5095     // Different possible minimax approximations of significand in
5096     // floating-point for various degrees of accuracy over [1,2].
5097     SDValue Log2ofMantissa;
5098     if (LimitFloatPrecision <= 6) {
5099       // For floating-point precision of 6:
5100       //
5101       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5102       //
5103       // error 0.0049451742, which is more than 7 bits
5104       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5105                                getF32Constant(DAG, 0xbeb08fe0, dl));
5106       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5107                                getF32Constant(DAG, 0x40019463, dl));
5108       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5109       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5110                                    getF32Constant(DAG, 0x3fd6633d, dl));
5111     } else if (LimitFloatPrecision <= 12) {
5112       // For floating-point precision of 12:
5113       //
5114       //   Log2ofMantissa =
5115       //     -2.51285454f +
5116       //       (4.07009056f +
5117       //         (-2.12067489f +
5118       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5119       //
5120       // error 0.0000876136000, which is better than 13 bits
5121       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5122                                getF32Constant(DAG, 0xbda7262e, dl));
5123       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5124                                getF32Constant(DAG, 0x3f25280b, dl));
5125       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5126       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5127                                getF32Constant(DAG, 0x4007b923, dl));
5128       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5129       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5130                                getF32Constant(DAG, 0x40823e2f, dl));
5131       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5132       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5133                                    getF32Constant(DAG, 0x4020d29c, dl));
5134     } else { // LimitFloatPrecision <= 18
5135       // For floating-point precision of 18:
5136       //
5137       //   Log2ofMantissa =
5138       //     -3.0400495f +
5139       //       (6.1129976f +
5140       //         (-5.3420409f +
5141       //           (3.2865683f +
5142       //             (-1.2669343f +
5143       //               (0.27515199f -
5144       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5145       //
5146       // error 0.0000018516, which is better than 18 bits
5147       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5148                                getF32Constant(DAG, 0xbcd2769e, dl));
5149       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5150                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5151       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5152       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5153                                getF32Constant(DAG, 0x3fa22ae7, dl));
5154       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5155       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5156                                getF32Constant(DAG, 0x40525723, dl));
5157       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5158       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5159                                getF32Constant(DAG, 0x40aaf200, dl));
5160       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5161       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5162                                getF32Constant(DAG, 0x40c39dad, dl));
5163       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5164       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5165                                    getF32Constant(DAG, 0x4042902c, dl));
5166     }
5167 
5168     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5169   }
5170 
5171   // No special expansion.
5172   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5173 }
5174 
5175 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5176 /// limited-precision mode.
5177 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5178                            const TargetLowering &TLI, SDNodeFlags Flags) {
5179   // TODO: What fast-math-flags should be set on the floating-point nodes?
5180 
5181   if (Op.getValueType() == MVT::f32 &&
5182       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5183     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5184 
5185     // Scale the exponent by log10(2) [0.30102999f].
5186     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5187     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5188                                         getF32Constant(DAG, 0x3e9a209a, dl));
5189 
5190     // Get the significand and build it into a floating-point number with
5191     // exponent of 1.
5192     SDValue X = GetSignificand(DAG, Op1, dl);
5193 
5194     SDValue Log10ofMantissa;
5195     if (LimitFloatPrecision <= 6) {
5196       // For floating-point precision of 6:
5197       //
5198       //   Log10ofMantissa =
5199       //     -0.50419619f +
5200       //       (0.60948995f - 0.10380950f * x) * x;
5201       //
5202       // error 0.0014886165, which is 6 bits
5203       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5204                                getF32Constant(DAG, 0xbdd49a13, dl));
5205       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5206                                getF32Constant(DAG, 0x3f1c0789, dl));
5207       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5208       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5209                                     getF32Constant(DAG, 0x3f011300, dl));
5210     } else if (LimitFloatPrecision <= 12) {
5211       // For floating-point precision of 12:
5212       //
5213       //   Log10ofMantissa =
5214       //     -0.64831180f +
5215       //       (0.91751397f +
5216       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5217       //
5218       // error 0.00019228036, which is better than 12 bits
5219       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5220                                getF32Constant(DAG, 0x3d431f31, dl));
5221       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5222                                getF32Constant(DAG, 0x3ea21fb2, dl));
5223       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5224       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5225                                getF32Constant(DAG, 0x3f6ae232, dl));
5226       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5227       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5228                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5229     } else { // LimitFloatPrecision <= 18
5230       // For floating-point precision of 18:
5231       //
5232       //   Log10ofMantissa =
5233       //     -0.84299375f +
5234       //       (1.5327582f +
5235       //         (-1.0688956f +
5236       //           (0.49102474f +
5237       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5238       //
5239       // error 0.0000037995730, which is better than 18 bits
5240       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5241                                getF32Constant(DAG, 0x3c5d51ce, dl));
5242       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5243                                getF32Constant(DAG, 0x3e00685a, dl));
5244       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5245       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5246                                getF32Constant(DAG, 0x3efb6798, dl));
5247       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5248       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5249                                getF32Constant(DAG, 0x3f88d192, dl));
5250       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5251       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5252                                getF32Constant(DAG, 0x3fc4316c, dl));
5253       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5254       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5255                                     getF32Constant(DAG, 0x3f57ce70, dl));
5256     }
5257 
5258     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5259   }
5260 
5261   // No special expansion.
5262   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5263 }
5264 
5265 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5266 /// limited-precision mode.
5267 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5268                           const TargetLowering &TLI, SDNodeFlags Flags) {
5269   if (Op.getValueType() == MVT::f32 &&
5270       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5271     return getLimitedPrecisionExp2(Op, dl, DAG);
5272 
5273   // No special expansion.
5274   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5275 }
5276 
5277 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5278 /// limited-precision mode with x == 10.0f.
5279 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5280                          SelectionDAG &DAG, const TargetLowering &TLI,
5281                          SDNodeFlags Flags) {
5282   bool IsExp10 = false;
5283   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5284       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5285     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5286       APFloat Ten(10.0f);
5287       IsExp10 = LHSC->isExactlyValue(Ten);
5288     }
5289   }
5290 
5291   // TODO: What fast-math-flags should be set on the FMUL node?
5292   if (IsExp10) {
5293     // Put the exponent in the right bit position for later addition to the
5294     // final result:
5295     //
5296     //   #define LOG2OF10 3.3219281f
5297     //   t0 = Op * LOG2OF10;
5298     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5299                              getF32Constant(DAG, 0x40549a78, dl));
5300     return getLimitedPrecisionExp2(t0, dl, DAG);
5301   }
5302 
5303   // No special expansion.
5304   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5305 }
5306 
5307 /// ExpandPowI - Expand a llvm.powi intrinsic.
5308 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5309                           SelectionDAG &DAG) {
5310   // If RHS is a constant, we can expand this out to a multiplication tree,
5311   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5312   // optimizing for size, we only want to do this if the expansion would produce
5313   // a small number of multiplies, otherwise we do the full expansion.
5314   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5315     // Get the exponent as a positive value.
5316     unsigned Val = RHSC->getSExtValue();
5317     if ((int)Val < 0) Val = -Val;
5318 
5319     // powi(x, 0) -> 1.0
5320     if (Val == 0)
5321       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5322 
5323     bool OptForSize = DAG.shouldOptForSize();
5324     if (!OptForSize ||
5325         // If optimizing for size, don't insert too many multiplies.
5326         // This inserts up to 5 multiplies.
5327         countPopulation(Val) + Log2_32(Val) < 7) {
5328       // We use the simple binary decomposition method to generate the multiply
5329       // sequence.  There are more optimal ways to do this (for example,
5330       // powi(x,15) generates one more multiply than it should), but this has
5331       // the benefit of being both really simple and much better than a libcall.
5332       SDValue Res;  // Logically starts equal to 1.0
5333       SDValue CurSquare = LHS;
5334       // TODO: Intrinsics should have fast-math-flags that propagate to these
5335       // nodes.
5336       while (Val) {
5337         if (Val & 1) {
5338           if (Res.getNode())
5339             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5340           else
5341             Res = CurSquare;  // 1.0*CurSquare.
5342         }
5343 
5344         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5345                                 CurSquare, CurSquare);
5346         Val >>= 1;
5347       }
5348 
5349       // If the original was negative, invert the result, producing 1/(x*x*x).
5350       if (RHSC->getSExtValue() < 0)
5351         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5352                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5353       return Res;
5354     }
5355   }
5356 
5357   // Otherwise, expand to a libcall.
5358   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5359 }
5360 
5361 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5362                             SDValue LHS, SDValue RHS, SDValue Scale,
5363                             SelectionDAG &DAG, const TargetLowering &TLI) {
5364   EVT VT = LHS.getValueType();
5365   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5366   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5367   LLVMContext &Ctx = *DAG.getContext();
5368 
5369   // If the type is legal but the operation isn't, this node might survive all
5370   // the way to operation legalization. If we end up there and we do not have
5371   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5372   // node.
5373 
5374   // Coax the legalizer into expanding the node during type legalization instead
5375   // by bumping the size by one bit. This will force it to Promote, enabling the
5376   // early expansion and avoiding the need to expand later.
5377 
5378   // We don't have to do this if Scale is 0; that can always be expanded, unless
5379   // it's a saturating signed operation. Those can experience true integer
5380   // division overflow, a case which we must avoid.
5381 
5382   // FIXME: We wouldn't have to do this (or any of the early
5383   // expansion/promotion) if it was possible to expand a libcall of an
5384   // illegal type during operation legalization. But it's not, so things
5385   // get a bit hacky.
5386   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5387   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5388       (TLI.isTypeLegal(VT) ||
5389        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5390     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5391         Opcode, VT, ScaleInt);
5392     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5393       EVT PromVT;
5394       if (VT.isScalarInteger())
5395         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5396       else if (VT.isVector()) {
5397         PromVT = VT.getVectorElementType();
5398         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5399         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5400       } else
5401         llvm_unreachable("Wrong VT for DIVFIX?");
5402       if (Signed) {
5403         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5404         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5405       } else {
5406         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5407         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5408       }
5409       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5410       // For saturating operations, we need to shift up the LHS to get the
5411       // proper saturation width, and then shift down again afterwards.
5412       if (Saturating)
5413         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5414                           DAG.getConstant(1, DL, ShiftTy));
5415       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5416       if (Saturating)
5417         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5418                           DAG.getConstant(1, DL, ShiftTy));
5419       return DAG.getZExtOrTrunc(Res, DL, VT);
5420     }
5421   }
5422 
5423   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5424 }
5425 
5426 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5427 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5428 static void
5429 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5430                      const SDValue &N) {
5431   switch (N.getOpcode()) {
5432   case ISD::CopyFromReg: {
5433     SDValue Op = N.getOperand(1);
5434     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5435                       Op.getValueType().getSizeInBits());
5436     return;
5437   }
5438   case ISD::BITCAST:
5439   case ISD::AssertZext:
5440   case ISD::AssertSext:
5441   case ISD::TRUNCATE:
5442     getUnderlyingArgRegs(Regs, N.getOperand(0));
5443     return;
5444   case ISD::BUILD_PAIR:
5445   case ISD::BUILD_VECTOR:
5446   case ISD::CONCAT_VECTORS:
5447     for (SDValue Op : N->op_values())
5448       getUnderlyingArgRegs(Regs, Op);
5449     return;
5450   default:
5451     return;
5452   }
5453 }
5454 
5455 /// If the DbgValueInst is a dbg_value of a function argument, create the
5456 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5457 /// instruction selection, they will be inserted to the entry BB.
5458 /// We don't currently support this for variadic dbg_values, as they shouldn't
5459 /// appear for function arguments or in the prologue.
5460 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5461     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5462     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5463   const Argument *Arg = dyn_cast<Argument>(V);
5464   if (!Arg)
5465     return false;
5466 
5467   if (!IsDbgDeclare) {
5468     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5469     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5470     // the entry block.
5471     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5472     if (!IsInEntryBlock)
5473       return false;
5474 
5475     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5476     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5477     // variable that also is a param.
5478     //
5479     // Although, if we are at the top of the entry block already, we can still
5480     // emit using ArgDbgValue. This might catch some situations when the
5481     // dbg.value refers to an argument that isn't used in the entry block, so
5482     // any CopyToReg node would be optimized out and the only way to express
5483     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5484     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5485     // we should only emit as ArgDbgValue if the Variable is an argument to the
5486     // current function, and the dbg.value intrinsic is found in the entry
5487     // block.
5488     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5489         !DL->getInlinedAt();
5490     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5491     if (!IsInPrologue && !VariableIsFunctionInputArg)
5492       return false;
5493 
5494     // Here we assume that a function argument on IR level only can be used to
5495     // describe one input parameter on source level. If we for example have
5496     // source code like this
5497     //
5498     //    struct A { long x, y; };
5499     //    void foo(struct A a, long b) {
5500     //      ...
5501     //      b = a.x;
5502     //      ...
5503     //    }
5504     //
5505     // and IR like this
5506     //
5507     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5508     //  entry:
5509     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5510     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5511     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5512     //    ...
5513     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5514     //    ...
5515     //
5516     // then the last dbg.value is describing a parameter "b" using a value that
5517     // is an argument. But since we already has used %a1 to describe a parameter
5518     // we should not handle that last dbg.value here (that would result in an
5519     // incorrect hoisting of the DBG_VALUE to the function entry).
5520     // Notice that we allow one dbg.value per IR level argument, to accommodate
5521     // for the situation with fragments above.
5522     if (VariableIsFunctionInputArg) {
5523       unsigned ArgNo = Arg->getArgNo();
5524       if (ArgNo >= FuncInfo.DescribedArgs.size())
5525         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5526       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5527         return false;
5528       FuncInfo.DescribedArgs.set(ArgNo);
5529     }
5530   }
5531 
5532   MachineFunction &MF = DAG.getMachineFunction();
5533   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5534 
5535   bool IsIndirect = false;
5536   Optional<MachineOperand> Op;
5537   // Some arguments' frame index is recorded during argument lowering.
5538   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5539   if (FI != std::numeric_limits<int>::max())
5540     Op = MachineOperand::CreateFI(FI);
5541 
5542   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5543   if (!Op && N.getNode()) {
5544     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5545     Register Reg;
5546     if (ArgRegsAndSizes.size() == 1)
5547       Reg = ArgRegsAndSizes.front().first;
5548 
5549     if (Reg && Reg.isVirtual()) {
5550       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5551       Register PR = RegInfo.getLiveInPhysReg(Reg);
5552       if (PR)
5553         Reg = PR;
5554     }
5555     if (Reg) {
5556       Op = MachineOperand::CreateReg(Reg, false);
5557       IsIndirect = IsDbgDeclare;
5558     }
5559   }
5560 
5561   if (!Op && N.getNode()) {
5562     // Check if frame index is available.
5563     SDValue LCandidate = peekThroughBitcasts(N);
5564     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5565       if (FrameIndexSDNode *FINode =
5566           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5567         Op = MachineOperand::CreateFI(FINode->getIndex());
5568   }
5569 
5570   if (!Op) {
5571     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5572     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5573                                          SplitRegs) {
5574       unsigned Offset = 0;
5575       for (auto RegAndSize : SplitRegs) {
5576         // If the expression is already a fragment, the current register
5577         // offset+size might extend beyond the fragment. In this case, only
5578         // the register bits that are inside the fragment are relevant.
5579         int RegFragmentSizeInBits = RegAndSize.second;
5580         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5581           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5582           // The register is entirely outside the expression fragment,
5583           // so is irrelevant for debug info.
5584           if (Offset >= ExprFragmentSizeInBits)
5585             break;
5586           // The register is partially outside the expression fragment, only
5587           // the low bits within the fragment are relevant for debug info.
5588           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5589             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5590           }
5591         }
5592 
5593         auto FragmentExpr = DIExpression::createFragmentExpression(
5594             Expr, Offset, RegFragmentSizeInBits);
5595         Offset += RegAndSize.second;
5596         // If a valid fragment expression cannot be created, the variable's
5597         // correct value cannot be determined and so it is set as Undef.
5598         if (!FragmentExpr) {
5599           SDDbgValue *SDV = DAG.getConstantDbgValue(
5600               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5601           DAG.AddDbgValue(SDV, false);
5602           continue;
5603         }
5604         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5605         FuncInfo.ArgDbgValues.push_back(
5606           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5607                   RegAndSize.first, Variable, *FragmentExpr));
5608       }
5609     };
5610 
5611     // Check if ValueMap has reg number.
5612     DenseMap<const Value *, Register>::const_iterator
5613       VMI = FuncInfo.ValueMap.find(V);
5614     if (VMI != FuncInfo.ValueMap.end()) {
5615       const auto &TLI = DAG.getTargetLoweringInfo();
5616       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5617                        V->getType(), None);
5618       if (RFV.occupiesMultipleRegs()) {
5619         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5620         return true;
5621       }
5622 
5623       Op = MachineOperand::CreateReg(VMI->second, false);
5624       IsIndirect = IsDbgDeclare;
5625     } else if (ArgRegsAndSizes.size() > 1) {
5626       // This was split due to the calling convention, and no virtual register
5627       // mapping exists for the value.
5628       splitMultiRegDbgValue(ArgRegsAndSizes);
5629       return true;
5630     }
5631   }
5632 
5633   if (!Op)
5634     return false;
5635 
5636   assert(Variable->isValidLocationForIntrinsic(DL) &&
5637          "Expected inlined-at fields to agree");
5638   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5639   FuncInfo.ArgDbgValues.push_back(
5640       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5641               *Op, Variable, Expr));
5642 
5643   return true;
5644 }
5645 
5646 /// Return the appropriate SDDbgValue based on N.
5647 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5648                                              DILocalVariable *Variable,
5649                                              DIExpression *Expr,
5650                                              const DebugLoc &dl,
5651                                              unsigned DbgSDNodeOrder) {
5652   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5653     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5654     // stack slot locations.
5655     //
5656     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5657     // debug values here after optimization:
5658     //
5659     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5660     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5661     //
5662     // Both describe the direct values of their associated variables.
5663     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5664                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5665   }
5666   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5667                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5668 }
5669 
5670 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5671   switch (Intrinsic) {
5672   case Intrinsic::smul_fix:
5673     return ISD::SMULFIX;
5674   case Intrinsic::umul_fix:
5675     return ISD::UMULFIX;
5676   case Intrinsic::smul_fix_sat:
5677     return ISD::SMULFIXSAT;
5678   case Intrinsic::umul_fix_sat:
5679     return ISD::UMULFIXSAT;
5680   case Intrinsic::sdiv_fix:
5681     return ISD::SDIVFIX;
5682   case Intrinsic::udiv_fix:
5683     return ISD::UDIVFIX;
5684   case Intrinsic::sdiv_fix_sat:
5685     return ISD::SDIVFIXSAT;
5686   case Intrinsic::udiv_fix_sat:
5687     return ISD::UDIVFIXSAT;
5688   default:
5689     llvm_unreachable("Unhandled fixed point intrinsic");
5690   }
5691 }
5692 
5693 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5694                                            const char *FunctionName) {
5695   assert(FunctionName && "FunctionName must not be nullptr");
5696   SDValue Callee = DAG.getExternalSymbol(
5697       FunctionName,
5698       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5699   LowerCallTo(I, Callee, I.isTailCall());
5700 }
5701 
5702 /// Given a @llvm.call.preallocated.setup, return the corresponding
5703 /// preallocated call.
5704 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5705   assert(cast<CallBase>(PreallocatedSetup)
5706                  ->getCalledFunction()
5707                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5708          "expected call_preallocated_setup Value");
5709   for (auto *U : PreallocatedSetup->users()) {
5710     auto *UseCall = cast<CallBase>(U);
5711     const Function *Fn = UseCall->getCalledFunction();
5712     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5713       return UseCall;
5714     }
5715   }
5716   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5717 }
5718 
5719 /// Lower the call to the specified intrinsic function.
5720 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5721                                              unsigned Intrinsic) {
5722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5723   SDLoc sdl = getCurSDLoc();
5724   DebugLoc dl = getCurDebugLoc();
5725   SDValue Res;
5726 
5727   SDNodeFlags Flags;
5728   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5729     Flags.copyFMF(*FPOp);
5730 
5731   switch (Intrinsic) {
5732   default:
5733     // By default, turn this into a target intrinsic node.
5734     visitTargetIntrinsic(I, Intrinsic);
5735     return;
5736   case Intrinsic::vscale: {
5737     match(&I, m_VScale(DAG.getDataLayout()));
5738     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5739     setValue(&I,
5740              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5741     return;
5742   }
5743   case Intrinsic::vastart:  visitVAStart(I); return;
5744   case Intrinsic::vaend:    visitVAEnd(I); return;
5745   case Intrinsic::vacopy:   visitVACopy(I); return;
5746   case Intrinsic::returnaddress:
5747     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5748                              TLI.getPointerTy(DAG.getDataLayout()),
5749                              getValue(I.getArgOperand(0))));
5750     return;
5751   case Intrinsic::addressofreturnaddress:
5752     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5753                              TLI.getPointerTy(DAG.getDataLayout())));
5754     return;
5755   case Intrinsic::sponentry:
5756     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5757                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5758     return;
5759   case Intrinsic::frameaddress:
5760     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5761                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5762                              getValue(I.getArgOperand(0))));
5763     return;
5764   case Intrinsic::read_volatile_register:
5765   case Intrinsic::read_register: {
5766     Value *Reg = I.getArgOperand(0);
5767     SDValue Chain = getRoot();
5768     SDValue RegName =
5769         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5770     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5771     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5772       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5773     setValue(&I, Res);
5774     DAG.setRoot(Res.getValue(1));
5775     return;
5776   }
5777   case Intrinsic::write_register: {
5778     Value *Reg = I.getArgOperand(0);
5779     Value *RegValue = I.getArgOperand(1);
5780     SDValue Chain = getRoot();
5781     SDValue RegName =
5782         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5783     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5784                             RegName, getValue(RegValue)));
5785     return;
5786   }
5787   case Intrinsic::memcpy: {
5788     const auto &MCI = cast<MemCpyInst>(I);
5789     SDValue Op1 = getValue(I.getArgOperand(0));
5790     SDValue Op2 = getValue(I.getArgOperand(1));
5791     SDValue Op3 = getValue(I.getArgOperand(2));
5792     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5793     Align DstAlign = MCI.getDestAlign().valueOrOne();
5794     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5795     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5796     bool isVol = MCI.isVolatile();
5797     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5798     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5799     // node.
5800     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5801     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5802                                /* AlwaysInline */ false, isTC,
5803                                MachinePointerInfo(I.getArgOperand(0)),
5804                                MachinePointerInfo(I.getArgOperand(1)));
5805     updateDAGForMaybeTailCall(MC);
5806     return;
5807   }
5808   case Intrinsic::memcpy_inline: {
5809     const auto &MCI = cast<MemCpyInlineInst>(I);
5810     SDValue Dst = getValue(I.getArgOperand(0));
5811     SDValue Src = getValue(I.getArgOperand(1));
5812     SDValue Size = getValue(I.getArgOperand(2));
5813     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5814     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5815     Align DstAlign = MCI.getDestAlign().valueOrOne();
5816     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5817     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5818     bool isVol = MCI.isVolatile();
5819     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5820     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5821     // node.
5822     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5823                                /* AlwaysInline */ true, isTC,
5824                                MachinePointerInfo(I.getArgOperand(0)),
5825                                MachinePointerInfo(I.getArgOperand(1)));
5826     updateDAGForMaybeTailCall(MC);
5827     return;
5828   }
5829   case Intrinsic::memset: {
5830     const auto &MSI = cast<MemSetInst>(I);
5831     SDValue Op1 = getValue(I.getArgOperand(0));
5832     SDValue Op2 = getValue(I.getArgOperand(1));
5833     SDValue Op3 = getValue(I.getArgOperand(2));
5834     // @llvm.memset defines 0 and 1 to both mean no alignment.
5835     Align Alignment = MSI.getDestAlign().valueOrOne();
5836     bool isVol = MSI.isVolatile();
5837     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5838     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5839     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5840                                MachinePointerInfo(I.getArgOperand(0)));
5841     updateDAGForMaybeTailCall(MS);
5842     return;
5843   }
5844   case Intrinsic::memmove: {
5845     const auto &MMI = cast<MemMoveInst>(I);
5846     SDValue Op1 = getValue(I.getArgOperand(0));
5847     SDValue Op2 = getValue(I.getArgOperand(1));
5848     SDValue Op3 = getValue(I.getArgOperand(2));
5849     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5850     Align DstAlign = MMI.getDestAlign().valueOrOne();
5851     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5852     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5853     bool isVol = MMI.isVolatile();
5854     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5855     // FIXME: Support passing different dest/src alignments to the memmove DAG
5856     // node.
5857     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5858     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5859                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5860                                 MachinePointerInfo(I.getArgOperand(1)));
5861     updateDAGForMaybeTailCall(MM);
5862     return;
5863   }
5864   case Intrinsic::memcpy_element_unordered_atomic: {
5865     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5866     SDValue Dst = getValue(MI.getRawDest());
5867     SDValue Src = getValue(MI.getRawSource());
5868     SDValue Length = getValue(MI.getLength());
5869 
5870     unsigned DstAlign = MI.getDestAlignment();
5871     unsigned SrcAlign = MI.getSourceAlignment();
5872     Type *LengthTy = MI.getLength()->getType();
5873     unsigned ElemSz = MI.getElementSizeInBytes();
5874     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5875     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5876                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5877                                      MachinePointerInfo(MI.getRawDest()),
5878                                      MachinePointerInfo(MI.getRawSource()));
5879     updateDAGForMaybeTailCall(MC);
5880     return;
5881   }
5882   case Intrinsic::memmove_element_unordered_atomic: {
5883     auto &MI = cast<AtomicMemMoveInst>(I);
5884     SDValue Dst = getValue(MI.getRawDest());
5885     SDValue Src = getValue(MI.getRawSource());
5886     SDValue Length = getValue(MI.getLength());
5887 
5888     unsigned DstAlign = MI.getDestAlignment();
5889     unsigned SrcAlign = MI.getSourceAlignment();
5890     Type *LengthTy = MI.getLength()->getType();
5891     unsigned ElemSz = MI.getElementSizeInBytes();
5892     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5893     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5894                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5895                                       MachinePointerInfo(MI.getRawDest()),
5896                                       MachinePointerInfo(MI.getRawSource()));
5897     updateDAGForMaybeTailCall(MC);
5898     return;
5899   }
5900   case Intrinsic::memset_element_unordered_atomic: {
5901     auto &MI = cast<AtomicMemSetInst>(I);
5902     SDValue Dst = getValue(MI.getRawDest());
5903     SDValue Val = getValue(MI.getValue());
5904     SDValue Length = getValue(MI.getLength());
5905 
5906     unsigned DstAlign = MI.getDestAlignment();
5907     Type *LengthTy = MI.getLength()->getType();
5908     unsigned ElemSz = MI.getElementSizeInBytes();
5909     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5910     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5911                                      LengthTy, ElemSz, isTC,
5912                                      MachinePointerInfo(MI.getRawDest()));
5913     updateDAGForMaybeTailCall(MC);
5914     return;
5915   }
5916   case Intrinsic::call_preallocated_setup: {
5917     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5918     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5919     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5920                               getRoot(), SrcValue);
5921     setValue(&I, Res);
5922     DAG.setRoot(Res);
5923     return;
5924   }
5925   case Intrinsic::call_preallocated_arg: {
5926     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5927     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5928     SDValue Ops[3];
5929     Ops[0] = getRoot();
5930     Ops[1] = SrcValue;
5931     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5932                                    MVT::i32); // arg index
5933     SDValue Res = DAG.getNode(
5934         ISD::PREALLOCATED_ARG, sdl,
5935         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5936     setValue(&I, Res);
5937     DAG.setRoot(Res.getValue(1));
5938     return;
5939   }
5940   case Intrinsic::dbg_addr:
5941   case Intrinsic::dbg_declare: {
5942     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
5943     // they are non-variadic.
5944     const auto &DI = cast<DbgVariableIntrinsic>(I);
5945     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
5946     DILocalVariable *Variable = DI.getVariable();
5947     DIExpression *Expression = DI.getExpression();
5948     dropDanglingDebugInfo(Variable, Expression);
5949     assert(Variable && "Missing variable");
5950     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5951                       << "\n");
5952     // Check if address has undef value.
5953     const Value *Address = DI.getVariableLocationOp(0);
5954     if (!Address || isa<UndefValue>(Address) ||
5955         (Address->use_empty() && !isa<Argument>(Address))) {
5956       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5957                         << " (bad/undef/unused-arg address)\n");
5958       return;
5959     }
5960 
5961     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5962 
5963     // Check if this variable can be described by a frame index, typically
5964     // either as a static alloca or a byval parameter.
5965     int FI = std::numeric_limits<int>::max();
5966     if (const auto *AI =
5967             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5968       if (AI->isStaticAlloca()) {
5969         auto I = FuncInfo.StaticAllocaMap.find(AI);
5970         if (I != FuncInfo.StaticAllocaMap.end())
5971           FI = I->second;
5972       }
5973     } else if (const auto *Arg = dyn_cast<Argument>(
5974                    Address->stripInBoundsConstantOffsets())) {
5975       FI = FuncInfo.getArgumentFrameIndex(Arg);
5976     }
5977 
5978     // llvm.dbg.addr is control dependent and always generates indirect
5979     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5980     // the MachineFunction variable table.
5981     if (FI != std::numeric_limits<int>::max()) {
5982       if (Intrinsic == Intrinsic::dbg_addr) {
5983         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5984             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
5985             dl, SDNodeOrder);
5986         DAG.AddDbgValue(SDV, isParameter);
5987       } else {
5988         LLVM_DEBUG(dbgs() << "Skipping " << DI
5989                           << " (variable info stashed in MF side table)\n");
5990       }
5991       return;
5992     }
5993 
5994     SDValue &N = NodeMap[Address];
5995     if (!N.getNode() && isa<Argument>(Address))
5996       // Check unused arguments map.
5997       N = UnusedArgNodeMap[Address];
5998     SDDbgValue *SDV;
5999     if (N.getNode()) {
6000       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6001         Address = BCI->getOperand(0);
6002       // Parameters are handled specially.
6003       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6004       if (isParameter && FINode) {
6005         // Byval parameter. We have a frame index at this point.
6006         SDV =
6007             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6008                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6009       } else if (isa<Argument>(Address)) {
6010         // Address is an argument, so try to emit its dbg value using
6011         // virtual register info from the FuncInfo.ValueMap.
6012         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6013         return;
6014       } else {
6015         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6016                               true, dl, SDNodeOrder);
6017       }
6018       DAG.AddDbgValue(SDV, isParameter);
6019     } else {
6020       // If Address is an argument then try to emit its dbg value using
6021       // virtual register info from the FuncInfo.ValueMap.
6022       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6023                                     N)) {
6024         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6025                           << " (could not emit func-arg dbg_value)\n");
6026       }
6027     }
6028     return;
6029   }
6030   case Intrinsic::dbg_label: {
6031     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6032     DILabel *Label = DI.getLabel();
6033     assert(Label && "Missing label");
6034 
6035     SDDbgLabel *SDV;
6036     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6037     DAG.AddDbgLabel(SDV);
6038     return;
6039   }
6040   case Intrinsic::dbg_value: {
6041     const DbgValueInst &DI = cast<DbgValueInst>(I);
6042     assert(DI.getVariable() && "Missing variable");
6043 
6044     DILocalVariable *Variable = DI.getVariable();
6045     DIExpression *Expression = DI.getExpression();
6046     dropDanglingDebugInfo(Variable, Expression);
6047     SmallVector<Value *> Values(DI.getValues());
6048     if (Values.empty())
6049       return;
6050 
6051     if (std::count(Values.begin(), Values.end(), nullptr))
6052       return;
6053 
6054     bool IsVariadic = DI.hasArgList();
6055     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6056                           SDNodeOrder, IsVariadic))
6057       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6058     return;
6059   }
6060 
6061   case Intrinsic::eh_typeid_for: {
6062     // Find the type id for the given typeinfo.
6063     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6064     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6065     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6066     setValue(&I, Res);
6067     return;
6068   }
6069 
6070   case Intrinsic::eh_return_i32:
6071   case Intrinsic::eh_return_i64:
6072     DAG.getMachineFunction().setCallsEHReturn(true);
6073     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6074                             MVT::Other,
6075                             getControlRoot(),
6076                             getValue(I.getArgOperand(0)),
6077                             getValue(I.getArgOperand(1))));
6078     return;
6079   case Intrinsic::eh_unwind_init:
6080     DAG.getMachineFunction().setCallsUnwindInit(true);
6081     return;
6082   case Intrinsic::eh_dwarf_cfa:
6083     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6084                              TLI.getPointerTy(DAG.getDataLayout()),
6085                              getValue(I.getArgOperand(0))));
6086     return;
6087   case Intrinsic::eh_sjlj_callsite: {
6088     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6089     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6090     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6091     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6092 
6093     MMI.setCurrentCallSite(CI->getZExtValue());
6094     return;
6095   }
6096   case Intrinsic::eh_sjlj_functioncontext: {
6097     // Get and store the index of the function context.
6098     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6099     AllocaInst *FnCtx =
6100       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6101     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6102     MFI.setFunctionContextIndex(FI);
6103     return;
6104   }
6105   case Intrinsic::eh_sjlj_setjmp: {
6106     SDValue Ops[2];
6107     Ops[0] = getRoot();
6108     Ops[1] = getValue(I.getArgOperand(0));
6109     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6110                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6111     setValue(&I, Op.getValue(0));
6112     DAG.setRoot(Op.getValue(1));
6113     return;
6114   }
6115   case Intrinsic::eh_sjlj_longjmp:
6116     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6117                             getRoot(), getValue(I.getArgOperand(0))));
6118     return;
6119   case Intrinsic::eh_sjlj_setup_dispatch:
6120     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6121                             getRoot()));
6122     return;
6123   case Intrinsic::masked_gather:
6124     visitMaskedGather(I);
6125     return;
6126   case Intrinsic::masked_load:
6127     visitMaskedLoad(I);
6128     return;
6129   case Intrinsic::masked_scatter:
6130     visitMaskedScatter(I);
6131     return;
6132   case Intrinsic::masked_store:
6133     visitMaskedStore(I);
6134     return;
6135   case Intrinsic::masked_expandload:
6136     visitMaskedLoad(I, true /* IsExpanding */);
6137     return;
6138   case Intrinsic::masked_compressstore:
6139     visitMaskedStore(I, true /* IsCompressing */);
6140     return;
6141   case Intrinsic::powi:
6142     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6143                             getValue(I.getArgOperand(1)), DAG));
6144     return;
6145   case Intrinsic::log:
6146     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6147     return;
6148   case Intrinsic::log2:
6149     setValue(&I,
6150              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6151     return;
6152   case Intrinsic::log10:
6153     setValue(&I,
6154              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6155     return;
6156   case Intrinsic::exp:
6157     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6158     return;
6159   case Intrinsic::exp2:
6160     setValue(&I,
6161              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6162     return;
6163   case Intrinsic::pow:
6164     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6165                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6166     return;
6167   case Intrinsic::sqrt:
6168   case Intrinsic::fabs:
6169   case Intrinsic::sin:
6170   case Intrinsic::cos:
6171   case Intrinsic::floor:
6172   case Intrinsic::ceil:
6173   case Intrinsic::trunc:
6174   case Intrinsic::rint:
6175   case Intrinsic::nearbyint:
6176   case Intrinsic::round:
6177   case Intrinsic::roundeven:
6178   case Intrinsic::canonicalize: {
6179     unsigned Opcode;
6180     switch (Intrinsic) {
6181     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6182     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6183     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6184     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6185     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6186     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6187     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6188     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6189     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6190     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6191     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6192     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6193     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6194     }
6195 
6196     setValue(&I, DAG.getNode(Opcode, sdl,
6197                              getValue(I.getArgOperand(0)).getValueType(),
6198                              getValue(I.getArgOperand(0)), Flags));
6199     return;
6200   }
6201   case Intrinsic::lround:
6202   case Intrinsic::llround:
6203   case Intrinsic::lrint:
6204   case Intrinsic::llrint: {
6205     unsigned Opcode;
6206     switch (Intrinsic) {
6207     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6208     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6209     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6210     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6211     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6212     }
6213 
6214     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6215     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6216                              getValue(I.getArgOperand(0))));
6217     return;
6218   }
6219   case Intrinsic::minnum:
6220     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6221                              getValue(I.getArgOperand(0)).getValueType(),
6222                              getValue(I.getArgOperand(0)),
6223                              getValue(I.getArgOperand(1)), Flags));
6224     return;
6225   case Intrinsic::maxnum:
6226     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6227                              getValue(I.getArgOperand(0)).getValueType(),
6228                              getValue(I.getArgOperand(0)),
6229                              getValue(I.getArgOperand(1)), Flags));
6230     return;
6231   case Intrinsic::minimum:
6232     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6233                              getValue(I.getArgOperand(0)).getValueType(),
6234                              getValue(I.getArgOperand(0)),
6235                              getValue(I.getArgOperand(1)), Flags));
6236     return;
6237   case Intrinsic::maximum:
6238     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6239                              getValue(I.getArgOperand(0)).getValueType(),
6240                              getValue(I.getArgOperand(0)),
6241                              getValue(I.getArgOperand(1)), Flags));
6242     return;
6243   case Intrinsic::copysign:
6244     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6245                              getValue(I.getArgOperand(0)).getValueType(),
6246                              getValue(I.getArgOperand(0)),
6247                              getValue(I.getArgOperand(1)), Flags));
6248     return;
6249   case Intrinsic::fma:
6250     setValue(&I, DAG.getNode(
6251                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6252                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6253                      getValue(I.getArgOperand(2)), Flags));
6254     return;
6255 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6256   case Intrinsic::INTRINSIC:
6257 #include "llvm/IR/ConstrainedOps.def"
6258     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6259     return;
6260 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6261 #include "llvm/IR/VPIntrinsics.def"
6262     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6263     return;
6264   case Intrinsic::fmuladd: {
6265     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6266     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6267         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6268       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6269                                getValue(I.getArgOperand(0)).getValueType(),
6270                                getValue(I.getArgOperand(0)),
6271                                getValue(I.getArgOperand(1)),
6272                                getValue(I.getArgOperand(2)), Flags));
6273     } else {
6274       // TODO: Intrinsic calls should have fast-math-flags.
6275       SDValue Mul = DAG.getNode(
6276           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6277           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6278       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6279                                 getValue(I.getArgOperand(0)).getValueType(),
6280                                 Mul, getValue(I.getArgOperand(2)), Flags);
6281       setValue(&I, Add);
6282     }
6283     return;
6284   }
6285   case Intrinsic::convert_to_fp16:
6286     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6287                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6288                                          getValue(I.getArgOperand(0)),
6289                                          DAG.getTargetConstant(0, sdl,
6290                                                                MVT::i32))));
6291     return;
6292   case Intrinsic::convert_from_fp16:
6293     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6294                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6295                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6296                                          getValue(I.getArgOperand(0)))));
6297     return;
6298   case Intrinsic::fptosi_sat: {
6299     EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
6300     SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
6301     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, Type,
6302                              getValue(I.getArgOperand(0)), SatW));
6303     return;
6304   }
6305   case Intrinsic::fptoui_sat: {
6306     EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
6307     SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
6308     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, Type,
6309                              getValue(I.getArgOperand(0)), SatW));
6310     return;
6311   }
6312   case Intrinsic::set_rounding:
6313     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6314                       {getRoot(), getValue(I.getArgOperand(0))});
6315     setValue(&I, Res);
6316     DAG.setRoot(Res.getValue(0));
6317     return;
6318   case Intrinsic::pcmarker: {
6319     SDValue Tmp = getValue(I.getArgOperand(0));
6320     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6321     return;
6322   }
6323   case Intrinsic::readcyclecounter: {
6324     SDValue Op = getRoot();
6325     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6326                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6327     setValue(&I, Res);
6328     DAG.setRoot(Res.getValue(1));
6329     return;
6330   }
6331   case Intrinsic::bitreverse:
6332     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6333                              getValue(I.getArgOperand(0)).getValueType(),
6334                              getValue(I.getArgOperand(0))));
6335     return;
6336   case Intrinsic::bswap:
6337     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6338                              getValue(I.getArgOperand(0)).getValueType(),
6339                              getValue(I.getArgOperand(0))));
6340     return;
6341   case Intrinsic::cttz: {
6342     SDValue Arg = getValue(I.getArgOperand(0));
6343     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6344     EVT Ty = Arg.getValueType();
6345     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6346                              sdl, Ty, Arg));
6347     return;
6348   }
6349   case Intrinsic::ctlz: {
6350     SDValue Arg = getValue(I.getArgOperand(0));
6351     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6352     EVT Ty = Arg.getValueType();
6353     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6354                              sdl, Ty, Arg));
6355     return;
6356   }
6357   case Intrinsic::ctpop: {
6358     SDValue Arg = getValue(I.getArgOperand(0));
6359     EVT Ty = Arg.getValueType();
6360     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6361     return;
6362   }
6363   case Intrinsic::fshl:
6364   case Intrinsic::fshr: {
6365     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6366     SDValue X = getValue(I.getArgOperand(0));
6367     SDValue Y = getValue(I.getArgOperand(1));
6368     SDValue Z = getValue(I.getArgOperand(2));
6369     EVT VT = X.getValueType();
6370 
6371     if (X == Y) {
6372       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6373       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6374     } else {
6375       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6376       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6377     }
6378     return;
6379   }
6380   case Intrinsic::sadd_sat: {
6381     SDValue Op1 = getValue(I.getArgOperand(0));
6382     SDValue Op2 = getValue(I.getArgOperand(1));
6383     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6384     return;
6385   }
6386   case Intrinsic::uadd_sat: {
6387     SDValue Op1 = getValue(I.getArgOperand(0));
6388     SDValue Op2 = getValue(I.getArgOperand(1));
6389     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6390     return;
6391   }
6392   case Intrinsic::ssub_sat: {
6393     SDValue Op1 = getValue(I.getArgOperand(0));
6394     SDValue Op2 = getValue(I.getArgOperand(1));
6395     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6396     return;
6397   }
6398   case Intrinsic::usub_sat: {
6399     SDValue Op1 = getValue(I.getArgOperand(0));
6400     SDValue Op2 = getValue(I.getArgOperand(1));
6401     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6402     return;
6403   }
6404   case Intrinsic::sshl_sat: {
6405     SDValue Op1 = getValue(I.getArgOperand(0));
6406     SDValue Op2 = getValue(I.getArgOperand(1));
6407     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6408     return;
6409   }
6410   case Intrinsic::ushl_sat: {
6411     SDValue Op1 = getValue(I.getArgOperand(0));
6412     SDValue Op2 = getValue(I.getArgOperand(1));
6413     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6414     return;
6415   }
6416   case Intrinsic::smul_fix:
6417   case Intrinsic::umul_fix:
6418   case Intrinsic::smul_fix_sat:
6419   case Intrinsic::umul_fix_sat: {
6420     SDValue Op1 = getValue(I.getArgOperand(0));
6421     SDValue Op2 = getValue(I.getArgOperand(1));
6422     SDValue Op3 = getValue(I.getArgOperand(2));
6423     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6424                              Op1.getValueType(), Op1, Op2, Op3));
6425     return;
6426   }
6427   case Intrinsic::sdiv_fix:
6428   case Intrinsic::udiv_fix:
6429   case Intrinsic::sdiv_fix_sat:
6430   case Intrinsic::udiv_fix_sat: {
6431     SDValue Op1 = getValue(I.getArgOperand(0));
6432     SDValue Op2 = getValue(I.getArgOperand(1));
6433     SDValue Op3 = getValue(I.getArgOperand(2));
6434     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6435                               Op1, Op2, Op3, DAG, TLI));
6436     return;
6437   }
6438   case Intrinsic::smax: {
6439     SDValue Op1 = getValue(I.getArgOperand(0));
6440     SDValue Op2 = getValue(I.getArgOperand(1));
6441     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6442     return;
6443   }
6444   case Intrinsic::smin: {
6445     SDValue Op1 = getValue(I.getArgOperand(0));
6446     SDValue Op2 = getValue(I.getArgOperand(1));
6447     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6448     return;
6449   }
6450   case Intrinsic::umax: {
6451     SDValue Op1 = getValue(I.getArgOperand(0));
6452     SDValue Op2 = getValue(I.getArgOperand(1));
6453     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6454     return;
6455   }
6456   case Intrinsic::umin: {
6457     SDValue Op1 = getValue(I.getArgOperand(0));
6458     SDValue Op2 = getValue(I.getArgOperand(1));
6459     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6460     return;
6461   }
6462   case Intrinsic::abs: {
6463     // TODO: Preserve "int min is poison" arg in SDAG?
6464     SDValue Op1 = getValue(I.getArgOperand(0));
6465     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6466     return;
6467   }
6468   case Intrinsic::stacksave: {
6469     SDValue Op = getRoot();
6470     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6471     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6472     setValue(&I, Res);
6473     DAG.setRoot(Res.getValue(1));
6474     return;
6475   }
6476   case Intrinsic::stackrestore:
6477     Res = getValue(I.getArgOperand(0));
6478     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6479     return;
6480   case Intrinsic::get_dynamic_area_offset: {
6481     SDValue Op = getRoot();
6482     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6483     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6484     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6485     // target.
6486     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6487       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6488                          " intrinsic!");
6489     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6490                       Op);
6491     DAG.setRoot(Op);
6492     setValue(&I, Res);
6493     return;
6494   }
6495   case Intrinsic::stackguard: {
6496     MachineFunction &MF = DAG.getMachineFunction();
6497     const Module &M = *MF.getFunction().getParent();
6498     SDValue Chain = getRoot();
6499     if (TLI.useLoadStackGuardNode()) {
6500       Res = getLoadStackGuard(DAG, sdl, Chain);
6501     } else {
6502       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6503       const Value *Global = TLI.getSDagStackGuard(M);
6504       Align Align = DL->getPrefTypeAlign(Global->getType());
6505       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6506                         MachinePointerInfo(Global, 0), Align,
6507                         MachineMemOperand::MOVolatile);
6508     }
6509     if (TLI.useStackGuardXorFP())
6510       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6511     DAG.setRoot(Chain);
6512     setValue(&I, Res);
6513     return;
6514   }
6515   case Intrinsic::stackprotector: {
6516     // Emit code into the DAG to store the stack guard onto the stack.
6517     MachineFunction &MF = DAG.getMachineFunction();
6518     MachineFrameInfo &MFI = MF.getFrameInfo();
6519     SDValue Src, Chain = getRoot();
6520 
6521     if (TLI.useLoadStackGuardNode())
6522       Src = getLoadStackGuard(DAG, sdl, Chain);
6523     else
6524       Src = getValue(I.getArgOperand(0));   // The guard's value.
6525 
6526     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6527 
6528     int FI = FuncInfo.StaticAllocaMap[Slot];
6529     MFI.setStackProtectorIndex(FI);
6530     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6531 
6532     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6533 
6534     // Store the stack protector onto the stack.
6535     Res = DAG.getStore(
6536         Chain, sdl, Src, FIN,
6537         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6538         MaybeAlign(), MachineMemOperand::MOVolatile);
6539     setValue(&I, Res);
6540     DAG.setRoot(Res);
6541     return;
6542   }
6543   case Intrinsic::objectsize:
6544     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6545 
6546   case Intrinsic::is_constant:
6547     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6548 
6549   case Intrinsic::annotation:
6550   case Intrinsic::ptr_annotation:
6551   case Intrinsic::launder_invariant_group:
6552   case Intrinsic::strip_invariant_group:
6553     // Drop the intrinsic, but forward the value
6554     setValue(&I, getValue(I.getOperand(0)));
6555     return;
6556 
6557   case Intrinsic::assume:
6558   case Intrinsic::experimental_noalias_scope_decl:
6559   case Intrinsic::var_annotation:
6560   case Intrinsic::sideeffect:
6561     // Discard annotate attributes, noalias scope declarations, assumptions, and
6562     // artificial side-effects.
6563     return;
6564 
6565   case Intrinsic::codeview_annotation: {
6566     // Emit a label associated with this metadata.
6567     MachineFunction &MF = DAG.getMachineFunction();
6568     MCSymbol *Label =
6569         MF.getMMI().getContext().createTempSymbol("annotation", true);
6570     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6571     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6572     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6573     DAG.setRoot(Res);
6574     return;
6575   }
6576 
6577   case Intrinsic::init_trampoline: {
6578     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6579 
6580     SDValue Ops[6];
6581     Ops[0] = getRoot();
6582     Ops[1] = getValue(I.getArgOperand(0));
6583     Ops[2] = getValue(I.getArgOperand(1));
6584     Ops[3] = getValue(I.getArgOperand(2));
6585     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6586     Ops[5] = DAG.getSrcValue(F);
6587 
6588     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6589 
6590     DAG.setRoot(Res);
6591     return;
6592   }
6593   case Intrinsic::adjust_trampoline:
6594     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6595                              TLI.getPointerTy(DAG.getDataLayout()),
6596                              getValue(I.getArgOperand(0))));
6597     return;
6598   case Intrinsic::gcroot: {
6599     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6600            "only valid in functions with gc specified, enforced by Verifier");
6601     assert(GFI && "implied by previous");
6602     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6603     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6604 
6605     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6606     GFI->addStackRoot(FI->getIndex(), TypeMap);
6607     return;
6608   }
6609   case Intrinsic::gcread:
6610   case Intrinsic::gcwrite:
6611     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6612   case Intrinsic::flt_rounds:
6613     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6614     setValue(&I, Res);
6615     DAG.setRoot(Res.getValue(1));
6616     return;
6617 
6618   case Intrinsic::expect:
6619     // Just replace __builtin_expect(exp, c) with EXP.
6620     setValue(&I, getValue(I.getArgOperand(0)));
6621     return;
6622 
6623   case Intrinsic::ubsantrap:
6624   case Intrinsic::debugtrap:
6625   case Intrinsic::trap: {
6626     StringRef TrapFuncName =
6627         I.getAttributes()
6628             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6629             .getValueAsString();
6630     if (TrapFuncName.empty()) {
6631       switch (Intrinsic) {
6632       case Intrinsic::trap:
6633         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6634         break;
6635       case Intrinsic::debugtrap:
6636         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6637         break;
6638       case Intrinsic::ubsantrap:
6639         DAG.setRoot(DAG.getNode(
6640             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6641             DAG.getTargetConstant(
6642                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6643                 MVT::i32)));
6644         break;
6645       default: llvm_unreachable("unknown trap intrinsic");
6646       }
6647       return;
6648     }
6649     TargetLowering::ArgListTy Args;
6650     if (Intrinsic == Intrinsic::ubsantrap) {
6651       Args.push_back(TargetLoweringBase::ArgListEntry());
6652       Args[0].Val = I.getArgOperand(0);
6653       Args[0].Node = getValue(Args[0].Val);
6654       Args[0].Ty = Args[0].Val->getType();
6655     }
6656 
6657     TargetLowering::CallLoweringInfo CLI(DAG);
6658     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6659         CallingConv::C, I.getType(),
6660         DAG.getExternalSymbol(TrapFuncName.data(),
6661                               TLI.getPointerTy(DAG.getDataLayout())),
6662         std::move(Args));
6663 
6664     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6665     DAG.setRoot(Result.second);
6666     return;
6667   }
6668 
6669   case Intrinsic::uadd_with_overflow:
6670   case Intrinsic::sadd_with_overflow:
6671   case Intrinsic::usub_with_overflow:
6672   case Intrinsic::ssub_with_overflow:
6673   case Intrinsic::umul_with_overflow:
6674   case Intrinsic::smul_with_overflow: {
6675     ISD::NodeType Op;
6676     switch (Intrinsic) {
6677     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6678     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6679     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6680     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6681     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6682     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6683     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6684     }
6685     SDValue Op1 = getValue(I.getArgOperand(0));
6686     SDValue Op2 = getValue(I.getArgOperand(1));
6687 
6688     EVT ResultVT = Op1.getValueType();
6689     EVT OverflowVT = MVT::i1;
6690     if (ResultVT.isVector())
6691       OverflowVT = EVT::getVectorVT(
6692           *Context, OverflowVT, ResultVT.getVectorElementCount());
6693 
6694     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6695     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6696     return;
6697   }
6698   case Intrinsic::prefetch: {
6699     SDValue Ops[5];
6700     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6701     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6702     Ops[0] = DAG.getRoot();
6703     Ops[1] = getValue(I.getArgOperand(0));
6704     Ops[2] = getValue(I.getArgOperand(1));
6705     Ops[3] = getValue(I.getArgOperand(2));
6706     Ops[4] = getValue(I.getArgOperand(3));
6707     SDValue Result = DAG.getMemIntrinsicNode(
6708         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6709         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6710         /* align */ None, Flags);
6711 
6712     // Chain the prefetch in parallell with any pending loads, to stay out of
6713     // the way of later optimizations.
6714     PendingLoads.push_back(Result);
6715     Result = getRoot();
6716     DAG.setRoot(Result);
6717     return;
6718   }
6719   case Intrinsic::lifetime_start:
6720   case Intrinsic::lifetime_end: {
6721     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6722     // Stack coloring is not enabled in O0, discard region information.
6723     if (TM.getOptLevel() == CodeGenOpt::None)
6724       return;
6725 
6726     const int64_t ObjectSize =
6727         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6728     Value *const ObjectPtr = I.getArgOperand(1);
6729     SmallVector<const Value *, 4> Allocas;
6730     getUnderlyingObjects(ObjectPtr, Allocas);
6731 
6732     for (const Value *Alloca : Allocas) {
6733       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6734 
6735       // Could not find an Alloca.
6736       if (!LifetimeObject)
6737         continue;
6738 
6739       // First check that the Alloca is static, otherwise it won't have a
6740       // valid frame index.
6741       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6742       if (SI == FuncInfo.StaticAllocaMap.end())
6743         return;
6744 
6745       const int FrameIndex = SI->second;
6746       int64_t Offset;
6747       if (GetPointerBaseWithConstantOffset(
6748               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6749         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6750       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6751                                 Offset);
6752       DAG.setRoot(Res);
6753     }
6754     return;
6755   }
6756   case Intrinsic::pseudoprobe: {
6757     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6758     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6759     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6760     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6761     DAG.setRoot(Res);
6762     return;
6763   }
6764   case Intrinsic::invariant_start:
6765     // Discard region information.
6766     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6767     return;
6768   case Intrinsic::invariant_end:
6769     // Discard region information.
6770     return;
6771   case Intrinsic::clear_cache:
6772     /// FunctionName may be null.
6773     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6774       lowerCallToExternalSymbol(I, FunctionName);
6775     return;
6776   case Intrinsic::donothing:
6777     // ignore
6778     return;
6779   case Intrinsic::experimental_stackmap:
6780     visitStackmap(I);
6781     return;
6782   case Intrinsic::experimental_patchpoint_void:
6783   case Intrinsic::experimental_patchpoint_i64:
6784     visitPatchpoint(I);
6785     return;
6786   case Intrinsic::experimental_gc_statepoint:
6787     LowerStatepoint(cast<GCStatepointInst>(I));
6788     return;
6789   case Intrinsic::experimental_gc_result:
6790     visitGCResult(cast<GCResultInst>(I));
6791     return;
6792   case Intrinsic::experimental_gc_relocate:
6793     visitGCRelocate(cast<GCRelocateInst>(I));
6794     return;
6795   case Intrinsic::instrprof_increment:
6796     llvm_unreachable("instrprof failed to lower an increment");
6797   case Intrinsic::instrprof_value_profile:
6798     llvm_unreachable("instrprof failed to lower a value profiling call");
6799   case Intrinsic::localescape: {
6800     MachineFunction &MF = DAG.getMachineFunction();
6801     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6802 
6803     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6804     // is the same on all targets.
6805     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6806       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6807       if (isa<ConstantPointerNull>(Arg))
6808         continue; // Skip null pointers. They represent a hole in index space.
6809       AllocaInst *Slot = cast<AllocaInst>(Arg);
6810       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6811              "can only escape static allocas");
6812       int FI = FuncInfo.StaticAllocaMap[Slot];
6813       MCSymbol *FrameAllocSym =
6814           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6815               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6816       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6817               TII->get(TargetOpcode::LOCAL_ESCAPE))
6818           .addSym(FrameAllocSym)
6819           .addFrameIndex(FI);
6820     }
6821 
6822     return;
6823   }
6824 
6825   case Intrinsic::localrecover: {
6826     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6827     MachineFunction &MF = DAG.getMachineFunction();
6828 
6829     // Get the symbol that defines the frame offset.
6830     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6831     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6832     unsigned IdxVal =
6833         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6834     MCSymbol *FrameAllocSym =
6835         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6836             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6837 
6838     Value *FP = I.getArgOperand(1);
6839     SDValue FPVal = getValue(FP);
6840     EVT PtrVT = FPVal.getValueType();
6841 
6842     // Create a MCSymbol for the label to avoid any target lowering
6843     // that would make this PC relative.
6844     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6845     SDValue OffsetVal =
6846         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6847 
6848     // Add the offset to the FP.
6849     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6850     setValue(&I, Add);
6851 
6852     return;
6853   }
6854 
6855   case Intrinsic::eh_exceptionpointer:
6856   case Intrinsic::eh_exceptioncode: {
6857     // Get the exception pointer vreg, copy from it, and resize it to fit.
6858     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6859     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6860     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6861     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6862     SDValue N =
6863         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6864     if (Intrinsic == Intrinsic::eh_exceptioncode)
6865       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6866     setValue(&I, N);
6867     return;
6868   }
6869   case Intrinsic::xray_customevent: {
6870     // Here we want to make sure that the intrinsic behaves as if it has a
6871     // specific calling convention, and only for x86_64.
6872     // FIXME: Support other platforms later.
6873     const auto &Triple = DAG.getTarget().getTargetTriple();
6874     if (Triple.getArch() != Triple::x86_64)
6875       return;
6876 
6877     SDLoc DL = getCurSDLoc();
6878     SmallVector<SDValue, 8> Ops;
6879 
6880     // We want to say that we always want the arguments in registers.
6881     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6882     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6883     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6884     SDValue Chain = getRoot();
6885     Ops.push_back(LogEntryVal);
6886     Ops.push_back(StrSizeVal);
6887     Ops.push_back(Chain);
6888 
6889     // We need to enforce the calling convention for the callsite, so that
6890     // argument ordering is enforced correctly, and that register allocation can
6891     // see that some registers may be assumed clobbered and have to preserve
6892     // them across calls to the intrinsic.
6893     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6894                                            DL, NodeTys, Ops);
6895     SDValue patchableNode = SDValue(MN, 0);
6896     DAG.setRoot(patchableNode);
6897     setValue(&I, patchableNode);
6898     return;
6899   }
6900   case Intrinsic::xray_typedevent: {
6901     // Here we want to make sure that the intrinsic behaves as if it has a
6902     // specific calling convention, and only for x86_64.
6903     // FIXME: Support other platforms later.
6904     const auto &Triple = DAG.getTarget().getTargetTriple();
6905     if (Triple.getArch() != Triple::x86_64)
6906       return;
6907 
6908     SDLoc DL = getCurSDLoc();
6909     SmallVector<SDValue, 8> Ops;
6910 
6911     // We want to say that we always want the arguments in registers.
6912     // It's unclear to me how manipulating the selection DAG here forces callers
6913     // to provide arguments in registers instead of on the stack.
6914     SDValue LogTypeId = getValue(I.getArgOperand(0));
6915     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6916     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6917     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6918     SDValue Chain = getRoot();
6919     Ops.push_back(LogTypeId);
6920     Ops.push_back(LogEntryVal);
6921     Ops.push_back(StrSizeVal);
6922     Ops.push_back(Chain);
6923 
6924     // We need to enforce the calling convention for the callsite, so that
6925     // argument ordering is enforced correctly, and that register allocation can
6926     // see that some registers may be assumed clobbered and have to preserve
6927     // them across calls to the intrinsic.
6928     MachineSDNode *MN = DAG.getMachineNode(
6929         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6930     SDValue patchableNode = SDValue(MN, 0);
6931     DAG.setRoot(patchableNode);
6932     setValue(&I, patchableNode);
6933     return;
6934   }
6935   case Intrinsic::experimental_deoptimize:
6936     LowerDeoptimizeCall(&I);
6937     return;
6938 
6939   case Intrinsic::vector_reduce_fadd:
6940   case Intrinsic::vector_reduce_fmul:
6941   case Intrinsic::vector_reduce_add:
6942   case Intrinsic::vector_reduce_mul:
6943   case Intrinsic::vector_reduce_and:
6944   case Intrinsic::vector_reduce_or:
6945   case Intrinsic::vector_reduce_xor:
6946   case Intrinsic::vector_reduce_smax:
6947   case Intrinsic::vector_reduce_smin:
6948   case Intrinsic::vector_reduce_umax:
6949   case Intrinsic::vector_reduce_umin:
6950   case Intrinsic::vector_reduce_fmax:
6951   case Intrinsic::vector_reduce_fmin:
6952     visitVectorReduce(I, Intrinsic);
6953     return;
6954 
6955   case Intrinsic::icall_branch_funnel: {
6956     SmallVector<SDValue, 16> Ops;
6957     Ops.push_back(getValue(I.getArgOperand(0)));
6958 
6959     int64_t Offset;
6960     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6961         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6962     if (!Base)
6963       report_fatal_error(
6964           "llvm.icall.branch.funnel operand must be a GlobalValue");
6965     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6966 
6967     struct BranchFunnelTarget {
6968       int64_t Offset;
6969       SDValue Target;
6970     };
6971     SmallVector<BranchFunnelTarget, 8> Targets;
6972 
6973     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6974       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6975           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6976       if (ElemBase != Base)
6977         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6978                            "to the same GlobalValue");
6979 
6980       SDValue Val = getValue(I.getArgOperand(Op + 1));
6981       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6982       if (!GA)
6983         report_fatal_error(
6984             "llvm.icall.branch.funnel operand must be a GlobalValue");
6985       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6986                                      GA->getGlobal(), getCurSDLoc(),
6987                                      Val.getValueType(), GA->getOffset())});
6988     }
6989     llvm::sort(Targets,
6990                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6991                  return T1.Offset < T2.Offset;
6992                });
6993 
6994     for (auto &T : Targets) {
6995       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6996       Ops.push_back(T.Target);
6997     }
6998 
6999     Ops.push_back(DAG.getRoot()); // Chain
7000     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
7001                                  getCurSDLoc(), MVT::Other, Ops),
7002               0);
7003     DAG.setRoot(N);
7004     setValue(&I, N);
7005     HasTailCall = true;
7006     return;
7007   }
7008 
7009   case Intrinsic::wasm_landingpad_index:
7010     // Information this intrinsic contained has been transferred to
7011     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7012     // delete it now.
7013     return;
7014 
7015   case Intrinsic::aarch64_settag:
7016   case Intrinsic::aarch64_settag_zero: {
7017     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7018     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7019     SDValue Val = TSI.EmitTargetCodeForSetTag(
7020         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
7021         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7022         ZeroMemory);
7023     DAG.setRoot(Val);
7024     setValue(&I, Val);
7025     return;
7026   }
7027   case Intrinsic::ptrmask: {
7028     SDValue Ptr = getValue(I.getOperand(0));
7029     SDValue Const = getValue(I.getOperand(1));
7030 
7031     EVT PtrVT = Ptr.getValueType();
7032     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
7033                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
7034     return;
7035   }
7036   case Intrinsic::get_active_lane_mask: {
7037     auto DL = getCurSDLoc();
7038     SDValue Index = getValue(I.getOperand(0));
7039     SDValue TripCount = getValue(I.getOperand(1));
7040     Type *ElementTy = I.getOperand(0)->getType();
7041     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7042     unsigned VecWidth = VT.getVectorNumElements();
7043 
7044     SmallVector<SDValue, 16> OpsTripCount;
7045     SmallVector<SDValue, 16> OpsIndex;
7046     SmallVector<SDValue, 16> OpsStepConstants;
7047     for (unsigned i = 0; i < VecWidth; i++) {
7048       OpsTripCount.push_back(TripCount);
7049       OpsIndex.push_back(Index);
7050       OpsStepConstants.push_back(
7051           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
7052     }
7053 
7054     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
7055 
7056     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
7057     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
7058     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
7059     SDValue VectorInduction = DAG.getNode(
7060        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
7061     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
7062     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
7063                                  VectorTripCount, ISD::CondCode::SETULT);
7064     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
7065                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
7066                              SetCC));
7067     return;
7068   }
7069   case Intrinsic::experimental_vector_insert: {
7070     auto DL = getCurSDLoc();
7071 
7072     SDValue Vec = getValue(I.getOperand(0));
7073     SDValue SubVec = getValue(I.getOperand(1));
7074     SDValue Index = getValue(I.getOperand(2));
7075 
7076     // The intrinsic's index type is i64, but the SDNode requires an index type
7077     // suitable for the target. Convert the index as required.
7078     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7079     if (Index.getValueType() != VectorIdxTy)
7080       Index = DAG.getVectorIdxConstant(
7081           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7082 
7083     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7084     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
7085                              Index));
7086     return;
7087   }
7088   case Intrinsic::experimental_vector_extract: {
7089     auto DL = getCurSDLoc();
7090 
7091     SDValue Vec = getValue(I.getOperand(0));
7092     SDValue Index = getValue(I.getOperand(1));
7093     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7094 
7095     // The intrinsic's index type is i64, but the SDNode requires an index type
7096     // suitable for the target. Convert the index as required.
7097     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7098     if (Index.getValueType() != VectorIdxTy)
7099       Index = DAG.getVectorIdxConstant(
7100           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7101 
7102     setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
7103     return;
7104   }
7105   case Intrinsic::experimental_vector_reverse:
7106     visitVectorReverse(I);
7107     return;
7108   case Intrinsic::experimental_vector_splice:
7109     visitVectorSplice(I);
7110     return;
7111   }
7112 }
7113 
7114 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7115     const ConstrainedFPIntrinsic &FPI) {
7116   SDLoc sdl = getCurSDLoc();
7117 
7118   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7119   SmallVector<EVT, 4> ValueVTs;
7120   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7121   ValueVTs.push_back(MVT::Other); // Out chain
7122 
7123   // We do not need to serialize constrained FP intrinsics against
7124   // each other or against (nonvolatile) loads, so they can be
7125   // chained like loads.
7126   SDValue Chain = DAG.getRoot();
7127   SmallVector<SDValue, 4> Opers;
7128   Opers.push_back(Chain);
7129   if (FPI.isUnaryOp()) {
7130     Opers.push_back(getValue(FPI.getArgOperand(0)));
7131   } else if (FPI.isTernaryOp()) {
7132     Opers.push_back(getValue(FPI.getArgOperand(0)));
7133     Opers.push_back(getValue(FPI.getArgOperand(1)));
7134     Opers.push_back(getValue(FPI.getArgOperand(2)));
7135   } else {
7136     Opers.push_back(getValue(FPI.getArgOperand(0)));
7137     Opers.push_back(getValue(FPI.getArgOperand(1)));
7138   }
7139 
7140   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7141     assert(Result.getNode()->getNumValues() == 2);
7142 
7143     // Push node to the appropriate list so that future instructions can be
7144     // chained up correctly.
7145     SDValue OutChain = Result.getValue(1);
7146     switch (EB) {
7147     case fp::ExceptionBehavior::ebIgnore:
7148       // The only reason why ebIgnore nodes still need to be chained is that
7149       // they might depend on the current rounding mode, and therefore must
7150       // not be moved across instruction that may change that mode.
7151       LLVM_FALLTHROUGH;
7152     case fp::ExceptionBehavior::ebMayTrap:
7153       // These must not be moved across calls or instructions that may change
7154       // floating-point exception masks.
7155       PendingConstrainedFP.push_back(OutChain);
7156       break;
7157     case fp::ExceptionBehavior::ebStrict:
7158       // These must not be moved across calls or instructions that may change
7159       // floating-point exception masks or read floating-point exception flags.
7160       // In addition, they cannot be optimized out even if unused.
7161       PendingConstrainedFPStrict.push_back(OutChain);
7162       break;
7163     }
7164   };
7165 
7166   SDVTList VTs = DAG.getVTList(ValueVTs);
7167   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7168 
7169   SDNodeFlags Flags;
7170   if (EB == fp::ExceptionBehavior::ebIgnore)
7171     Flags.setNoFPExcept(true);
7172 
7173   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7174     Flags.copyFMF(*FPOp);
7175 
7176   unsigned Opcode;
7177   switch (FPI.getIntrinsicID()) {
7178   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7179 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7180   case Intrinsic::INTRINSIC:                                                   \
7181     Opcode = ISD::STRICT_##DAGN;                                               \
7182     break;
7183 #include "llvm/IR/ConstrainedOps.def"
7184   case Intrinsic::experimental_constrained_fmuladd: {
7185     Opcode = ISD::STRICT_FMA;
7186     // Break fmuladd into fmul and fadd.
7187     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7188         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7189                                         ValueVTs[0])) {
7190       Opers.pop_back();
7191       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7192       pushOutChain(Mul, EB);
7193       Opcode = ISD::STRICT_FADD;
7194       Opers.clear();
7195       Opers.push_back(Mul.getValue(1));
7196       Opers.push_back(Mul.getValue(0));
7197       Opers.push_back(getValue(FPI.getArgOperand(2)));
7198     }
7199     break;
7200   }
7201   }
7202 
7203   // A few strict DAG nodes carry additional operands that are not
7204   // set up by the default code above.
7205   switch (Opcode) {
7206   default: break;
7207   case ISD::STRICT_FP_ROUND:
7208     Opers.push_back(
7209         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7210     break;
7211   case ISD::STRICT_FSETCC:
7212   case ISD::STRICT_FSETCCS: {
7213     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7214     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7215     if (TM.Options.NoNaNsFPMath)
7216       Condition = getFCmpCodeWithoutNaN(Condition);
7217     Opers.push_back(DAG.getCondCode(Condition));
7218     break;
7219   }
7220   }
7221 
7222   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7223   pushOutChain(Result, EB);
7224 
7225   SDValue FPResult = Result.getValue(0);
7226   setValue(&FPI, FPResult);
7227 }
7228 
7229 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7230   Optional<unsigned> ResOPC;
7231   switch (VPIntrin.getIntrinsicID()) {
7232 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
7233 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
7234 #define END_REGISTER_VP_INTRINSIC(...) break;
7235 #include "llvm/IR/VPIntrinsics.def"
7236   }
7237 
7238   if (!ResOPC.hasValue())
7239     llvm_unreachable(
7240         "Inconsistency: no SDNode available for this VPIntrinsic!");
7241 
7242   return ResOPC.getValue();
7243 }
7244 
7245 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7246     const VPIntrinsic &VPIntrin) {
7247   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7248 
7249   SmallVector<EVT, 4> ValueVTs;
7250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7251   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7252   SDVTList VTs = DAG.getVTList(ValueVTs);
7253 
7254   // Request operands.
7255   SmallVector<SDValue, 7> OpValues;
7256   for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i)
7257     OpValues.push_back(getValue(VPIntrin.getArgOperand(i)));
7258 
7259   SDLoc DL = getCurSDLoc();
7260   SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7261   setValue(&VPIntrin, Result);
7262 }
7263 
7264 std::pair<SDValue, SDValue>
7265 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7266                                     const BasicBlock *EHPadBB) {
7267   MachineFunction &MF = DAG.getMachineFunction();
7268   MachineModuleInfo &MMI = MF.getMMI();
7269   MCSymbol *BeginLabel = nullptr;
7270 
7271   if (EHPadBB) {
7272     // Insert a label before the invoke call to mark the try range.  This can be
7273     // used to detect deletion of the invoke via the MachineModuleInfo.
7274     BeginLabel = MMI.getContext().createTempSymbol();
7275 
7276     // For SjLj, keep track of which landing pads go with which invokes
7277     // so as to maintain the ordering of pads in the LSDA.
7278     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7279     if (CallSiteIndex) {
7280       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7281       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7282 
7283       // Now that the call site is handled, stop tracking it.
7284       MMI.setCurrentCallSite(0);
7285     }
7286 
7287     // Both PendingLoads and PendingExports must be flushed here;
7288     // this call might not return.
7289     (void)getRoot();
7290     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7291 
7292     CLI.setChain(getRoot());
7293   }
7294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7295   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7296 
7297   assert((CLI.IsTailCall || Result.second.getNode()) &&
7298          "Non-null chain expected with non-tail call!");
7299   assert((Result.second.getNode() || !Result.first.getNode()) &&
7300          "Null value expected with tail call!");
7301 
7302   if (!Result.second.getNode()) {
7303     // As a special case, a null chain means that a tail call has been emitted
7304     // and the DAG root is already updated.
7305     HasTailCall = true;
7306 
7307     // Since there's no actual continuation from this block, nothing can be
7308     // relying on us setting vregs for them.
7309     PendingExports.clear();
7310   } else {
7311     DAG.setRoot(Result.second);
7312   }
7313 
7314   if (EHPadBB) {
7315     // Insert a label at the end of the invoke call to mark the try range.  This
7316     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7317     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7318     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7319 
7320     // Inform MachineModuleInfo of range.
7321     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7322     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7323     // actually use outlined funclets and their LSDA info style.
7324     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7325       assert(CLI.CB);
7326       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7327       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7328     } else if (!isScopedEHPersonality(Pers)) {
7329       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7330     }
7331   }
7332 
7333   return Result;
7334 }
7335 
7336 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7337                                       bool isTailCall,
7338                                       const BasicBlock *EHPadBB) {
7339   auto &DL = DAG.getDataLayout();
7340   FunctionType *FTy = CB.getFunctionType();
7341   Type *RetTy = CB.getType();
7342 
7343   TargetLowering::ArgListTy Args;
7344   Args.reserve(CB.arg_size());
7345 
7346   const Value *SwiftErrorVal = nullptr;
7347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7348 
7349   if (isTailCall) {
7350     // Avoid emitting tail calls in functions with the disable-tail-calls
7351     // attribute.
7352     auto *Caller = CB.getParent()->getParent();
7353     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7354         "true")
7355       isTailCall = false;
7356 
7357     // We can't tail call inside a function with a swifterror argument. Lowering
7358     // does not support this yet. It would have to move into the swifterror
7359     // register before the call.
7360     if (TLI.supportSwiftError() &&
7361         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7362       isTailCall = false;
7363   }
7364 
7365   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7366     TargetLowering::ArgListEntry Entry;
7367     const Value *V = *I;
7368 
7369     // Skip empty types
7370     if (V->getType()->isEmptyTy())
7371       continue;
7372 
7373     SDValue ArgNode = getValue(V);
7374     Entry.Node = ArgNode; Entry.Ty = V->getType();
7375 
7376     Entry.setAttributes(&CB, I - CB.arg_begin());
7377 
7378     // Use swifterror virtual register as input to the call.
7379     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7380       SwiftErrorVal = V;
7381       // We find the virtual register for the actual swifterror argument.
7382       // Instead of using the Value, we use the virtual register instead.
7383       Entry.Node =
7384           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7385                           EVT(TLI.getPointerTy(DL)));
7386     }
7387 
7388     Args.push_back(Entry);
7389 
7390     // If we have an explicit sret argument that is an Instruction, (i.e., it
7391     // might point to function-local memory), we can't meaningfully tail-call.
7392     if (Entry.IsSRet && isa<Instruction>(V))
7393       isTailCall = false;
7394   }
7395 
7396   // If call site has a cfguardtarget operand bundle, create and add an
7397   // additional ArgListEntry.
7398   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7399     TargetLowering::ArgListEntry Entry;
7400     Value *V = Bundle->Inputs[0];
7401     SDValue ArgNode = getValue(V);
7402     Entry.Node = ArgNode;
7403     Entry.Ty = V->getType();
7404     Entry.IsCFGuardTarget = true;
7405     Args.push_back(Entry);
7406   }
7407 
7408   // Check if target-independent constraints permit a tail call here.
7409   // Target-dependent constraints are checked within TLI->LowerCallTo.
7410   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7411     isTailCall = false;
7412 
7413   // Disable tail calls if there is an swifterror argument. Targets have not
7414   // been updated to support tail calls.
7415   if (TLI.supportSwiftError() && SwiftErrorVal)
7416     isTailCall = false;
7417 
7418   TargetLowering::CallLoweringInfo CLI(DAG);
7419   CLI.setDebugLoc(getCurSDLoc())
7420       .setChain(getRoot())
7421       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7422       .setTailCall(isTailCall)
7423       .setConvergent(CB.isConvergent())
7424       .setIsPreallocated(
7425           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7426   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7427 
7428   if (Result.first.getNode()) {
7429     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7430     setValue(&CB, Result.first);
7431   }
7432 
7433   // The last element of CLI.InVals has the SDValue for swifterror return.
7434   // Here we copy it to a virtual register and update SwiftErrorMap for
7435   // book-keeping.
7436   if (SwiftErrorVal && TLI.supportSwiftError()) {
7437     // Get the last element of InVals.
7438     SDValue Src = CLI.InVals.back();
7439     Register VReg =
7440         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7441     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7442     DAG.setRoot(CopyNode);
7443   }
7444 }
7445 
7446 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7447                              SelectionDAGBuilder &Builder) {
7448   // Check to see if this load can be trivially constant folded, e.g. if the
7449   // input is from a string literal.
7450   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7451     // Cast pointer to the type we really want to load.
7452     Type *LoadTy =
7453         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7454     if (LoadVT.isVector())
7455       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7456 
7457     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7458                                          PointerType::getUnqual(LoadTy));
7459 
7460     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7461             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7462       return Builder.getValue(LoadCst);
7463   }
7464 
7465   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7466   // still constant memory, the input chain can be the entry node.
7467   SDValue Root;
7468   bool ConstantMemory = false;
7469 
7470   // Do not serialize (non-volatile) loads of constant memory with anything.
7471   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7472     Root = Builder.DAG.getEntryNode();
7473     ConstantMemory = true;
7474   } else {
7475     // Do not serialize non-volatile loads against each other.
7476     Root = Builder.DAG.getRoot();
7477   }
7478 
7479   SDValue Ptr = Builder.getValue(PtrVal);
7480   SDValue LoadVal =
7481       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7482                           MachinePointerInfo(PtrVal), Align(1));
7483 
7484   if (!ConstantMemory)
7485     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7486   return LoadVal;
7487 }
7488 
7489 /// Record the value for an instruction that produces an integer result,
7490 /// converting the type where necessary.
7491 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7492                                                   SDValue Value,
7493                                                   bool IsSigned) {
7494   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7495                                                     I.getType(), true);
7496   if (IsSigned)
7497     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7498   else
7499     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7500   setValue(&I, Value);
7501 }
7502 
7503 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7504 /// true and lower it. Otherwise return false, and it will be lowered like a
7505 /// normal call.
7506 /// The caller already checked that \p I calls the appropriate LibFunc with a
7507 /// correct prototype.
7508 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7509   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7510   const Value *Size = I.getArgOperand(2);
7511   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7512   if (CSize && CSize->getZExtValue() == 0) {
7513     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7514                                                           I.getType(), true);
7515     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7516     return true;
7517   }
7518 
7519   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7520   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7521       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7522       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7523   if (Res.first.getNode()) {
7524     processIntegerCallValue(I, Res.first, true);
7525     PendingLoads.push_back(Res.second);
7526     return true;
7527   }
7528 
7529   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7530   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7531   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7532     return false;
7533 
7534   // If the target has a fast compare for the given size, it will return a
7535   // preferred load type for that size. Require that the load VT is legal and
7536   // that the target supports unaligned loads of that type. Otherwise, return
7537   // INVALID.
7538   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7539     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7540     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7541     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7542       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7543       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7544       // TODO: Check alignment of src and dest ptrs.
7545       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7546       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7547       if (!TLI.isTypeLegal(LVT) ||
7548           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7549           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7550         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7551     }
7552 
7553     return LVT;
7554   };
7555 
7556   // This turns into unaligned loads. We only do this if the target natively
7557   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7558   // we'll only produce a small number of byte loads.
7559   MVT LoadVT;
7560   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7561   switch (NumBitsToCompare) {
7562   default:
7563     return false;
7564   case 16:
7565     LoadVT = MVT::i16;
7566     break;
7567   case 32:
7568     LoadVT = MVT::i32;
7569     break;
7570   case 64:
7571   case 128:
7572   case 256:
7573     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7574     break;
7575   }
7576 
7577   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7578     return false;
7579 
7580   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7581   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7582 
7583   // Bitcast to a wide integer type if the loads are vectors.
7584   if (LoadVT.isVector()) {
7585     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7586     LoadL = DAG.getBitcast(CmpVT, LoadL);
7587     LoadR = DAG.getBitcast(CmpVT, LoadR);
7588   }
7589 
7590   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7591   processIntegerCallValue(I, Cmp, false);
7592   return true;
7593 }
7594 
7595 /// See if we can lower a memchr call into an optimized form. If so, return
7596 /// true and lower it. Otherwise return false, and it will be lowered like a
7597 /// normal call.
7598 /// The caller already checked that \p I calls the appropriate LibFunc with a
7599 /// correct prototype.
7600 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7601   const Value *Src = I.getArgOperand(0);
7602   const Value *Char = I.getArgOperand(1);
7603   const Value *Length = I.getArgOperand(2);
7604 
7605   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7606   std::pair<SDValue, SDValue> Res =
7607     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7608                                 getValue(Src), getValue(Char), getValue(Length),
7609                                 MachinePointerInfo(Src));
7610   if (Res.first.getNode()) {
7611     setValue(&I, Res.first);
7612     PendingLoads.push_back(Res.second);
7613     return true;
7614   }
7615 
7616   return false;
7617 }
7618 
7619 /// See if we can lower a mempcpy call into an optimized form. If so, return
7620 /// true and lower it. Otherwise return false, and it will be lowered like a
7621 /// normal call.
7622 /// The caller already checked that \p I calls the appropriate LibFunc with a
7623 /// correct prototype.
7624 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7625   SDValue Dst = getValue(I.getArgOperand(0));
7626   SDValue Src = getValue(I.getArgOperand(1));
7627   SDValue Size = getValue(I.getArgOperand(2));
7628 
7629   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7630   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7631   // DAG::getMemcpy needs Alignment to be defined.
7632   Align Alignment = std::min(DstAlign, SrcAlign);
7633 
7634   bool isVol = false;
7635   SDLoc sdl = getCurSDLoc();
7636 
7637   // In the mempcpy context we need to pass in a false value for isTailCall
7638   // because the return pointer needs to be adjusted by the size of
7639   // the copied memory.
7640   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7641   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7642                              /*isTailCall=*/false,
7643                              MachinePointerInfo(I.getArgOperand(0)),
7644                              MachinePointerInfo(I.getArgOperand(1)));
7645   assert(MC.getNode() != nullptr &&
7646          "** memcpy should not be lowered as TailCall in mempcpy context **");
7647   DAG.setRoot(MC);
7648 
7649   // Check if Size needs to be truncated or extended.
7650   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7651 
7652   // Adjust return pointer to point just past the last dst byte.
7653   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7654                                     Dst, Size);
7655   setValue(&I, DstPlusSize);
7656   return true;
7657 }
7658 
7659 /// See if we can lower a strcpy call into an optimized form.  If so, return
7660 /// true and lower it, otherwise return false and it will be lowered like a
7661 /// normal call.
7662 /// The caller already checked that \p I calls the appropriate LibFunc with a
7663 /// correct prototype.
7664 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7665   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7666 
7667   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7668   std::pair<SDValue, SDValue> Res =
7669     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7670                                 getValue(Arg0), getValue(Arg1),
7671                                 MachinePointerInfo(Arg0),
7672                                 MachinePointerInfo(Arg1), isStpcpy);
7673   if (Res.first.getNode()) {
7674     setValue(&I, Res.first);
7675     DAG.setRoot(Res.second);
7676     return true;
7677   }
7678 
7679   return false;
7680 }
7681 
7682 /// See if we can lower a strcmp call into an optimized form.  If so, return
7683 /// true and lower it, otherwise return false and it will be lowered like a
7684 /// normal call.
7685 /// The caller already checked that \p I calls the appropriate LibFunc with a
7686 /// correct prototype.
7687 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7688   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7689 
7690   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7691   std::pair<SDValue, SDValue> Res =
7692     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7693                                 getValue(Arg0), getValue(Arg1),
7694                                 MachinePointerInfo(Arg0),
7695                                 MachinePointerInfo(Arg1));
7696   if (Res.first.getNode()) {
7697     processIntegerCallValue(I, Res.first, true);
7698     PendingLoads.push_back(Res.second);
7699     return true;
7700   }
7701 
7702   return false;
7703 }
7704 
7705 /// See if we can lower a strlen call into an optimized form.  If so, return
7706 /// true and lower it, otherwise return false and it will be lowered like a
7707 /// normal call.
7708 /// The caller already checked that \p I calls the appropriate LibFunc with a
7709 /// correct prototype.
7710 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7711   const Value *Arg0 = I.getArgOperand(0);
7712 
7713   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7714   std::pair<SDValue, SDValue> Res =
7715     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7716                                 getValue(Arg0), MachinePointerInfo(Arg0));
7717   if (Res.first.getNode()) {
7718     processIntegerCallValue(I, Res.first, false);
7719     PendingLoads.push_back(Res.second);
7720     return true;
7721   }
7722 
7723   return false;
7724 }
7725 
7726 /// See if we can lower a strnlen call into an optimized form.  If so, return
7727 /// true and lower it, otherwise return false and it will be lowered like a
7728 /// normal call.
7729 /// The caller already checked that \p I calls the appropriate LibFunc with a
7730 /// correct prototype.
7731 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7732   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7733 
7734   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7735   std::pair<SDValue, SDValue> Res =
7736     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7737                                  getValue(Arg0), getValue(Arg1),
7738                                  MachinePointerInfo(Arg0));
7739   if (Res.first.getNode()) {
7740     processIntegerCallValue(I, Res.first, false);
7741     PendingLoads.push_back(Res.second);
7742     return true;
7743   }
7744 
7745   return false;
7746 }
7747 
7748 /// See if we can lower a unary floating-point operation into an SDNode with
7749 /// the specified Opcode.  If so, return true and lower it, otherwise return
7750 /// false and it will be lowered like a normal call.
7751 /// The caller already checked that \p I calls the appropriate LibFunc with a
7752 /// correct prototype.
7753 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7754                                               unsigned Opcode) {
7755   // We already checked this call's prototype; verify it doesn't modify errno.
7756   if (!I.onlyReadsMemory())
7757     return false;
7758 
7759   SDNodeFlags Flags;
7760   Flags.copyFMF(cast<FPMathOperator>(I));
7761 
7762   SDValue Tmp = getValue(I.getArgOperand(0));
7763   setValue(&I,
7764            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7765   return true;
7766 }
7767 
7768 /// See if we can lower a binary floating-point operation into an SDNode with
7769 /// the specified Opcode. If so, return true and lower it. Otherwise return
7770 /// false, and it will be lowered like a normal call.
7771 /// The caller already checked that \p I calls the appropriate LibFunc with a
7772 /// correct prototype.
7773 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7774                                                unsigned Opcode) {
7775   // We already checked this call's prototype; verify it doesn't modify errno.
7776   if (!I.onlyReadsMemory())
7777     return false;
7778 
7779   SDNodeFlags Flags;
7780   Flags.copyFMF(cast<FPMathOperator>(I));
7781 
7782   SDValue Tmp0 = getValue(I.getArgOperand(0));
7783   SDValue Tmp1 = getValue(I.getArgOperand(1));
7784   EVT VT = Tmp0.getValueType();
7785   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
7786   return true;
7787 }
7788 
7789 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7790   // Handle inline assembly differently.
7791   if (I.isInlineAsm()) {
7792     visitInlineAsm(I);
7793     return;
7794   }
7795 
7796   if (Function *F = I.getCalledFunction()) {
7797     if (F->isDeclaration()) {
7798       // Is this an LLVM intrinsic or a target-specific intrinsic?
7799       unsigned IID = F->getIntrinsicID();
7800       if (!IID)
7801         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7802           IID = II->getIntrinsicID(F);
7803 
7804       if (IID) {
7805         visitIntrinsicCall(I, IID);
7806         return;
7807       }
7808     }
7809 
7810     // Check for well-known libc/libm calls.  If the function is internal, it
7811     // can't be a library call.  Don't do the check if marked as nobuiltin for
7812     // some reason or the call site requires strict floating point semantics.
7813     LibFunc Func;
7814     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7815         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7816         LibInfo->hasOptimizedCodeGen(Func)) {
7817       switch (Func) {
7818       default: break;
7819       case LibFunc_bcmp:
7820         if (visitMemCmpBCmpCall(I))
7821           return;
7822         break;
7823       case LibFunc_copysign:
7824       case LibFunc_copysignf:
7825       case LibFunc_copysignl:
7826         // We already checked this call's prototype; verify it doesn't modify
7827         // errno.
7828         if (I.onlyReadsMemory()) {
7829           SDValue LHS = getValue(I.getArgOperand(0));
7830           SDValue RHS = getValue(I.getArgOperand(1));
7831           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7832                                    LHS.getValueType(), LHS, RHS));
7833           return;
7834         }
7835         break;
7836       case LibFunc_fabs:
7837       case LibFunc_fabsf:
7838       case LibFunc_fabsl:
7839         if (visitUnaryFloatCall(I, ISD::FABS))
7840           return;
7841         break;
7842       case LibFunc_fmin:
7843       case LibFunc_fminf:
7844       case LibFunc_fminl:
7845         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7846           return;
7847         break;
7848       case LibFunc_fmax:
7849       case LibFunc_fmaxf:
7850       case LibFunc_fmaxl:
7851         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7852           return;
7853         break;
7854       case LibFunc_sin:
7855       case LibFunc_sinf:
7856       case LibFunc_sinl:
7857         if (visitUnaryFloatCall(I, ISD::FSIN))
7858           return;
7859         break;
7860       case LibFunc_cos:
7861       case LibFunc_cosf:
7862       case LibFunc_cosl:
7863         if (visitUnaryFloatCall(I, ISD::FCOS))
7864           return;
7865         break;
7866       case LibFunc_sqrt:
7867       case LibFunc_sqrtf:
7868       case LibFunc_sqrtl:
7869       case LibFunc_sqrt_finite:
7870       case LibFunc_sqrtf_finite:
7871       case LibFunc_sqrtl_finite:
7872         if (visitUnaryFloatCall(I, ISD::FSQRT))
7873           return;
7874         break;
7875       case LibFunc_floor:
7876       case LibFunc_floorf:
7877       case LibFunc_floorl:
7878         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7879           return;
7880         break;
7881       case LibFunc_nearbyint:
7882       case LibFunc_nearbyintf:
7883       case LibFunc_nearbyintl:
7884         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7885           return;
7886         break;
7887       case LibFunc_ceil:
7888       case LibFunc_ceilf:
7889       case LibFunc_ceill:
7890         if (visitUnaryFloatCall(I, ISD::FCEIL))
7891           return;
7892         break;
7893       case LibFunc_rint:
7894       case LibFunc_rintf:
7895       case LibFunc_rintl:
7896         if (visitUnaryFloatCall(I, ISD::FRINT))
7897           return;
7898         break;
7899       case LibFunc_round:
7900       case LibFunc_roundf:
7901       case LibFunc_roundl:
7902         if (visitUnaryFloatCall(I, ISD::FROUND))
7903           return;
7904         break;
7905       case LibFunc_trunc:
7906       case LibFunc_truncf:
7907       case LibFunc_truncl:
7908         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7909           return;
7910         break;
7911       case LibFunc_log2:
7912       case LibFunc_log2f:
7913       case LibFunc_log2l:
7914         if (visitUnaryFloatCall(I, ISD::FLOG2))
7915           return;
7916         break;
7917       case LibFunc_exp2:
7918       case LibFunc_exp2f:
7919       case LibFunc_exp2l:
7920         if (visitUnaryFloatCall(I, ISD::FEXP2))
7921           return;
7922         break;
7923       case LibFunc_memcmp:
7924         if (visitMemCmpBCmpCall(I))
7925           return;
7926         break;
7927       case LibFunc_mempcpy:
7928         if (visitMemPCpyCall(I))
7929           return;
7930         break;
7931       case LibFunc_memchr:
7932         if (visitMemChrCall(I))
7933           return;
7934         break;
7935       case LibFunc_strcpy:
7936         if (visitStrCpyCall(I, false))
7937           return;
7938         break;
7939       case LibFunc_stpcpy:
7940         if (visitStrCpyCall(I, true))
7941           return;
7942         break;
7943       case LibFunc_strcmp:
7944         if (visitStrCmpCall(I))
7945           return;
7946         break;
7947       case LibFunc_strlen:
7948         if (visitStrLenCall(I))
7949           return;
7950         break;
7951       case LibFunc_strnlen:
7952         if (visitStrNLenCall(I))
7953           return;
7954         break;
7955       }
7956     }
7957   }
7958 
7959   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7960   // have to do anything here to lower funclet bundles.
7961   // CFGuardTarget bundles are lowered in LowerCallTo.
7962   assert(!I.hasOperandBundlesOtherThan(
7963              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7964               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
7965               LLVMContext::OB_clang_arc_attachedcall}) &&
7966          "Cannot lower calls with arbitrary operand bundles!");
7967 
7968   SDValue Callee = getValue(I.getCalledOperand());
7969 
7970   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7971     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7972   else
7973     // Check if we can potentially perform a tail call. More detailed checking
7974     // is be done within LowerCallTo, after more information about the call is
7975     // known.
7976     LowerCallTo(I, Callee, I.isTailCall());
7977 }
7978 
7979 namespace {
7980 
7981 /// AsmOperandInfo - This contains information for each constraint that we are
7982 /// lowering.
7983 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7984 public:
7985   /// CallOperand - If this is the result output operand or a clobber
7986   /// this is null, otherwise it is the incoming operand to the CallInst.
7987   /// This gets modified as the asm is processed.
7988   SDValue CallOperand;
7989 
7990   /// AssignedRegs - If this is a register or register class operand, this
7991   /// contains the set of register corresponding to the operand.
7992   RegsForValue AssignedRegs;
7993 
7994   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7995     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7996   }
7997 
7998   /// Whether or not this operand accesses memory
7999   bool hasMemory(const TargetLowering &TLI) const {
8000     // Indirect operand accesses access memory.
8001     if (isIndirect)
8002       return true;
8003 
8004     for (const auto &Code : Codes)
8005       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8006         return true;
8007 
8008     return false;
8009   }
8010 
8011   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8012   /// corresponds to.  If there is no Value* for this operand, it returns
8013   /// MVT::Other.
8014   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8015                            const DataLayout &DL) const {
8016     if (!CallOperandVal) return MVT::Other;
8017 
8018     if (isa<BasicBlock>(CallOperandVal))
8019       return TLI.getProgramPointerTy(DL);
8020 
8021     llvm::Type *OpTy = CallOperandVal->getType();
8022 
8023     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8024     // If this is an indirect operand, the operand is a pointer to the
8025     // accessed type.
8026     if (isIndirect) {
8027       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
8028       if (!PtrTy)
8029         report_fatal_error("Indirect operand for inline asm not a pointer!");
8030       OpTy = PtrTy->getElementType();
8031     }
8032 
8033     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8034     if (StructType *STy = dyn_cast<StructType>(OpTy))
8035       if (STy->getNumElements() == 1)
8036         OpTy = STy->getElementType(0);
8037 
8038     // If OpTy is not a single value, it may be a struct/union that we
8039     // can tile with integers.
8040     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8041       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8042       switch (BitSize) {
8043       default: break;
8044       case 1:
8045       case 8:
8046       case 16:
8047       case 32:
8048       case 64:
8049       case 128:
8050         OpTy = IntegerType::get(Context, BitSize);
8051         break;
8052       }
8053     }
8054 
8055     return TLI.getValueType(DL, OpTy, true);
8056   }
8057 };
8058 
8059 
8060 } // end anonymous namespace
8061 
8062 /// Make sure that the output operand \p OpInfo and its corresponding input
8063 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8064 /// out).
8065 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8066                                SDISelAsmOperandInfo &MatchingOpInfo,
8067                                SelectionDAG &DAG) {
8068   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8069     return;
8070 
8071   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8072   const auto &TLI = DAG.getTargetLoweringInfo();
8073 
8074   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8075       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8076                                        OpInfo.ConstraintVT);
8077   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8078       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8079                                        MatchingOpInfo.ConstraintVT);
8080   if ((OpInfo.ConstraintVT.isInteger() !=
8081        MatchingOpInfo.ConstraintVT.isInteger()) ||
8082       (MatchRC.second != InputRC.second)) {
8083     // FIXME: error out in a more elegant fashion
8084     report_fatal_error("Unsupported asm: input constraint"
8085                        " with a matching output constraint of"
8086                        " incompatible type!");
8087   }
8088   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8089 }
8090 
8091 /// Get a direct memory input to behave well as an indirect operand.
8092 /// This may introduce stores, hence the need for a \p Chain.
8093 /// \return The (possibly updated) chain.
8094 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8095                                         SDISelAsmOperandInfo &OpInfo,
8096                                         SelectionDAG &DAG) {
8097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8098 
8099   // If we don't have an indirect input, put it in the constpool if we can,
8100   // otherwise spill it to a stack slot.
8101   // TODO: This isn't quite right. We need to handle these according to
8102   // the addressing mode that the constraint wants. Also, this may take
8103   // an additional register for the computation and we don't want that
8104   // either.
8105 
8106   // If the operand is a float, integer, or vector constant, spill to a
8107   // constant pool entry to get its address.
8108   const Value *OpVal = OpInfo.CallOperandVal;
8109   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8110       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8111     OpInfo.CallOperand = DAG.getConstantPool(
8112         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8113     return Chain;
8114   }
8115 
8116   // Otherwise, create a stack slot and emit a store to it before the asm.
8117   Type *Ty = OpVal->getType();
8118   auto &DL = DAG.getDataLayout();
8119   uint64_t TySize = DL.getTypeAllocSize(Ty);
8120   MachineFunction &MF = DAG.getMachineFunction();
8121   int SSFI = MF.getFrameInfo().CreateStackObject(
8122       TySize, DL.getPrefTypeAlign(Ty), false);
8123   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8124   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8125                             MachinePointerInfo::getFixedStack(MF, SSFI),
8126                             TLI.getMemValueType(DL, Ty));
8127   OpInfo.CallOperand = StackSlot;
8128 
8129   return Chain;
8130 }
8131 
8132 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8133 /// specified operand.  We prefer to assign virtual registers, to allow the
8134 /// register allocator to handle the assignment process.  However, if the asm
8135 /// uses features that we can't model on machineinstrs, we have SDISel do the
8136 /// allocation.  This produces generally horrible, but correct, code.
8137 ///
8138 ///   OpInfo describes the operand
8139 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8140 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8141                                  SDISelAsmOperandInfo &OpInfo,
8142                                  SDISelAsmOperandInfo &RefOpInfo) {
8143   LLVMContext &Context = *DAG.getContext();
8144   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8145 
8146   MachineFunction &MF = DAG.getMachineFunction();
8147   SmallVector<unsigned, 4> Regs;
8148   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8149 
8150   // No work to do for memory operations.
8151   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8152     return;
8153 
8154   // If this is a constraint for a single physreg, or a constraint for a
8155   // register class, find it.
8156   unsigned AssignedReg;
8157   const TargetRegisterClass *RC;
8158   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8159       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8160   // RC is unset only on failure. Return immediately.
8161   if (!RC)
8162     return;
8163 
8164   // Get the actual register value type.  This is important, because the user
8165   // may have asked for (e.g.) the AX register in i32 type.  We need to
8166   // remember that AX is actually i16 to get the right extension.
8167   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8168 
8169   if (OpInfo.ConstraintVT != MVT::Other) {
8170     // If this is an FP operand in an integer register (or visa versa), or more
8171     // generally if the operand value disagrees with the register class we plan
8172     // to stick it in, fix the operand type.
8173     //
8174     // If this is an input value, the bitcast to the new type is done now.
8175     // Bitcast for output value is done at the end of visitInlineAsm().
8176     if ((OpInfo.Type == InlineAsm::isOutput ||
8177          OpInfo.Type == InlineAsm::isInput) &&
8178         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8179       // Try to convert to the first EVT that the reg class contains.  If the
8180       // types are identical size, use a bitcast to convert (e.g. two differing
8181       // vector types).  Note: output bitcast is done at the end of
8182       // visitInlineAsm().
8183       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8184         // Exclude indirect inputs while they are unsupported because the code
8185         // to perform the load is missing and thus OpInfo.CallOperand still
8186         // refers to the input address rather than the pointed-to value.
8187         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8188           OpInfo.CallOperand =
8189               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8190         OpInfo.ConstraintVT = RegVT;
8191         // If the operand is an FP value and we want it in integer registers,
8192         // use the corresponding integer type. This turns an f64 value into
8193         // i64, which can be passed with two i32 values on a 32-bit machine.
8194       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8195         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8196         if (OpInfo.Type == InlineAsm::isInput)
8197           OpInfo.CallOperand =
8198               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8199         OpInfo.ConstraintVT = VT;
8200       }
8201     }
8202   }
8203 
8204   // No need to allocate a matching input constraint since the constraint it's
8205   // matching to has already been allocated.
8206   if (OpInfo.isMatchingInputConstraint())
8207     return;
8208 
8209   EVT ValueVT = OpInfo.ConstraintVT;
8210   if (OpInfo.ConstraintVT == MVT::Other)
8211     ValueVT = RegVT;
8212 
8213   // Initialize NumRegs.
8214   unsigned NumRegs = 1;
8215   if (OpInfo.ConstraintVT != MVT::Other)
8216     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8217 
8218   // If this is a constraint for a specific physical register, like {r17},
8219   // assign it now.
8220 
8221   // If this associated to a specific register, initialize iterator to correct
8222   // place. If virtual, make sure we have enough registers
8223 
8224   // Initialize iterator if necessary
8225   TargetRegisterClass::iterator I = RC->begin();
8226   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8227 
8228   // Do not check for single registers.
8229   if (AssignedReg) {
8230       for (; *I != AssignedReg; ++I)
8231         assert(I != RC->end() && "AssignedReg should be member of RC");
8232   }
8233 
8234   for (; NumRegs; --NumRegs, ++I) {
8235     assert(I != RC->end() && "Ran out of registers to allocate!");
8236     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8237     Regs.push_back(R);
8238   }
8239 
8240   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8241 }
8242 
8243 static unsigned
8244 findMatchingInlineAsmOperand(unsigned OperandNo,
8245                              const std::vector<SDValue> &AsmNodeOperands) {
8246   // Scan until we find the definition we already emitted of this operand.
8247   unsigned CurOp = InlineAsm::Op_FirstOperand;
8248   for (; OperandNo; --OperandNo) {
8249     // Advance to the next operand.
8250     unsigned OpFlag =
8251         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8252     assert((InlineAsm::isRegDefKind(OpFlag) ||
8253             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8254             InlineAsm::isMemKind(OpFlag)) &&
8255            "Skipped past definitions?");
8256     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8257   }
8258   return CurOp;
8259 }
8260 
8261 namespace {
8262 
8263 class ExtraFlags {
8264   unsigned Flags = 0;
8265 
8266 public:
8267   explicit ExtraFlags(const CallBase &Call) {
8268     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8269     if (IA->hasSideEffects())
8270       Flags |= InlineAsm::Extra_HasSideEffects;
8271     if (IA->isAlignStack())
8272       Flags |= InlineAsm::Extra_IsAlignStack;
8273     if (Call.isConvergent())
8274       Flags |= InlineAsm::Extra_IsConvergent;
8275     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8276   }
8277 
8278   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8279     // Ideally, we would only check against memory constraints.  However, the
8280     // meaning of an Other constraint can be target-specific and we can't easily
8281     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8282     // for Other constraints as well.
8283     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8284         OpInfo.ConstraintType == TargetLowering::C_Other) {
8285       if (OpInfo.Type == InlineAsm::isInput)
8286         Flags |= InlineAsm::Extra_MayLoad;
8287       else if (OpInfo.Type == InlineAsm::isOutput)
8288         Flags |= InlineAsm::Extra_MayStore;
8289       else if (OpInfo.Type == InlineAsm::isClobber)
8290         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8291     }
8292   }
8293 
8294   unsigned get() const { return Flags; }
8295 };
8296 
8297 } // end anonymous namespace
8298 
8299 /// visitInlineAsm - Handle a call to an InlineAsm object.
8300 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8301   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8302 
8303   /// ConstraintOperands - Information about all of the constraints.
8304   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8305 
8306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8307   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8308       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8309 
8310   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8311   // AsmDialect, MayLoad, MayStore).
8312   bool HasSideEffect = IA->hasSideEffects();
8313   ExtraFlags ExtraInfo(Call);
8314 
8315   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8316   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8317   unsigned NumMatchingOps = 0;
8318   for (auto &T : TargetConstraints) {
8319     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8320     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8321 
8322     // Compute the value type for each operand.
8323     if (OpInfo.Type == InlineAsm::isInput ||
8324         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8325       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8326 
8327       // Process the call argument. BasicBlocks are labels, currently appearing
8328       // only in asm's.
8329       if (isa<CallBrInst>(Call) &&
8330           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8331                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8332                         NumMatchingOps) &&
8333           (NumMatchingOps == 0 ||
8334            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8335                         NumMatchingOps))) {
8336         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8337         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8338         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8339       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8340         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8341       } else {
8342         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8343       }
8344 
8345       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8346                                            DAG.getDataLayout());
8347       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8348     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8349       // The return value of the call is this value.  As such, there is no
8350       // corresponding argument.
8351       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8352       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8353         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8354             DAG.getDataLayout(), STy->getElementType(ResNo));
8355       } else {
8356         assert(ResNo == 0 && "Asm only has one result!");
8357         OpInfo.ConstraintVT =
8358             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8359       }
8360       ++ResNo;
8361     } else {
8362       OpInfo.ConstraintVT = MVT::Other;
8363     }
8364 
8365     if (OpInfo.hasMatchingInput())
8366       ++NumMatchingOps;
8367 
8368     if (!HasSideEffect)
8369       HasSideEffect = OpInfo.hasMemory(TLI);
8370 
8371     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8372     // FIXME: Could we compute this on OpInfo rather than T?
8373 
8374     // Compute the constraint code and ConstraintType to use.
8375     TLI.ComputeConstraintToUse(T, SDValue());
8376 
8377     if (T.ConstraintType == TargetLowering::C_Immediate &&
8378         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8379       // We've delayed emitting a diagnostic like the "n" constraint because
8380       // inlining could cause an integer showing up.
8381       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8382                                           "' expects an integer constant "
8383                                           "expression");
8384 
8385     ExtraInfo.update(T);
8386   }
8387 
8388 
8389   // We won't need to flush pending loads if this asm doesn't touch
8390   // memory and is nonvolatile.
8391   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8392 
8393   bool IsCallBr = isa<CallBrInst>(Call);
8394   if (IsCallBr) {
8395     // If this is a callbr we need to flush pending exports since inlineasm_br
8396     // is a terminator. We need to do this before nodes are glued to
8397     // the inlineasm_br node.
8398     Chain = getControlRoot();
8399   }
8400 
8401   // Second pass over the constraints: compute which constraint option to use.
8402   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8403     // If this is an output operand with a matching input operand, look up the
8404     // matching input. If their types mismatch, e.g. one is an integer, the
8405     // other is floating point, or their sizes are different, flag it as an
8406     // error.
8407     if (OpInfo.hasMatchingInput()) {
8408       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8409       patchMatchingInput(OpInfo, Input, DAG);
8410     }
8411 
8412     // Compute the constraint code and ConstraintType to use.
8413     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8414 
8415     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8416         OpInfo.Type == InlineAsm::isClobber)
8417       continue;
8418 
8419     // If this is a memory input, and if the operand is not indirect, do what we
8420     // need to provide an address for the memory input.
8421     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8422         !OpInfo.isIndirect) {
8423       assert((OpInfo.isMultipleAlternative ||
8424               (OpInfo.Type == InlineAsm::isInput)) &&
8425              "Can only indirectify direct input operands!");
8426 
8427       // Memory operands really want the address of the value.
8428       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8429 
8430       // There is no longer a Value* corresponding to this operand.
8431       OpInfo.CallOperandVal = nullptr;
8432 
8433       // It is now an indirect operand.
8434       OpInfo.isIndirect = true;
8435     }
8436 
8437   }
8438 
8439   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8440   std::vector<SDValue> AsmNodeOperands;
8441   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8442   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8443       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8444 
8445   // If we have a !srcloc metadata node associated with it, we want to attach
8446   // this to the ultimately generated inline asm machineinstr.  To do this, we
8447   // pass in the third operand as this (potentially null) inline asm MDNode.
8448   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8449   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8450 
8451   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8452   // bits as operand 3.
8453   AsmNodeOperands.push_back(DAG.getTargetConstant(
8454       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8455 
8456   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8457   // this, assign virtual and physical registers for inputs and otput.
8458   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8459     // Assign Registers.
8460     SDISelAsmOperandInfo &RefOpInfo =
8461         OpInfo.isMatchingInputConstraint()
8462             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8463             : OpInfo;
8464     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8465 
8466     auto DetectWriteToReservedRegister = [&]() {
8467       const MachineFunction &MF = DAG.getMachineFunction();
8468       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8469       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8470         if (Register::isPhysicalRegister(Reg) &&
8471             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8472           const char *RegName = TRI.getName(Reg);
8473           emitInlineAsmError(Call, "write to reserved register '" +
8474                                        Twine(RegName) + "'");
8475           return true;
8476         }
8477       }
8478       return false;
8479     };
8480 
8481     switch (OpInfo.Type) {
8482     case InlineAsm::isOutput:
8483       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8484         unsigned ConstraintID =
8485             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8486         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8487                "Failed to convert memory constraint code to constraint id.");
8488 
8489         // Add information to the INLINEASM node to know about this output.
8490         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8491         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8492         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8493                                                         MVT::i32));
8494         AsmNodeOperands.push_back(OpInfo.CallOperand);
8495       } else {
8496         // Otherwise, this outputs to a register (directly for C_Register /
8497         // C_RegisterClass, and a target-defined fashion for
8498         // C_Immediate/C_Other). Find a register that we can use.
8499         if (OpInfo.AssignedRegs.Regs.empty()) {
8500           emitInlineAsmError(
8501               Call, "couldn't allocate output register for constraint '" +
8502                         Twine(OpInfo.ConstraintCode) + "'");
8503           return;
8504         }
8505 
8506         if (DetectWriteToReservedRegister())
8507           return;
8508 
8509         // Add information to the INLINEASM node to know that this register is
8510         // set.
8511         OpInfo.AssignedRegs.AddInlineAsmOperands(
8512             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8513                                   : InlineAsm::Kind_RegDef,
8514             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8515       }
8516       break;
8517 
8518     case InlineAsm::isInput: {
8519       SDValue InOperandVal = OpInfo.CallOperand;
8520 
8521       if (OpInfo.isMatchingInputConstraint()) {
8522         // If this is required to match an output register we have already set,
8523         // just use its register.
8524         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8525                                                   AsmNodeOperands);
8526         unsigned OpFlag =
8527           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8528         if (InlineAsm::isRegDefKind(OpFlag) ||
8529             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8530           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8531           if (OpInfo.isIndirect) {
8532             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8533             emitInlineAsmError(Call, "inline asm not supported yet: "
8534                                      "don't know how to handle tied "
8535                                      "indirect register inputs");
8536             return;
8537           }
8538 
8539           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8540           SmallVector<unsigned, 4> Regs;
8541 
8542           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8543             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8544             MachineRegisterInfo &RegInfo =
8545                 DAG.getMachineFunction().getRegInfo();
8546             for (unsigned i = 0; i != NumRegs; ++i)
8547               Regs.push_back(RegInfo.createVirtualRegister(RC));
8548           } else {
8549             emitInlineAsmError(Call,
8550                                "inline asm error: This value type register "
8551                                "class is not natively supported!");
8552             return;
8553           }
8554 
8555           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8556 
8557           SDLoc dl = getCurSDLoc();
8558           // Use the produced MatchedRegs object to
8559           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8560           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8561                                            true, OpInfo.getMatchedOperand(), dl,
8562                                            DAG, AsmNodeOperands);
8563           break;
8564         }
8565 
8566         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8567         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8568                "Unexpected number of operands");
8569         // Add information to the INLINEASM node to know about this input.
8570         // See InlineAsm.h isUseOperandTiedToDef.
8571         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8572         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8573                                                     OpInfo.getMatchedOperand());
8574         AsmNodeOperands.push_back(DAG.getTargetConstant(
8575             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8576         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8577         break;
8578       }
8579 
8580       // Treat indirect 'X' constraint as memory.
8581       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8582           OpInfo.isIndirect)
8583         OpInfo.ConstraintType = TargetLowering::C_Memory;
8584 
8585       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8586           OpInfo.ConstraintType == TargetLowering::C_Other) {
8587         std::vector<SDValue> Ops;
8588         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8589                                           Ops, DAG);
8590         if (Ops.empty()) {
8591           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8592             if (isa<ConstantSDNode>(InOperandVal)) {
8593               emitInlineAsmError(Call, "value out of range for constraint '" +
8594                                            Twine(OpInfo.ConstraintCode) + "'");
8595               return;
8596             }
8597 
8598           emitInlineAsmError(Call,
8599                              "invalid operand for inline asm constraint '" +
8600                                  Twine(OpInfo.ConstraintCode) + "'");
8601           return;
8602         }
8603 
8604         // Add information to the INLINEASM node to know about this input.
8605         unsigned ResOpType =
8606           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8607         AsmNodeOperands.push_back(DAG.getTargetConstant(
8608             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8609         llvm::append_range(AsmNodeOperands, Ops);
8610         break;
8611       }
8612 
8613       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8614         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8615         assert(InOperandVal.getValueType() ==
8616                    TLI.getPointerTy(DAG.getDataLayout()) &&
8617                "Memory operands expect pointer values");
8618 
8619         unsigned ConstraintID =
8620             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8621         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8622                "Failed to convert memory constraint code to constraint id.");
8623 
8624         // Add information to the INLINEASM node to know about this input.
8625         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8626         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8627         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8628                                                         getCurSDLoc(),
8629                                                         MVT::i32));
8630         AsmNodeOperands.push_back(InOperandVal);
8631         break;
8632       }
8633 
8634       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8635               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8636              "Unknown constraint type!");
8637 
8638       // TODO: Support this.
8639       if (OpInfo.isIndirect) {
8640         emitInlineAsmError(
8641             Call, "Don't know how to handle indirect register inputs yet "
8642                   "for constraint '" +
8643                       Twine(OpInfo.ConstraintCode) + "'");
8644         return;
8645       }
8646 
8647       // Copy the input into the appropriate registers.
8648       if (OpInfo.AssignedRegs.Regs.empty()) {
8649         emitInlineAsmError(Call,
8650                            "couldn't allocate input reg for constraint '" +
8651                                Twine(OpInfo.ConstraintCode) + "'");
8652         return;
8653       }
8654 
8655       if (DetectWriteToReservedRegister())
8656         return;
8657 
8658       SDLoc dl = getCurSDLoc();
8659 
8660       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8661                                         &Call);
8662 
8663       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8664                                                dl, DAG, AsmNodeOperands);
8665       break;
8666     }
8667     case InlineAsm::isClobber:
8668       // Add the clobbered value to the operand list, so that the register
8669       // allocator is aware that the physreg got clobbered.
8670       if (!OpInfo.AssignedRegs.Regs.empty())
8671         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8672                                                  false, 0, getCurSDLoc(), DAG,
8673                                                  AsmNodeOperands);
8674       break;
8675     }
8676   }
8677 
8678   // Finish up input operands.  Set the input chain and add the flag last.
8679   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8680   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8681 
8682   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8683   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8684                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8685   Flag = Chain.getValue(1);
8686 
8687   // Do additional work to generate outputs.
8688 
8689   SmallVector<EVT, 1> ResultVTs;
8690   SmallVector<SDValue, 1> ResultValues;
8691   SmallVector<SDValue, 8> OutChains;
8692 
8693   llvm::Type *CallResultType = Call.getType();
8694   ArrayRef<Type *> ResultTypes;
8695   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8696     ResultTypes = StructResult->elements();
8697   else if (!CallResultType->isVoidTy())
8698     ResultTypes = makeArrayRef(CallResultType);
8699 
8700   auto CurResultType = ResultTypes.begin();
8701   auto handleRegAssign = [&](SDValue V) {
8702     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8703     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8704     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8705     ++CurResultType;
8706     // If the type of the inline asm call site return value is different but has
8707     // same size as the type of the asm output bitcast it.  One example of this
8708     // is for vectors with different width / number of elements.  This can
8709     // happen for register classes that can contain multiple different value
8710     // types.  The preg or vreg allocated may not have the same VT as was
8711     // expected.
8712     //
8713     // This can also happen for a return value that disagrees with the register
8714     // class it is put in, eg. a double in a general-purpose register on a
8715     // 32-bit machine.
8716     if (ResultVT != V.getValueType() &&
8717         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8718       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8719     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8720              V.getValueType().isInteger()) {
8721       // If a result value was tied to an input value, the computed result
8722       // may have a wider width than the expected result.  Extract the
8723       // relevant portion.
8724       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8725     }
8726     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8727     ResultVTs.push_back(ResultVT);
8728     ResultValues.push_back(V);
8729   };
8730 
8731   // Deal with output operands.
8732   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8733     if (OpInfo.Type == InlineAsm::isOutput) {
8734       SDValue Val;
8735       // Skip trivial output operands.
8736       if (OpInfo.AssignedRegs.Regs.empty())
8737         continue;
8738 
8739       switch (OpInfo.ConstraintType) {
8740       case TargetLowering::C_Register:
8741       case TargetLowering::C_RegisterClass:
8742         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8743                                                   Chain, &Flag, &Call);
8744         break;
8745       case TargetLowering::C_Immediate:
8746       case TargetLowering::C_Other:
8747         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8748                                               OpInfo, DAG);
8749         break;
8750       case TargetLowering::C_Memory:
8751         break; // Already handled.
8752       case TargetLowering::C_Unknown:
8753         assert(false && "Unexpected unknown constraint");
8754       }
8755 
8756       // Indirect output manifest as stores. Record output chains.
8757       if (OpInfo.isIndirect) {
8758         const Value *Ptr = OpInfo.CallOperandVal;
8759         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8760         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8761                                      MachinePointerInfo(Ptr));
8762         OutChains.push_back(Store);
8763       } else {
8764         // generate CopyFromRegs to associated registers.
8765         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8766         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8767           for (const SDValue &V : Val->op_values())
8768             handleRegAssign(V);
8769         } else
8770           handleRegAssign(Val);
8771       }
8772     }
8773   }
8774 
8775   // Set results.
8776   if (!ResultValues.empty()) {
8777     assert(CurResultType == ResultTypes.end() &&
8778            "Mismatch in number of ResultTypes");
8779     assert(ResultValues.size() == ResultTypes.size() &&
8780            "Mismatch in number of output operands in asm result");
8781 
8782     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8783                             DAG.getVTList(ResultVTs), ResultValues);
8784     setValue(&Call, V);
8785   }
8786 
8787   // Collect store chains.
8788   if (!OutChains.empty())
8789     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8790 
8791   // Only Update Root if inline assembly has a memory effect.
8792   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8793     DAG.setRoot(Chain);
8794 }
8795 
8796 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8797                                              const Twine &Message) {
8798   LLVMContext &Ctx = *DAG.getContext();
8799   Ctx.emitError(&Call, Message);
8800 
8801   // Make sure we leave the DAG in a valid state
8802   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8803   SmallVector<EVT, 1> ValueVTs;
8804   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8805 
8806   if (ValueVTs.empty())
8807     return;
8808 
8809   SmallVector<SDValue, 1> Ops;
8810   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8811     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8812 
8813   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8814 }
8815 
8816 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8817   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8818                           MVT::Other, getRoot(),
8819                           getValue(I.getArgOperand(0)),
8820                           DAG.getSrcValue(I.getArgOperand(0))));
8821 }
8822 
8823 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8825   const DataLayout &DL = DAG.getDataLayout();
8826   SDValue V = DAG.getVAArg(
8827       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8828       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8829       DL.getABITypeAlign(I.getType()).value());
8830   DAG.setRoot(V.getValue(1));
8831 
8832   if (I.getType()->isPointerTy())
8833     V = DAG.getPtrExtOrTrunc(
8834         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8835   setValue(&I, V);
8836 }
8837 
8838 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8839   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8840                           MVT::Other, getRoot(),
8841                           getValue(I.getArgOperand(0)),
8842                           DAG.getSrcValue(I.getArgOperand(0))));
8843 }
8844 
8845 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8846   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8847                           MVT::Other, getRoot(),
8848                           getValue(I.getArgOperand(0)),
8849                           getValue(I.getArgOperand(1)),
8850                           DAG.getSrcValue(I.getArgOperand(0)),
8851                           DAG.getSrcValue(I.getArgOperand(1))));
8852 }
8853 
8854 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8855                                                     const Instruction &I,
8856                                                     SDValue Op) {
8857   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8858   if (!Range)
8859     return Op;
8860 
8861   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8862   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8863     return Op;
8864 
8865   APInt Lo = CR.getUnsignedMin();
8866   if (!Lo.isMinValue())
8867     return Op;
8868 
8869   APInt Hi = CR.getUnsignedMax();
8870   unsigned Bits = std::max(Hi.getActiveBits(),
8871                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8872 
8873   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8874 
8875   SDLoc SL = getCurSDLoc();
8876 
8877   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8878                              DAG.getValueType(SmallVT));
8879   unsigned NumVals = Op.getNode()->getNumValues();
8880   if (NumVals == 1)
8881     return ZExt;
8882 
8883   SmallVector<SDValue, 4> Ops;
8884 
8885   Ops.push_back(ZExt);
8886   for (unsigned I = 1; I != NumVals; ++I)
8887     Ops.push_back(Op.getValue(I));
8888 
8889   return DAG.getMergeValues(Ops, SL);
8890 }
8891 
8892 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8893 /// the call being lowered.
8894 ///
8895 /// This is a helper for lowering intrinsics that follow a target calling
8896 /// convention or require stack pointer adjustment. Only a subset of the
8897 /// intrinsic's operands need to participate in the calling convention.
8898 void SelectionDAGBuilder::populateCallLoweringInfo(
8899     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8900     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8901     bool IsPatchPoint) {
8902   TargetLowering::ArgListTy Args;
8903   Args.reserve(NumArgs);
8904 
8905   // Populate the argument list.
8906   // Attributes for args start at offset 1, after the return attribute.
8907   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8908        ArgI != ArgE; ++ArgI) {
8909     const Value *V = Call->getOperand(ArgI);
8910 
8911     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8912 
8913     TargetLowering::ArgListEntry Entry;
8914     Entry.Node = getValue(V);
8915     Entry.Ty = V->getType();
8916     Entry.setAttributes(Call, ArgI);
8917     Args.push_back(Entry);
8918   }
8919 
8920   CLI.setDebugLoc(getCurSDLoc())
8921       .setChain(getRoot())
8922       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8923       .setDiscardResult(Call->use_empty())
8924       .setIsPatchPoint(IsPatchPoint)
8925       .setIsPreallocated(
8926           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8927 }
8928 
8929 /// Add a stack map intrinsic call's live variable operands to a stackmap
8930 /// or patchpoint target node's operand list.
8931 ///
8932 /// Constants are converted to TargetConstants purely as an optimization to
8933 /// avoid constant materialization and register allocation.
8934 ///
8935 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8936 /// generate addess computation nodes, and so FinalizeISel can convert the
8937 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8938 /// address materialization and register allocation, but may also be required
8939 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8940 /// alloca in the entry block, then the runtime may assume that the alloca's
8941 /// StackMap location can be read immediately after compilation and that the
8942 /// location is valid at any point during execution (this is similar to the
8943 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8944 /// only available in a register, then the runtime would need to trap when
8945 /// execution reaches the StackMap in order to read the alloca's location.
8946 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8947                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8948                                 SelectionDAGBuilder &Builder) {
8949   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8950     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8951     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8952       Ops.push_back(
8953         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8954       Ops.push_back(
8955         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8956     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8957       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8958       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8959           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8960     } else
8961       Ops.push_back(OpVal);
8962   }
8963 }
8964 
8965 /// Lower llvm.experimental.stackmap directly to its target opcode.
8966 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8967   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8968   //                                  [live variables...])
8969 
8970   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8971 
8972   SDValue Chain, InFlag, Callee, NullPtr;
8973   SmallVector<SDValue, 32> Ops;
8974 
8975   SDLoc DL = getCurSDLoc();
8976   Callee = getValue(CI.getCalledOperand());
8977   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8978 
8979   // The stackmap intrinsic only records the live variables (the arguments
8980   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8981   // intrinsic, this won't be lowered to a function call. This means we don't
8982   // have to worry about calling conventions and target specific lowering code.
8983   // Instead we perform the call lowering right here.
8984   //
8985   // chain, flag = CALLSEQ_START(chain, 0, 0)
8986   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8987   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8988   //
8989   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8990   InFlag = Chain.getValue(1);
8991 
8992   // Add the <id> and <numBytes> constants.
8993   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8994   Ops.push_back(DAG.getTargetConstant(
8995                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8996   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8997   Ops.push_back(DAG.getTargetConstant(
8998                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8999                   MVT::i32));
9000 
9001   // Push live variables for the stack map.
9002   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9003 
9004   // We are not pushing any register mask info here on the operands list,
9005   // because the stackmap doesn't clobber anything.
9006 
9007   // Push the chain and the glue flag.
9008   Ops.push_back(Chain);
9009   Ops.push_back(InFlag);
9010 
9011   // Create the STACKMAP node.
9012   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9013   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9014   Chain = SDValue(SM, 0);
9015   InFlag = Chain.getValue(1);
9016 
9017   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9018 
9019   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9020 
9021   // Set the root to the target-lowered call chain.
9022   DAG.setRoot(Chain);
9023 
9024   // Inform the Frame Information that we have a stackmap in this function.
9025   FuncInfo.MF->getFrameInfo().setHasStackMap();
9026 }
9027 
9028 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9029 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9030                                           const BasicBlock *EHPadBB) {
9031   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9032   //                                                 i32 <numBytes>,
9033   //                                                 i8* <target>,
9034   //                                                 i32 <numArgs>,
9035   //                                                 [Args...],
9036   //                                                 [live variables...])
9037 
9038   CallingConv::ID CC = CB.getCallingConv();
9039   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9040   bool HasDef = !CB.getType()->isVoidTy();
9041   SDLoc dl = getCurSDLoc();
9042   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9043 
9044   // Handle immediate and symbolic callees.
9045   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9046     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9047                                    /*isTarget=*/true);
9048   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9049     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9050                                          SDLoc(SymbolicCallee),
9051                                          SymbolicCallee->getValueType(0));
9052 
9053   // Get the real number of arguments participating in the call <numArgs>
9054   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9055   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9056 
9057   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9058   // Intrinsics include all meta-operands up to but not including CC.
9059   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9060   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9061          "Not enough arguments provided to the patchpoint intrinsic");
9062 
9063   // For AnyRegCC the arguments are lowered later on manually.
9064   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9065   Type *ReturnTy =
9066       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9067 
9068   TargetLowering::CallLoweringInfo CLI(DAG);
9069   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9070                            ReturnTy, true);
9071   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9072 
9073   SDNode *CallEnd = Result.second.getNode();
9074   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9075     CallEnd = CallEnd->getOperand(0).getNode();
9076 
9077   /// Get a call instruction from the call sequence chain.
9078   /// Tail calls are not allowed.
9079   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9080          "Expected a callseq node.");
9081   SDNode *Call = CallEnd->getOperand(0).getNode();
9082   bool HasGlue = Call->getGluedNode();
9083 
9084   // Replace the target specific call node with the patchable intrinsic.
9085   SmallVector<SDValue, 8> Ops;
9086 
9087   // Add the <id> and <numBytes> constants.
9088   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9089   Ops.push_back(DAG.getTargetConstant(
9090                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9091   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9092   Ops.push_back(DAG.getTargetConstant(
9093                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9094                   MVT::i32));
9095 
9096   // Add the callee.
9097   Ops.push_back(Callee);
9098 
9099   // Adjust <numArgs> to account for any arguments that have been passed on the
9100   // stack instead.
9101   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9102   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9103   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9104   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9105 
9106   // Add the calling convention
9107   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9108 
9109   // Add the arguments we omitted previously. The register allocator should
9110   // place these in any free register.
9111   if (IsAnyRegCC)
9112     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9113       Ops.push_back(getValue(CB.getArgOperand(i)));
9114 
9115   // Push the arguments from the call instruction up to the register mask.
9116   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9117   Ops.append(Call->op_begin() + 2, e);
9118 
9119   // Push live variables for the stack map.
9120   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9121 
9122   // Push the register mask info.
9123   if (HasGlue)
9124     Ops.push_back(*(Call->op_end()-2));
9125   else
9126     Ops.push_back(*(Call->op_end()-1));
9127 
9128   // Push the chain (this is originally the first operand of the call, but
9129   // becomes now the last or second to last operand).
9130   Ops.push_back(*(Call->op_begin()));
9131 
9132   // Push the glue flag (last operand).
9133   if (HasGlue)
9134     Ops.push_back(*(Call->op_end()-1));
9135 
9136   SDVTList NodeTys;
9137   if (IsAnyRegCC && HasDef) {
9138     // Create the return types based on the intrinsic definition
9139     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9140     SmallVector<EVT, 3> ValueVTs;
9141     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9142     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9143 
9144     // There is always a chain and a glue type at the end
9145     ValueVTs.push_back(MVT::Other);
9146     ValueVTs.push_back(MVT::Glue);
9147     NodeTys = DAG.getVTList(ValueVTs);
9148   } else
9149     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9150 
9151   // Replace the target specific call node with a PATCHPOINT node.
9152   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9153                                          dl, NodeTys, Ops);
9154 
9155   // Update the NodeMap.
9156   if (HasDef) {
9157     if (IsAnyRegCC)
9158       setValue(&CB, SDValue(MN, 0));
9159     else
9160       setValue(&CB, Result.first);
9161   }
9162 
9163   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9164   // call sequence. Furthermore the location of the chain and glue can change
9165   // when the AnyReg calling convention is used and the intrinsic returns a
9166   // value.
9167   if (IsAnyRegCC && HasDef) {
9168     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9169     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9170     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9171   } else
9172     DAG.ReplaceAllUsesWith(Call, MN);
9173   DAG.DeleteNode(Call);
9174 
9175   // Inform the Frame Information that we have a patchpoint in this function.
9176   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9177 }
9178 
9179 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9180                                             unsigned Intrinsic) {
9181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9182   SDValue Op1 = getValue(I.getArgOperand(0));
9183   SDValue Op2;
9184   if (I.getNumArgOperands() > 1)
9185     Op2 = getValue(I.getArgOperand(1));
9186   SDLoc dl = getCurSDLoc();
9187   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9188   SDValue Res;
9189   SDNodeFlags SDFlags;
9190   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9191     SDFlags.copyFMF(*FPMO);
9192 
9193   switch (Intrinsic) {
9194   case Intrinsic::vector_reduce_fadd:
9195     if (SDFlags.hasAllowReassociation())
9196       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9197                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9198                         SDFlags);
9199     else
9200       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9201     break;
9202   case Intrinsic::vector_reduce_fmul:
9203     if (SDFlags.hasAllowReassociation())
9204       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9205                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9206                         SDFlags);
9207     else
9208       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9209     break;
9210   case Intrinsic::vector_reduce_add:
9211     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9212     break;
9213   case Intrinsic::vector_reduce_mul:
9214     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9215     break;
9216   case Intrinsic::vector_reduce_and:
9217     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9218     break;
9219   case Intrinsic::vector_reduce_or:
9220     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9221     break;
9222   case Intrinsic::vector_reduce_xor:
9223     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9224     break;
9225   case Intrinsic::vector_reduce_smax:
9226     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9227     break;
9228   case Intrinsic::vector_reduce_smin:
9229     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9230     break;
9231   case Intrinsic::vector_reduce_umax:
9232     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9233     break;
9234   case Intrinsic::vector_reduce_umin:
9235     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9236     break;
9237   case Intrinsic::vector_reduce_fmax:
9238     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9239     break;
9240   case Intrinsic::vector_reduce_fmin:
9241     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9242     break;
9243   default:
9244     llvm_unreachable("Unhandled vector reduce intrinsic");
9245   }
9246   setValue(&I, Res);
9247 }
9248 
9249 /// Returns an AttributeList representing the attributes applied to the return
9250 /// value of the given call.
9251 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9252   SmallVector<Attribute::AttrKind, 2> Attrs;
9253   if (CLI.RetSExt)
9254     Attrs.push_back(Attribute::SExt);
9255   if (CLI.RetZExt)
9256     Attrs.push_back(Attribute::ZExt);
9257   if (CLI.IsInReg)
9258     Attrs.push_back(Attribute::InReg);
9259 
9260   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9261                             Attrs);
9262 }
9263 
9264 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9265 /// implementation, which just calls LowerCall.
9266 /// FIXME: When all targets are
9267 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9268 std::pair<SDValue, SDValue>
9269 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9270   // Handle the incoming return values from the call.
9271   CLI.Ins.clear();
9272   Type *OrigRetTy = CLI.RetTy;
9273   SmallVector<EVT, 4> RetTys;
9274   SmallVector<uint64_t, 4> Offsets;
9275   auto &DL = CLI.DAG.getDataLayout();
9276   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9277 
9278   if (CLI.IsPostTypeLegalization) {
9279     // If we are lowering a libcall after legalization, split the return type.
9280     SmallVector<EVT, 4> OldRetTys;
9281     SmallVector<uint64_t, 4> OldOffsets;
9282     RetTys.swap(OldRetTys);
9283     Offsets.swap(OldOffsets);
9284 
9285     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9286       EVT RetVT = OldRetTys[i];
9287       uint64_t Offset = OldOffsets[i];
9288       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9289       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9290       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9291       RetTys.append(NumRegs, RegisterVT);
9292       for (unsigned j = 0; j != NumRegs; ++j)
9293         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9294     }
9295   }
9296 
9297   SmallVector<ISD::OutputArg, 4> Outs;
9298   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9299 
9300   bool CanLowerReturn =
9301       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9302                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9303 
9304   SDValue DemoteStackSlot;
9305   int DemoteStackIdx = -100;
9306   if (!CanLowerReturn) {
9307     // FIXME: equivalent assert?
9308     // assert(!CS.hasInAllocaArgument() &&
9309     //        "sret demotion is incompatible with inalloca");
9310     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9311     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9312     MachineFunction &MF = CLI.DAG.getMachineFunction();
9313     DemoteStackIdx =
9314         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9315     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9316                                               DL.getAllocaAddrSpace());
9317 
9318     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9319     ArgListEntry Entry;
9320     Entry.Node = DemoteStackSlot;
9321     Entry.Ty = StackSlotPtrType;
9322     Entry.IsSExt = false;
9323     Entry.IsZExt = false;
9324     Entry.IsInReg = false;
9325     Entry.IsSRet = true;
9326     Entry.IsNest = false;
9327     Entry.IsByVal = false;
9328     Entry.IsByRef = false;
9329     Entry.IsReturned = false;
9330     Entry.IsSwiftSelf = false;
9331     Entry.IsSwiftError = false;
9332     Entry.IsCFGuardTarget = false;
9333     Entry.Alignment = Alignment;
9334     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9335     CLI.NumFixedArgs += 1;
9336     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9337 
9338     // sret demotion isn't compatible with tail-calls, since the sret argument
9339     // points into the callers stack frame.
9340     CLI.IsTailCall = false;
9341   } else {
9342     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9343         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9344     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9345       ISD::ArgFlagsTy Flags;
9346       if (NeedsRegBlock) {
9347         Flags.setInConsecutiveRegs();
9348         if (I == RetTys.size() - 1)
9349           Flags.setInConsecutiveRegsLast();
9350       }
9351       EVT VT = RetTys[I];
9352       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9353                                                      CLI.CallConv, VT);
9354       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9355                                                        CLI.CallConv, VT);
9356       for (unsigned i = 0; i != NumRegs; ++i) {
9357         ISD::InputArg MyFlags;
9358         MyFlags.Flags = Flags;
9359         MyFlags.VT = RegisterVT;
9360         MyFlags.ArgVT = VT;
9361         MyFlags.Used = CLI.IsReturnValueUsed;
9362         if (CLI.RetTy->isPointerTy()) {
9363           MyFlags.Flags.setPointer();
9364           MyFlags.Flags.setPointerAddrSpace(
9365               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9366         }
9367         if (CLI.RetSExt)
9368           MyFlags.Flags.setSExt();
9369         if (CLI.RetZExt)
9370           MyFlags.Flags.setZExt();
9371         if (CLI.IsInReg)
9372           MyFlags.Flags.setInReg();
9373         CLI.Ins.push_back(MyFlags);
9374       }
9375     }
9376   }
9377 
9378   // We push in swifterror return as the last element of CLI.Ins.
9379   ArgListTy &Args = CLI.getArgs();
9380   if (supportSwiftError()) {
9381     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9382       if (Args[i].IsSwiftError) {
9383         ISD::InputArg MyFlags;
9384         MyFlags.VT = getPointerTy(DL);
9385         MyFlags.ArgVT = EVT(getPointerTy(DL));
9386         MyFlags.Flags.setSwiftError();
9387         CLI.Ins.push_back(MyFlags);
9388       }
9389     }
9390   }
9391 
9392   // Handle all of the outgoing arguments.
9393   CLI.Outs.clear();
9394   CLI.OutVals.clear();
9395   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9396     SmallVector<EVT, 4> ValueVTs;
9397     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9398     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9399     Type *FinalType = Args[i].Ty;
9400     if (Args[i].IsByVal)
9401       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9402     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9403         FinalType, CLI.CallConv, CLI.IsVarArg);
9404     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9405          ++Value) {
9406       EVT VT = ValueVTs[Value];
9407       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9408       SDValue Op = SDValue(Args[i].Node.getNode(),
9409                            Args[i].Node.getResNo() + Value);
9410       ISD::ArgFlagsTy Flags;
9411 
9412       // Certain targets (such as MIPS), may have a different ABI alignment
9413       // for a type depending on the context. Give the target a chance to
9414       // specify the alignment it wants.
9415       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9416 
9417       if (Args[i].Ty->isPointerTy()) {
9418         Flags.setPointer();
9419         Flags.setPointerAddrSpace(
9420             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9421       }
9422       if (Args[i].IsZExt)
9423         Flags.setZExt();
9424       if (Args[i].IsSExt)
9425         Flags.setSExt();
9426       if (Args[i].IsInReg) {
9427         // If we are using vectorcall calling convention, a structure that is
9428         // passed InReg - is surely an HVA
9429         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9430             isa<StructType>(FinalType)) {
9431           // The first value of a structure is marked
9432           if (0 == Value)
9433             Flags.setHvaStart();
9434           Flags.setHva();
9435         }
9436         // Set InReg Flag
9437         Flags.setInReg();
9438       }
9439       if (Args[i].IsSRet)
9440         Flags.setSRet();
9441       if (Args[i].IsSwiftSelf)
9442         Flags.setSwiftSelf();
9443       if (Args[i].IsSwiftError)
9444         Flags.setSwiftError();
9445       if (Args[i].IsCFGuardTarget)
9446         Flags.setCFGuardTarget();
9447       if (Args[i].IsByVal)
9448         Flags.setByVal();
9449       if (Args[i].IsByRef)
9450         Flags.setByRef();
9451       if (Args[i].IsPreallocated) {
9452         Flags.setPreallocated();
9453         // Set the byval flag for CCAssignFn callbacks that don't know about
9454         // preallocated.  This way we can know how many bytes we should've
9455         // allocated and how many bytes a callee cleanup function will pop.  If
9456         // we port preallocated to more targets, we'll have to add custom
9457         // preallocated handling in the various CC lowering callbacks.
9458         Flags.setByVal();
9459       }
9460       if (Args[i].IsInAlloca) {
9461         Flags.setInAlloca();
9462         // Set the byval flag for CCAssignFn callbacks that don't know about
9463         // inalloca.  This way we can know how many bytes we should've allocated
9464         // and how many bytes a callee cleanup function will pop.  If we port
9465         // inalloca to more targets, we'll have to add custom inalloca handling
9466         // in the various CC lowering callbacks.
9467         Flags.setByVal();
9468       }
9469       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9470         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9471         Type *ElementTy = Ty->getElementType();
9472 
9473         unsigned FrameSize = DL.getTypeAllocSize(
9474             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9475         Flags.setByValSize(FrameSize);
9476 
9477         // info is not there but there are cases it cannot get right.
9478         Align FrameAlign;
9479         if (auto MA = Args[i].Alignment)
9480           FrameAlign = *MA;
9481         else
9482           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9483         Flags.setByValAlign(FrameAlign);
9484       }
9485       if (Args[i].IsNest)
9486         Flags.setNest();
9487       if (NeedsRegBlock)
9488         Flags.setInConsecutiveRegs();
9489       Flags.setOrigAlign(OriginalAlignment);
9490 
9491       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9492                                                  CLI.CallConv, VT);
9493       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9494                                                         CLI.CallConv, VT);
9495       SmallVector<SDValue, 4> Parts(NumParts);
9496       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9497 
9498       if (Args[i].IsSExt)
9499         ExtendKind = ISD::SIGN_EXTEND;
9500       else if (Args[i].IsZExt)
9501         ExtendKind = ISD::ZERO_EXTEND;
9502 
9503       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9504       // for now.
9505       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9506           CanLowerReturn) {
9507         assert((CLI.RetTy == Args[i].Ty ||
9508                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9509                  CLI.RetTy->getPointerAddressSpace() ==
9510                      Args[i].Ty->getPointerAddressSpace())) &&
9511                RetTys.size() == NumValues && "unexpected use of 'returned'");
9512         // Before passing 'returned' to the target lowering code, ensure that
9513         // either the register MVT and the actual EVT are the same size or that
9514         // the return value and argument are extended in the same way; in these
9515         // cases it's safe to pass the argument register value unchanged as the
9516         // return register value (although it's at the target's option whether
9517         // to do so)
9518         // TODO: allow code generation to take advantage of partially preserved
9519         // registers rather than clobbering the entire register when the
9520         // parameter extension method is not compatible with the return
9521         // extension method
9522         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9523             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9524              CLI.RetZExt == Args[i].IsZExt))
9525           Flags.setReturned();
9526       }
9527 
9528       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9529                      CLI.CallConv, ExtendKind);
9530 
9531       for (unsigned j = 0; j != NumParts; ++j) {
9532         // if it isn't first piece, alignment must be 1
9533         // For scalable vectors the scalable part is currently handled
9534         // by individual targets, so we just use the known minimum size here.
9535         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9536                     i < CLI.NumFixedArgs, i,
9537                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9538         if (NumParts > 1 && j == 0)
9539           MyFlags.Flags.setSplit();
9540         else if (j != 0) {
9541           MyFlags.Flags.setOrigAlign(Align(1));
9542           if (j == NumParts - 1)
9543             MyFlags.Flags.setSplitEnd();
9544         }
9545 
9546         CLI.Outs.push_back(MyFlags);
9547         CLI.OutVals.push_back(Parts[j]);
9548       }
9549 
9550       if (NeedsRegBlock && Value == NumValues - 1)
9551         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9552     }
9553   }
9554 
9555   SmallVector<SDValue, 4> InVals;
9556   CLI.Chain = LowerCall(CLI, InVals);
9557 
9558   // Update CLI.InVals to use outside of this function.
9559   CLI.InVals = InVals;
9560 
9561   // Verify that the target's LowerCall behaved as expected.
9562   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9563          "LowerCall didn't return a valid chain!");
9564   assert((!CLI.IsTailCall || InVals.empty()) &&
9565          "LowerCall emitted a return value for a tail call!");
9566   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9567          "LowerCall didn't emit the correct number of values!");
9568 
9569   // For a tail call, the return value is merely live-out and there aren't
9570   // any nodes in the DAG representing it. Return a special value to
9571   // indicate that a tail call has been emitted and no more Instructions
9572   // should be processed in the current block.
9573   if (CLI.IsTailCall) {
9574     CLI.DAG.setRoot(CLI.Chain);
9575     return std::make_pair(SDValue(), SDValue());
9576   }
9577 
9578 #ifndef NDEBUG
9579   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9580     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9581     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9582            "LowerCall emitted a value with the wrong type!");
9583   }
9584 #endif
9585 
9586   SmallVector<SDValue, 4> ReturnValues;
9587   if (!CanLowerReturn) {
9588     // The instruction result is the result of loading from the
9589     // hidden sret parameter.
9590     SmallVector<EVT, 1> PVTs;
9591     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9592 
9593     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9594     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9595     EVT PtrVT = PVTs[0];
9596 
9597     unsigned NumValues = RetTys.size();
9598     ReturnValues.resize(NumValues);
9599     SmallVector<SDValue, 4> Chains(NumValues);
9600 
9601     // An aggregate return value cannot wrap around the address space, so
9602     // offsets to its parts don't wrap either.
9603     SDNodeFlags Flags;
9604     Flags.setNoUnsignedWrap(true);
9605 
9606     MachineFunction &MF = CLI.DAG.getMachineFunction();
9607     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9608     for (unsigned i = 0; i < NumValues; ++i) {
9609       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9610                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9611                                                         PtrVT), Flags);
9612       SDValue L = CLI.DAG.getLoad(
9613           RetTys[i], CLI.DL, CLI.Chain, Add,
9614           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9615                                             DemoteStackIdx, Offsets[i]),
9616           HiddenSRetAlign);
9617       ReturnValues[i] = L;
9618       Chains[i] = L.getValue(1);
9619     }
9620 
9621     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9622   } else {
9623     // Collect the legal value parts into potentially illegal values
9624     // that correspond to the original function's return values.
9625     Optional<ISD::NodeType> AssertOp;
9626     if (CLI.RetSExt)
9627       AssertOp = ISD::AssertSext;
9628     else if (CLI.RetZExt)
9629       AssertOp = ISD::AssertZext;
9630     unsigned CurReg = 0;
9631     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9632       EVT VT = RetTys[I];
9633       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9634                                                      CLI.CallConv, VT);
9635       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9636                                                        CLI.CallConv, VT);
9637 
9638       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9639                                               NumRegs, RegisterVT, VT, nullptr,
9640                                               CLI.CallConv, AssertOp));
9641       CurReg += NumRegs;
9642     }
9643 
9644     // For a function returning void, there is no return value. We can't create
9645     // such a node, so we just return a null return value in that case. In
9646     // that case, nothing will actually look at the value.
9647     if (ReturnValues.empty())
9648       return std::make_pair(SDValue(), CLI.Chain);
9649   }
9650 
9651   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9652                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9653   return std::make_pair(Res, CLI.Chain);
9654 }
9655 
9656 /// Places new result values for the node in Results (their number
9657 /// and types must exactly match those of the original return values of
9658 /// the node), or leaves Results empty, which indicates that the node is not
9659 /// to be custom lowered after all.
9660 void TargetLowering::LowerOperationWrapper(SDNode *N,
9661                                            SmallVectorImpl<SDValue> &Results,
9662                                            SelectionDAG &DAG) const {
9663   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9664 
9665   if (!Res.getNode())
9666     return;
9667 
9668   // If the original node has one result, take the return value from
9669   // LowerOperation as is. It might not be result number 0.
9670   if (N->getNumValues() == 1) {
9671     Results.push_back(Res);
9672     return;
9673   }
9674 
9675   // If the original node has multiple results, then the return node should
9676   // have the same number of results.
9677   assert((N->getNumValues() == Res->getNumValues()) &&
9678       "Lowering returned the wrong number of results!");
9679 
9680   // Places new result values base on N result number.
9681   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9682     Results.push_back(Res.getValue(I));
9683 }
9684 
9685 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9686   llvm_unreachable("LowerOperation not implemented for this target!");
9687 }
9688 
9689 void
9690 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9691   SDValue Op = getNonRegisterValue(V);
9692   assert((Op.getOpcode() != ISD::CopyFromReg ||
9693           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9694          "Copy from a reg to the same reg!");
9695   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9696 
9697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9698   // If this is an InlineAsm we have to match the registers required, not the
9699   // notional registers required by the type.
9700 
9701   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9702                    None); // This is not an ABI copy.
9703   SDValue Chain = DAG.getEntryNode();
9704 
9705   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9706                               FuncInfo.PreferredExtendType.end())
9707                                  ? ISD::ANY_EXTEND
9708                                  : FuncInfo.PreferredExtendType[V];
9709   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9710   PendingExports.push_back(Chain);
9711 }
9712 
9713 #include "llvm/CodeGen/SelectionDAGISel.h"
9714 
9715 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9716 /// entry block, return true.  This includes arguments used by switches, since
9717 /// the switch may expand into multiple basic blocks.
9718 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9719   // With FastISel active, we may be splitting blocks, so force creation
9720   // of virtual registers for all non-dead arguments.
9721   if (FastISel)
9722     return A->use_empty();
9723 
9724   const BasicBlock &Entry = A->getParent()->front();
9725   for (const User *U : A->users())
9726     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9727       return false;  // Use not in entry block.
9728 
9729   return true;
9730 }
9731 
9732 using ArgCopyElisionMapTy =
9733     DenseMap<const Argument *,
9734              std::pair<const AllocaInst *, const StoreInst *>>;
9735 
9736 /// Scan the entry block of the function in FuncInfo for arguments that look
9737 /// like copies into a local alloca. Record any copied arguments in
9738 /// ArgCopyElisionCandidates.
9739 static void
9740 findArgumentCopyElisionCandidates(const DataLayout &DL,
9741                                   FunctionLoweringInfo *FuncInfo,
9742                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9743   // Record the state of every static alloca used in the entry block. Argument
9744   // allocas are all used in the entry block, so we need approximately as many
9745   // entries as we have arguments.
9746   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9747   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9748   unsigned NumArgs = FuncInfo->Fn->arg_size();
9749   StaticAllocas.reserve(NumArgs * 2);
9750 
9751   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9752     if (!V)
9753       return nullptr;
9754     V = V->stripPointerCasts();
9755     const auto *AI = dyn_cast<AllocaInst>(V);
9756     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9757       return nullptr;
9758     auto Iter = StaticAllocas.insert({AI, Unknown});
9759     return &Iter.first->second;
9760   };
9761 
9762   // Look for stores of arguments to static allocas. Look through bitcasts and
9763   // GEPs to handle type coercions, as long as the alloca is fully initialized
9764   // by the store. Any non-store use of an alloca escapes it and any subsequent
9765   // unanalyzed store might write it.
9766   // FIXME: Handle structs initialized with multiple stores.
9767   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9768     // Look for stores, and handle non-store uses conservatively.
9769     const auto *SI = dyn_cast<StoreInst>(&I);
9770     if (!SI) {
9771       // We will look through cast uses, so ignore them completely.
9772       if (I.isCast())
9773         continue;
9774       // Ignore debug info and pseudo op intrinsics, they don't escape or store
9775       // to allocas.
9776       if (I.isDebugOrPseudoInst())
9777         continue;
9778       // This is an unknown instruction. Assume it escapes or writes to all
9779       // static alloca operands.
9780       for (const Use &U : I.operands()) {
9781         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9782           *Info = StaticAllocaInfo::Clobbered;
9783       }
9784       continue;
9785     }
9786 
9787     // If the stored value is a static alloca, mark it as escaped.
9788     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9789       *Info = StaticAllocaInfo::Clobbered;
9790 
9791     // Check if the destination is a static alloca.
9792     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9793     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9794     if (!Info)
9795       continue;
9796     const AllocaInst *AI = cast<AllocaInst>(Dst);
9797 
9798     // Skip allocas that have been initialized or clobbered.
9799     if (*Info != StaticAllocaInfo::Unknown)
9800       continue;
9801 
9802     // Check if the stored value is an argument, and that this store fully
9803     // initializes the alloca. Don't elide copies from the same argument twice.
9804     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9805     const auto *Arg = dyn_cast<Argument>(Val);
9806     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9807         Arg->getType()->isEmptyTy() ||
9808         DL.getTypeStoreSize(Arg->getType()) !=
9809             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9810         ArgCopyElisionCandidates.count(Arg)) {
9811       *Info = StaticAllocaInfo::Clobbered;
9812       continue;
9813     }
9814 
9815     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9816                       << '\n');
9817 
9818     // Mark this alloca and store for argument copy elision.
9819     *Info = StaticAllocaInfo::Elidable;
9820     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9821 
9822     // Stop scanning if we've seen all arguments. This will happen early in -O0
9823     // builds, which is useful, because -O0 builds have large entry blocks and
9824     // many allocas.
9825     if (ArgCopyElisionCandidates.size() == NumArgs)
9826       break;
9827   }
9828 }
9829 
9830 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9831 /// ArgVal is a load from a suitable fixed stack object.
9832 static void tryToElideArgumentCopy(
9833     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9834     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9835     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9836     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9837     SDValue ArgVal, bool &ArgHasUses) {
9838   // Check if this is a load from a fixed stack object.
9839   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9840   if (!LNode)
9841     return;
9842   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9843   if (!FINode)
9844     return;
9845 
9846   // Check that the fixed stack object is the right size and alignment.
9847   // Look at the alignment that the user wrote on the alloca instead of looking
9848   // at the stack object.
9849   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9850   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9851   const AllocaInst *AI = ArgCopyIter->second.first;
9852   int FixedIndex = FINode->getIndex();
9853   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9854   int OldIndex = AllocaIndex;
9855   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9856   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9857     LLVM_DEBUG(
9858         dbgs() << "  argument copy elision failed due to bad fixed stack "
9859                   "object size\n");
9860     return;
9861   }
9862   Align RequiredAlignment = AI->getAlign();
9863   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9864     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9865                          "greater than stack argument alignment ("
9866                       << DebugStr(RequiredAlignment) << " vs "
9867                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9868     return;
9869   }
9870 
9871   // Perform the elision. Delete the old stack object and replace its only use
9872   // in the variable info map. Mark the stack object as mutable.
9873   LLVM_DEBUG({
9874     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9875            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9876            << '\n';
9877   });
9878   MFI.RemoveStackObject(OldIndex);
9879   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9880   AllocaIndex = FixedIndex;
9881   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9882   Chains.push_back(ArgVal.getValue(1));
9883 
9884   // Avoid emitting code for the store implementing the copy.
9885   const StoreInst *SI = ArgCopyIter->second.second;
9886   ElidedArgCopyInstrs.insert(SI);
9887 
9888   // Check for uses of the argument again so that we can avoid exporting ArgVal
9889   // if it is't used by anything other than the store.
9890   for (const Value *U : Arg.users()) {
9891     if (U != SI) {
9892       ArgHasUses = true;
9893       break;
9894     }
9895   }
9896 }
9897 
9898 void SelectionDAGISel::LowerArguments(const Function &F) {
9899   SelectionDAG &DAG = SDB->DAG;
9900   SDLoc dl = SDB->getCurSDLoc();
9901   const DataLayout &DL = DAG.getDataLayout();
9902   SmallVector<ISD::InputArg, 16> Ins;
9903 
9904   // In Naked functions we aren't going to save any registers.
9905   if (F.hasFnAttribute(Attribute::Naked))
9906     return;
9907 
9908   if (!FuncInfo->CanLowerReturn) {
9909     // Put in an sret pointer parameter before all the other parameters.
9910     SmallVector<EVT, 1> ValueVTs;
9911     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9912                     F.getReturnType()->getPointerTo(
9913                         DAG.getDataLayout().getAllocaAddrSpace()),
9914                     ValueVTs);
9915 
9916     // NOTE: Assuming that a pointer will never break down to more than one VT
9917     // or one register.
9918     ISD::ArgFlagsTy Flags;
9919     Flags.setSRet();
9920     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9921     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9922                          ISD::InputArg::NoArgIndex, 0);
9923     Ins.push_back(RetArg);
9924   }
9925 
9926   // Look for stores of arguments to static allocas. Mark such arguments with a
9927   // flag to ask the target to give us the memory location of that argument if
9928   // available.
9929   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9930   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9931                                     ArgCopyElisionCandidates);
9932 
9933   // Set up the incoming argument description vector.
9934   for (const Argument &Arg : F.args()) {
9935     unsigned ArgNo = Arg.getArgNo();
9936     SmallVector<EVT, 4> ValueVTs;
9937     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9938     bool isArgValueUsed = !Arg.use_empty();
9939     unsigned PartBase = 0;
9940     Type *FinalType = Arg.getType();
9941     if (Arg.hasAttribute(Attribute::ByVal))
9942       FinalType = Arg.getParamByValType();
9943     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9944         FinalType, F.getCallingConv(), F.isVarArg());
9945     for (unsigned Value = 0, NumValues = ValueVTs.size();
9946          Value != NumValues; ++Value) {
9947       EVT VT = ValueVTs[Value];
9948       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9949       ISD::ArgFlagsTy Flags;
9950 
9951       // Certain targets (such as MIPS), may have a different ABI alignment
9952       // for a type depending on the context. Give the target a chance to
9953       // specify the alignment it wants.
9954       const Align OriginalAlignment(
9955           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9956 
9957       if (Arg.getType()->isPointerTy()) {
9958         Flags.setPointer();
9959         Flags.setPointerAddrSpace(
9960             cast<PointerType>(Arg.getType())->getAddressSpace());
9961       }
9962       if (Arg.hasAttribute(Attribute::ZExt))
9963         Flags.setZExt();
9964       if (Arg.hasAttribute(Attribute::SExt))
9965         Flags.setSExt();
9966       if (Arg.hasAttribute(Attribute::InReg)) {
9967         // If we are using vectorcall calling convention, a structure that is
9968         // passed InReg - is surely an HVA
9969         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9970             isa<StructType>(Arg.getType())) {
9971           // The first value of a structure is marked
9972           if (0 == Value)
9973             Flags.setHvaStart();
9974           Flags.setHva();
9975         }
9976         // Set InReg Flag
9977         Flags.setInReg();
9978       }
9979       if (Arg.hasAttribute(Attribute::StructRet))
9980         Flags.setSRet();
9981       if (Arg.hasAttribute(Attribute::SwiftSelf))
9982         Flags.setSwiftSelf();
9983       if (Arg.hasAttribute(Attribute::SwiftError))
9984         Flags.setSwiftError();
9985       if (Arg.hasAttribute(Attribute::ByVal))
9986         Flags.setByVal();
9987       if (Arg.hasAttribute(Attribute::ByRef))
9988         Flags.setByRef();
9989       if (Arg.hasAttribute(Attribute::InAlloca)) {
9990         Flags.setInAlloca();
9991         // Set the byval flag for CCAssignFn callbacks that don't know about
9992         // inalloca.  This way we can know how many bytes we should've allocated
9993         // and how many bytes a callee cleanup function will pop.  If we port
9994         // inalloca to more targets, we'll have to add custom inalloca handling
9995         // in the various CC lowering callbacks.
9996         Flags.setByVal();
9997       }
9998       if (Arg.hasAttribute(Attribute::Preallocated)) {
9999         Flags.setPreallocated();
10000         // Set the byval flag for CCAssignFn callbacks that don't know about
10001         // preallocated.  This way we can know how many bytes we should've
10002         // allocated and how many bytes a callee cleanup function will pop.  If
10003         // we port preallocated to more targets, we'll have to add custom
10004         // preallocated handling in the various CC lowering callbacks.
10005         Flags.setByVal();
10006       }
10007 
10008       Type *ArgMemTy = nullptr;
10009       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10010           Flags.isByRef()) {
10011         if (!ArgMemTy)
10012           ArgMemTy = Arg.getPointeeInMemoryValueType();
10013 
10014         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10015 
10016         // For in-memory arguments, size and alignment should be passed from FE.
10017         // BE will guess if this info is not there but there are cases it cannot
10018         // get right.
10019         MaybeAlign MemAlign = Arg.getParamAlign();
10020         if (!MemAlign)
10021           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10022 
10023         if (Flags.isByRef()) {
10024           Flags.setByRefSize(MemSize);
10025           Flags.setByRefAlign(*MemAlign);
10026         } else {
10027           Flags.setByValSize(MemSize);
10028           Flags.setByValAlign(*MemAlign);
10029         }
10030       }
10031 
10032       if (Arg.hasAttribute(Attribute::Nest))
10033         Flags.setNest();
10034       if (NeedsRegBlock)
10035         Flags.setInConsecutiveRegs();
10036       Flags.setOrigAlign(OriginalAlignment);
10037       if (ArgCopyElisionCandidates.count(&Arg))
10038         Flags.setCopyElisionCandidate();
10039       if (Arg.hasAttribute(Attribute::Returned))
10040         Flags.setReturned();
10041 
10042       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10043           *CurDAG->getContext(), F.getCallingConv(), VT);
10044       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10045           *CurDAG->getContext(), F.getCallingConv(), VT);
10046       for (unsigned i = 0; i != NumRegs; ++i) {
10047         // For scalable vectors, use the minimum size; individual targets
10048         // are responsible for handling scalable vector arguments and
10049         // return values.
10050         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10051                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10052         if (NumRegs > 1 && i == 0)
10053           MyFlags.Flags.setSplit();
10054         // if it isn't first piece, alignment must be 1
10055         else if (i > 0) {
10056           MyFlags.Flags.setOrigAlign(Align(1));
10057           if (i == NumRegs - 1)
10058             MyFlags.Flags.setSplitEnd();
10059         }
10060         Ins.push_back(MyFlags);
10061       }
10062       if (NeedsRegBlock && Value == NumValues - 1)
10063         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10064       PartBase += VT.getStoreSize().getKnownMinSize();
10065     }
10066   }
10067 
10068   // Call the target to set up the argument values.
10069   SmallVector<SDValue, 8> InVals;
10070   SDValue NewRoot = TLI->LowerFormalArguments(
10071       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10072 
10073   // Verify that the target's LowerFormalArguments behaved as expected.
10074   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10075          "LowerFormalArguments didn't return a valid chain!");
10076   assert(InVals.size() == Ins.size() &&
10077          "LowerFormalArguments didn't emit the correct number of values!");
10078   LLVM_DEBUG({
10079     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10080       assert(InVals[i].getNode() &&
10081              "LowerFormalArguments emitted a null value!");
10082       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10083              "LowerFormalArguments emitted a value with the wrong type!");
10084     }
10085   });
10086 
10087   // Update the DAG with the new chain value resulting from argument lowering.
10088   DAG.setRoot(NewRoot);
10089 
10090   // Set up the argument values.
10091   unsigned i = 0;
10092   if (!FuncInfo->CanLowerReturn) {
10093     // Create a virtual register for the sret pointer, and put in a copy
10094     // from the sret argument into it.
10095     SmallVector<EVT, 1> ValueVTs;
10096     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10097                     F.getReturnType()->getPointerTo(
10098                         DAG.getDataLayout().getAllocaAddrSpace()),
10099                     ValueVTs);
10100     MVT VT = ValueVTs[0].getSimpleVT();
10101     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10102     Optional<ISD::NodeType> AssertOp = None;
10103     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10104                                         nullptr, F.getCallingConv(), AssertOp);
10105 
10106     MachineFunction& MF = SDB->DAG.getMachineFunction();
10107     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10108     Register SRetReg =
10109         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10110     FuncInfo->DemoteRegister = SRetReg;
10111     NewRoot =
10112         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10113     DAG.setRoot(NewRoot);
10114 
10115     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10116     ++i;
10117   }
10118 
10119   SmallVector<SDValue, 4> Chains;
10120   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10121   for (const Argument &Arg : F.args()) {
10122     SmallVector<SDValue, 4> ArgValues;
10123     SmallVector<EVT, 4> ValueVTs;
10124     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10125     unsigned NumValues = ValueVTs.size();
10126     if (NumValues == 0)
10127       continue;
10128 
10129     bool ArgHasUses = !Arg.use_empty();
10130 
10131     // Elide the copying store if the target loaded this argument from a
10132     // suitable fixed stack object.
10133     if (Ins[i].Flags.isCopyElisionCandidate()) {
10134       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10135                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10136                              InVals[i], ArgHasUses);
10137     }
10138 
10139     // If this argument is unused then remember its value. It is used to generate
10140     // debugging information.
10141     bool isSwiftErrorArg =
10142         TLI->supportSwiftError() &&
10143         Arg.hasAttribute(Attribute::SwiftError);
10144     if (!ArgHasUses && !isSwiftErrorArg) {
10145       SDB->setUnusedArgValue(&Arg, InVals[i]);
10146 
10147       // Also remember any frame index for use in FastISel.
10148       if (FrameIndexSDNode *FI =
10149           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10150         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10151     }
10152 
10153     for (unsigned Val = 0; Val != NumValues; ++Val) {
10154       EVT VT = ValueVTs[Val];
10155       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10156                                                       F.getCallingConv(), VT);
10157       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10158           *CurDAG->getContext(), F.getCallingConv(), VT);
10159 
10160       // Even an apparent 'unused' swifterror argument needs to be returned. So
10161       // we do generate a copy for it that can be used on return from the
10162       // function.
10163       if (ArgHasUses || isSwiftErrorArg) {
10164         Optional<ISD::NodeType> AssertOp;
10165         if (Arg.hasAttribute(Attribute::SExt))
10166           AssertOp = ISD::AssertSext;
10167         else if (Arg.hasAttribute(Attribute::ZExt))
10168           AssertOp = ISD::AssertZext;
10169 
10170         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10171                                              PartVT, VT, nullptr,
10172                                              F.getCallingConv(), AssertOp));
10173       }
10174 
10175       i += NumParts;
10176     }
10177 
10178     // We don't need to do anything else for unused arguments.
10179     if (ArgValues.empty())
10180       continue;
10181 
10182     // Note down frame index.
10183     if (FrameIndexSDNode *FI =
10184         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10185       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10186 
10187     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10188                                      SDB->getCurSDLoc());
10189 
10190     SDB->setValue(&Arg, Res);
10191     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10192       // We want to associate the argument with the frame index, among
10193       // involved operands, that correspond to the lowest address. The
10194       // getCopyFromParts function, called earlier, is swapping the order of
10195       // the operands to BUILD_PAIR depending on endianness. The result of
10196       // that swapping is that the least significant bits of the argument will
10197       // be in the first operand of the BUILD_PAIR node, and the most
10198       // significant bits will be in the second operand.
10199       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10200       if (LoadSDNode *LNode =
10201           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10202         if (FrameIndexSDNode *FI =
10203             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10204           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10205     }
10206 
10207     // Analyses past this point are naive and don't expect an assertion.
10208     if (Res.getOpcode() == ISD::AssertZext)
10209       Res = Res.getOperand(0);
10210 
10211     // Update the SwiftErrorVRegDefMap.
10212     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10213       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10214       if (Register::isVirtualRegister(Reg))
10215         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10216                                    Reg);
10217     }
10218 
10219     // If this argument is live outside of the entry block, insert a copy from
10220     // wherever we got it to the vreg that other BB's will reference it as.
10221     if (Res.getOpcode() == ISD::CopyFromReg) {
10222       // If we can, though, try to skip creating an unnecessary vreg.
10223       // FIXME: This isn't very clean... it would be nice to make this more
10224       // general.
10225       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10226       if (Register::isVirtualRegister(Reg)) {
10227         FuncInfo->ValueMap[&Arg] = Reg;
10228         continue;
10229       }
10230     }
10231     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10232       FuncInfo->InitializeRegForValue(&Arg);
10233       SDB->CopyToExportRegsIfNeeded(&Arg);
10234     }
10235   }
10236 
10237   if (!Chains.empty()) {
10238     Chains.push_back(NewRoot);
10239     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10240   }
10241 
10242   DAG.setRoot(NewRoot);
10243 
10244   assert(i == InVals.size() && "Argument register count mismatch!");
10245 
10246   // If any argument copy elisions occurred and we have debug info, update the
10247   // stale frame indices used in the dbg.declare variable info table.
10248   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10249   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10250     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10251       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10252       if (I != ArgCopyElisionFrameIndexMap.end())
10253         VI.Slot = I->second;
10254     }
10255   }
10256 
10257   // Finally, if the target has anything special to do, allow it to do so.
10258   emitFunctionEntryCode();
10259 }
10260 
10261 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10262 /// ensure constants are generated when needed.  Remember the virtual registers
10263 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10264 /// directly add them, because expansion might result in multiple MBB's for one
10265 /// BB.  As such, the start of the BB might correspond to a different MBB than
10266 /// the end.
10267 void
10268 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10269   const Instruction *TI = LLVMBB->getTerminator();
10270 
10271   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10272 
10273   // Check PHI nodes in successors that expect a value to be available from this
10274   // block.
10275   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10276     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10277     if (!isa<PHINode>(SuccBB->begin())) continue;
10278     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10279 
10280     // If this terminator has multiple identical successors (common for
10281     // switches), only handle each succ once.
10282     if (!SuccsHandled.insert(SuccMBB).second)
10283       continue;
10284 
10285     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10286 
10287     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10288     // nodes and Machine PHI nodes, but the incoming operands have not been
10289     // emitted yet.
10290     for (const PHINode &PN : SuccBB->phis()) {
10291       // Ignore dead phi's.
10292       if (PN.use_empty())
10293         continue;
10294 
10295       // Skip empty types
10296       if (PN.getType()->isEmptyTy())
10297         continue;
10298 
10299       unsigned Reg;
10300       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10301 
10302       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10303         unsigned &RegOut = ConstantsOut[C];
10304         if (RegOut == 0) {
10305           RegOut = FuncInfo.CreateRegs(C);
10306           CopyValueToVirtualRegister(C, RegOut);
10307         }
10308         Reg = RegOut;
10309       } else {
10310         DenseMap<const Value *, Register>::iterator I =
10311           FuncInfo.ValueMap.find(PHIOp);
10312         if (I != FuncInfo.ValueMap.end())
10313           Reg = I->second;
10314         else {
10315           assert(isa<AllocaInst>(PHIOp) &&
10316                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10317                  "Didn't codegen value into a register!??");
10318           Reg = FuncInfo.CreateRegs(PHIOp);
10319           CopyValueToVirtualRegister(PHIOp, Reg);
10320         }
10321       }
10322 
10323       // Remember that this register needs to added to the machine PHI node as
10324       // the input for this MBB.
10325       SmallVector<EVT, 4> ValueVTs;
10326       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10327       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10328       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10329         EVT VT = ValueVTs[vti];
10330         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10331         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10332           FuncInfo.PHINodesToUpdate.push_back(
10333               std::make_pair(&*MBBI++, Reg + i));
10334         Reg += NumRegisters;
10335       }
10336     }
10337   }
10338 
10339   ConstantsOut.clear();
10340 }
10341 
10342 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10343 /// is 0.
10344 MachineBasicBlock *
10345 SelectionDAGBuilder::StackProtectorDescriptor::
10346 AddSuccessorMBB(const BasicBlock *BB,
10347                 MachineBasicBlock *ParentMBB,
10348                 bool IsLikely,
10349                 MachineBasicBlock *SuccMBB) {
10350   // If SuccBB has not been created yet, create it.
10351   if (!SuccMBB) {
10352     MachineFunction *MF = ParentMBB->getParent();
10353     MachineFunction::iterator BBI(ParentMBB);
10354     SuccMBB = MF->CreateMachineBasicBlock(BB);
10355     MF->insert(++BBI, SuccMBB);
10356   }
10357   // Add it as a successor of ParentMBB.
10358   ParentMBB->addSuccessor(
10359       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10360   return SuccMBB;
10361 }
10362 
10363 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10364   MachineFunction::iterator I(MBB);
10365   if (++I == FuncInfo.MF->end())
10366     return nullptr;
10367   return &*I;
10368 }
10369 
10370 /// During lowering new call nodes can be created (such as memset, etc.).
10371 /// Those will become new roots of the current DAG, but complications arise
10372 /// when they are tail calls. In such cases, the call lowering will update
10373 /// the root, but the builder still needs to know that a tail call has been
10374 /// lowered in order to avoid generating an additional return.
10375 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10376   // If the node is null, we do have a tail call.
10377   if (MaybeTC.getNode() != nullptr)
10378     DAG.setRoot(MaybeTC);
10379   else
10380     HasTailCall = true;
10381 }
10382 
10383 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10384                                         MachineBasicBlock *SwitchMBB,
10385                                         MachineBasicBlock *DefaultMBB) {
10386   MachineFunction *CurMF = FuncInfo.MF;
10387   MachineBasicBlock *NextMBB = nullptr;
10388   MachineFunction::iterator BBI(W.MBB);
10389   if (++BBI != FuncInfo.MF->end())
10390     NextMBB = &*BBI;
10391 
10392   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10393 
10394   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10395 
10396   if (Size == 2 && W.MBB == SwitchMBB) {
10397     // If any two of the cases has the same destination, and if one value
10398     // is the same as the other, but has one bit unset that the other has set,
10399     // use bit manipulation to do two compares at once.  For example:
10400     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10401     // TODO: This could be extended to merge any 2 cases in switches with 3
10402     // cases.
10403     // TODO: Handle cases where W.CaseBB != SwitchBB.
10404     CaseCluster &Small = *W.FirstCluster;
10405     CaseCluster &Big = *W.LastCluster;
10406 
10407     if (Small.Low == Small.High && Big.Low == Big.High &&
10408         Small.MBB == Big.MBB) {
10409       const APInt &SmallValue = Small.Low->getValue();
10410       const APInt &BigValue = Big.Low->getValue();
10411 
10412       // Check that there is only one bit different.
10413       APInt CommonBit = BigValue ^ SmallValue;
10414       if (CommonBit.isPowerOf2()) {
10415         SDValue CondLHS = getValue(Cond);
10416         EVT VT = CondLHS.getValueType();
10417         SDLoc DL = getCurSDLoc();
10418 
10419         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10420                                  DAG.getConstant(CommonBit, DL, VT));
10421         SDValue Cond = DAG.getSetCC(
10422             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10423             ISD::SETEQ);
10424 
10425         // Update successor info.
10426         // Both Small and Big will jump to Small.BB, so we sum up the
10427         // probabilities.
10428         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10429         if (BPI)
10430           addSuccessorWithProb(
10431               SwitchMBB, DefaultMBB,
10432               // The default destination is the first successor in IR.
10433               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10434         else
10435           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10436 
10437         // Insert the true branch.
10438         SDValue BrCond =
10439             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10440                         DAG.getBasicBlock(Small.MBB));
10441         // Insert the false branch.
10442         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10443                              DAG.getBasicBlock(DefaultMBB));
10444 
10445         DAG.setRoot(BrCond);
10446         return;
10447       }
10448     }
10449   }
10450 
10451   if (TM.getOptLevel() != CodeGenOpt::None) {
10452     // Here, we order cases by probability so the most likely case will be
10453     // checked first. However, two clusters can have the same probability in
10454     // which case their relative ordering is non-deterministic. So we use Low
10455     // as a tie-breaker as clusters are guaranteed to never overlap.
10456     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10457                [](const CaseCluster &a, const CaseCluster &b) {
10458       return a.Prob != b.Prob ?
10459              a.Prob > b.Prob :
10460              a.Low->getValue().slt(b.Low->getValue());
10461     });
10462 
10463     // Rearrange the case blocks so that the last one falls through if possible
10464     // without changing the order of probabilities.
10465     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10466       --I;
10467       if (I->Prob > W.LastCluster->Prob)
10468         break;
10469       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10470         std::swap(*I, *W.LastCluster);
10471         break;
10472       }
10473     }
10474   }
10475 
10476   // Compute total probability.
10477   BranchProbability DefaultProb = W.DefaultProb;
10478   BranchProbability UnhandledProbs = DefaultProb;
10479   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10480     UnhandledProbs += I->Prob;
10481 
10482   MachineBasicBlock *CurMBB = W.MBB;
10483   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10484     bool FallthroughUnreachable = false;
10485     MachineBasicBlock *Fallthrough;
10486     if (I == W.LastCluster) {
10487       // For the last cluster, fall through to the default destination.
10488       Fallthrough = DefaultMBB;
10489       FallthroughUnreachable = isa<UnreachableInst>(
10490           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10491     } else {
10492       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10493       CurMF->insert(BBI, Fallthrough);
10494       // Put Cond in a virtual register to make it available from the new blocks.
10495       ExportFromCurrentBlock(Cond);
10496     }
10497     UnhandledProbs -= I->Prob;
10498 
10499     switch (I->Kind) {
10500       case CC_JumpTable: {
10501         // FIXME: Optimize away range check based on pivot comparisons.
10502         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10503         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10504 
10505         // The jump block hasn't been inserted yet; insert it here.
10506         MachineBasicBlock *JumpMBB = JT->MBB;
10507         CurMF->insert(BBI, JumpMBB);
10508 
10509         auto JumpProb = I->Prob;
10510         auto FallthroughProb = UnhandledProbs;
10511 
10512         // If the default statement is a target of the jump table, we evenly
10513         // distribute the default probability to successors of CurMBB. Also
10514         // update the probability on the edge from JumpMBB to Fallthrough.
10515         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10516                                               SE = JumpMBB->succ_end();
10517              SI != SE; ++SI) {
10518           if (*SI == DefaultMBB) {
10519             JumpProb += DefaultProb / 2;
10520             FallthroughProb -= DefaultProb / 2;
10521             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10522             JumpMBB->normalizeSuccProbs();
10523             break;
10524           }
10525         }
10526 
10527         if (FallthroughUnreachable) {
10528           // Skip the range check if the fallthrough block is unreachable.
10529           JTH->OmitRangeCheck = true;
10530         }
10531 
10532         if (!JTH->OmitRangeCheck)
10533           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10534         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10535         CurMBB->normalizeSuccProbs();
10536 
10537         // The jump table header will be inserted in our current block, do the
10538         // range check, and fall through to our fallthrough block.
10539         JTH->HeaderBB = CurMBB;
10540         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10541 
10542         // If we're in the right place, emit the jump table header right now.
10543         if (CurMBB == SwitchMBB) {
10544           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10545           JTH->Emitted = true;
10546         }
10547         break;
10548       }
10549       case CC_BitTests: {
10550         // FIXME: Optimize away range check based on pivot comparisons.
10551         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10552 
10553         // The bit test blocks haven't been inserted yet; insert them here.
10554         for (BitTestCase &BTC : BTB->Cases)
10555           CurMF->insert(BBI, BTC.ThisBB);
10556 
10557         // Fill in fields of the BitTestBlock.
10558         BTB->Parent = CurMBB;
10559         BTB->Default = Fallthrough;
10560 
10561         BTB->DefaultProb = UnhandledProbs;
10562         // If the cases in bit test don't form a contiguous range, we evenly
10563         // distribute the probability on the edge to Fallthrough to two
10564         // successors of CurMBB.
10565         if (!BTB->ContiguousRange) {
10566           BTB->Prob += DefaultProb / 2;
10567           BTB->DefaultProb -= DefaultProb / 2;
10568         }
10569 
10570         if (FallthroughUnreachable) {
10571           // Skip the range check if the fallthrough block is unreachable.
10572           BTB->OmitRangeCheck = true;
10573         }
10574 
10575         // If we're in the right place, emit the bit test header right now.
10576         if (CurMBB == SwitchMBB) {
10577           visitBitTestHeader(*BTB, SwitchMBB);
10578           BTB->Emitted = true;
10579         }
10580         break;
10581       }
10582       case CC_Range: {
10583         const Value *RHS, *LHS, *MHS;
10584         ISD::CondCode CC;
10585         if (I->Low == I->High) {
10586           // Check Cond == I->Low.
10587           CC = ISD::SETEQ;
10588           LHS = Cond;
10589           RHS=I->Low;
10590           MHS = nullptr;
10591         } else {
10592           // Check I->Low <= Cond <= I->High.
10593           CC = ISD::SETLE;
10594           LHS = I->Low;
10595           MHS = Cond;
10596           RHS = I->High;
10597         }
10598 
10599         // If Fallthrough is unreachable, fold away the comparison.
10600         if (FallthroughUnreachable)
10601           CC = ISD::SETTRUE;
10602 
10603         // The false probability is the sum of all unhandled cases.
10604         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10605                      getCurSDLoc(), I->Prob, UnhandledProbs);
10606 
10607         if (CurMBB == SwitchMBB)
10608           visitSwitchCase(CB, SwitchMBB);
10609         else
10610           SL->SwitchCases.push_back(CB);
10611 
10612         break;
10613       }
10614     }
10615     CurMBB = Fallthrough;
10616   }
10617 }
10618 
10619 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10620                                               CaseClusterIt First,
10621                                               CaseClusterIt Last) {
10622   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10623     if (X.Prob != CC.Prob)
10624       return X.Prob > CC.Prob;
10625 
10626     // Ties are broken by comparing the case value.
10627     return X.Low->getValue().slt(CC.Low->getValue());
10628   });
10629 }
10630 
10631 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10632                                         const SwitchWorkListItem &W,
10633                                         Value *Cond,
10634                                         MachineBasicBlock *SwitchMBB) {
10635   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10636          "Clusters not sorted?");
10637 
10638   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10639 
10640   // Balance the tree based on branch probabilities to create a near-optimal (in
10641   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10642   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10643   CaseClusterIt LastLeft = W.FirstCluster;
10644   CaseClusterIt FirstRight = W.LastCluster;
10645   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10646   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10647 
10648   // Move LastLeft and FirstRight towards each other from opposite directions to
10649   // find a partitioning of the clusters which balances the probability on both
10650   // sides. If LeftProb and RightProb are equal, alternate which side is
10651   // taken to ensure 0-probability nodes are distributed evenly.
10652   unsigned I = 0;
10653   while (LastLeft + 1 < FirstRight) {
10654     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10655       LeftProb += (++LastLeft)->Prob;
10656     else
10657       RightProb += (--FirstRight)->Prob;
10658     I++;
10659   }
10660 
10661   while (true) {
10662     // Our binary search tree differs from a typical BST in that ours can have up
10663     // to three values in each leaf. The pivot selection above doesn't take that
10664     // into account, which means the tree might require more nodes and be less
10665     // efficient. We compensate for this here.
10666 
10667     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10668     unsigned NumRight = W.LastCluster - FirstRight + 1;
10669 
10670     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10671       // If one side has less than 3 clusters, and the other has more than 3,
10672       // consider taking a cluster from the other side.
10673 
10674       if (NumLeft < NumRight) {
10675         // Consider moving the first cluster on the right to the left side.
10676         CaseCluster &CC = *FirstRight;
10677         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10678         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10679         if (LeftSideRank <= RightSideRank) {
10680           // Moving the cluster to the left does not demote it.
10681           ++LastLeft;
10682           ++FirstRight;
10683           continue;
10684         }
10685       } else {
10686         assert(NumRight < NumLeft);
10687         // Consider moving the last element on the left to the right side.
10688         CaseCluster &CC = *LastLeft;
10689         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10690         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10691         if (RightSideRank <= LeftSideRank) {
10692           // Moving the cluster to the right does not demot it.
10693           --LastLeft;
10694           --FirstRight;
10695           continue;
10696         }
10697       }
10698     }
10699     break;
10700   }
10701 
10702   assert(LastLeft + 1 == FirstRight);
10703   assert(LastLeft >= W.FirstCluster);
10704   assert(FirstRight <= W.LastCluster);
10705 
10706   // Use the first element on the right as pivot since we will make less-than
10707   // comparisons against it.
10708   CaseClusterIt PivotCluster = FirstRight;
10709   assert(PivotCluster > W.FirstCluster);
10710   assert(PivotCluster <= W.LastCluster);
10711 
10712   CaseClusterIt FirstLeft = W.FirstCluster;
10713   CaseClusterIt LastRight = W.LastCluster;
10714 
10715   const ConstantInt *Pivot = PivotCluster->Low;
10716 
10717   // New blocks will be inserted immediately after the current one.
10718   MachineFunction::iterator BBI(W.MBB);
10719   ++BBI;
10720 
10721   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10722   // we can branch to its destination directly if it's squeezed exactly in
10723   // between the known lower bound and Pivot - 1.
10724   MachineBasicBlock *LeftMBB;
10725   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10726       FirstLeft->Low == W.GE &&
10727       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10728     LeftMBB = FirstLeft->MBB;
10729   } else {
10730     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10731     FuncInfo.MF->insert(BBI, LeftMBB);
10732     WorkList.push_back(
10733         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10734     // Put Cond in a virtual register to make it available from the new blocks.
10735     ExportFromCurrentBlock(Cond);
10736   }
10737 
10738   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10739   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10740   // directly if RHS.High equals the current upper bound.
10741   MachineBasicBlock *RightMBB;
10742   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10743       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10744     RightMBB = FirstRight->MBB;
10745   } else {
10746     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10747     FuncInfo.MF->insert(BBI, RightMBB);
10748     WorkList.push_back(
10749         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10750     // Put Cond in a virtual register to make it available from the new blocks.
10751     ExportFromCurrentBlock(Cond);
10752   }
10753 
10754   // Create the CaseBlock record that will be used to lower the branch.
10755   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10756                getCurSDLoc(), LeftProb, RightProb);
10757 
10758   if (W.MBB == SwitchMBB)
10759     visitSwitchCase(CB, SwitchMBB);
10760   else
10761     SL->SwitchCases.push_back(CB);
10762 }
10763 
10764 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10765 // from the swith statement.
10766 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10767                                             BranchProbability PeeledCaseProb) {
10768   if (PeeledCaseProb == BranchProbability::getOne())
10769     return BranchProbability::getZero();
10770   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10771 
10772   uint32_t Numerator = CaseProb.getNumerator();
10773   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10774   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10775 }
10776 
10777 // Try to peel the top probability case if it exceeds the threshold.
10778 // Return current MachineBasicBlock for the switch statement if the peeling
10779 // does not occur.
10780 // If the peeling is performed, return the newly created MachineBasicBlock
10781 // for the peeled switch statement. Also update Clusters to remove the peeled
10782 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10783 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10784     const SwitchInst &SI, CaseClusterVector &Clusters,
10785     BranchProbability &PeeledCaseProb) {
10786   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10787   // Don't perform if there is only one cluster or optimizing for size.
10788   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10789       TM.getOptLevel() == CodeGenOpt::None ||
10790       SwitchMBB->getParent()->getFunction().hasMinSize())
10791     return SwitchMBB;
10792 
10793   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10794   unsigned PeeledCaseIndex = 0;
10795   bool SwitchPeeled = false;
10796   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10797     CaseCluster &CC = Clusters[Index];
10798     if (CC.Prob < TopCaseProb)
10799       continue;
10800     TopCaseProb = CC.Prob;
10801     PeeledCaseIndex = Index;
10802     SwitchPeeled = true;
10803   }
10804   if (!SwitchPeeled)
10805     return SwitchMBB;
10806 
10807   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10808                     << TopCaseProb << "\n");
10809 
10810   // Record the MBB for the peeled switch statement.
10811   MachineFunction::iterator BBI(SwitchMBB);
10812   ++BBI;
10813   MachineBasicBlock *PeeledSwitchMBB =
10814       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10815   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10816 
10817   ExportFromCurrentBlock(SI.getCondition());
10818   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10819   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10820                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10821   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10822 
10823   Clusters.erase(PeeledCaseIt);
10824   for (CaseCluster &CC : Clusters) {
10825     LLVM_DEBUG(
10826         dbgs() << "Scale the probablity for one cluster, before scaling: "
10827                << CC.Prob << "\n");
10828     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10829     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10830   }
10831   PeeledCaseProb = TopCaseProb;
10832   return PeeledSwitchMBB;
10833 }
10834 
10835 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10836   // Extract cases from the switch.
10837   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10838   CaseClusterVector Clusters;
10839   Clusters.reserve(SI.getNumCases());
10840   for (auto I : SI.cases()) {
10841     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10842     const ConstantInt *CaseVal = I.getCaseValue();
10843     BranchProbability Prob =
10844         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10845             : BranchProbability(1, SI.getNumCases() + 1);
10846     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10847   }
10848 
10849   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10850 
10851   // Cluster adjacent cases with the same destination. We do this at all
10852   // optimization levels because it's cheap to do and will make codegen faster
10853   // if there are many clusters.
10854   sortAndRangeify(Clusters);
10855 
10856   // The branch probablity of the peeled case.
10857   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10858   MachineBasicBlock *PeeledSwitchMBB =
10859       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10860 
10861   // If there is only the default destination, jump there directly.
10862   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10863   if (Clusters.empty()) {
10864     assert(PeeledSwitchMBB == SwitchMBB);
10865     SwitchMBB->addSuccessor(DefaultMBB);
10866     if (DefaultMBB != NextBlock(SwitchMBB)) {
10867       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10868                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10869     }
10870     return;
10871   }
10872 
10873   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10874   SL->findBitTestClusters(Clusters, &SI);
10875 
10876   LLVM_DEBUG({
10877     dbgs() << "Case clusters: ";
10878     for (const CaseCluster &C : Clusters) {
10879       if (C.Kind == CC_JumpTable)
10880         dbgs() << "JT:";
10881       if (C.Kind == CC_BitTests)
10882         dbgs() << "BT:";
10883 
10884       C.Low->getValue().print(dbgs(), true);
10885       if (C.Low != C.High) {
10886         dbgs() << '-';
10887         C.High->getValue().print(dbgs(), true);
10888       }
10889       dbgs() << ' ';
10890     }
10891     dbgs() << '\n';
10892   });
10893 
10894   assert(!Clusters.empty());
10895   SwitchWorkList WorkList;
10896   CaseClusterIt First = Clusters.begin();
10897   CaseClusterIt Last = Clusters.end() - 1;
10898   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10899   // Scale the branchprobability for DefaultMBB if the peel occurs and
10900   // DefaultMBB is not replaced.
10901   if (PeeledCaseProb != BranchProbability::getZero() &&
10902       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10903     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10904   WorkList.push_back(
10905       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10906 
10907   while (!WorkList.empty()) {
10908     SwitchWorkListItem W = WorkList.pop_back_val();
10909     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10910 
10911     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10912         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10913       // For optimized builds, lower large range as a balanced binary tree.
10914       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10915       continue;
10916     }
10917 
10918     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10919   }
10920 }
10921 
10922 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
10923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10924   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10925 
10926   SDLoc DL = getCurSDLoc();
10927   SDValue V = getValue(I.getOperand(0));
10928   assert(VT == V.getValueType() && "Malformed vector.reverse!");
10929 
10930   if (VT.isScalableVector()) {
10931     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
10932     return;
10933   }
10934 
10935   // Use VECTOR_SHUFFLE for the fixed-length vector
10936   // to maintain existing behavior.
10937   SmallVector<int, 8> Mask;
10938   unsigned NumElts = VT.getVectorMinNumElements();
10939   for (unsigned i = 0; i != NumElts; ++i)
10940     Mask.push_back(NumElts - 1 - i);
10941 
10942   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
10943 }
10944 
10945 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10946   SmallVector<EVT, 4> ValueVTs;
10947   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10948                   ValueVTs);
10949   unsigned NumValues = ValueVTs.size();
10950   if (NumValues == 0) return;
10951 
10952   SmallVector<SDValue, 4> Values(NumValues);
10953   SDValue Op = getValue(I.getOperand(0));
10954 
10955   for (unsigned i = 0; i != NumValues; ++i)
10956     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10957                             SDValue(Op.getNode(), Op.getResNo() + i));
10958 
10959   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10960                            DAG.getVTList(ValueVTs), Values));
10961 }
10962 
10963 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
10964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10965   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10966 
10967   SDLoc DL = getCurSDLoc();
10968   SDValue V1 = getValue(I.getOperand(0));
10969   SDValue V2 = getValue(I.getOperand(1));
10970   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
10971 
10972   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
10973   if (VT.isScalableVector()) {
10974     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
10975     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
10976                              DAG.getConstant(Imm, DL, IdxVT)));
10977     return;
10978   }
10979 
10980   unsigned NumElts = VT.getVectorNumElements();
10981 
10982   if ((-Imm > NumElts) || (Imm >= NumElts)) {
10983     // Result is undefined if immediate is out-of-bounds.
10984     setValue(&I, DAG.getUNDEF(VT));
10985     return;
10986   }
10987 
10988   uint64_t Idx = (NumElts + Imm) % NumElts;
10989 
10990   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
10991   SmallVector<int, 8> Mask;
10992   for (unsigned i = 0; i < NumElts; ++i)
10993     Mask.push_back(Idx + i);
10994   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
10995 }
10996