xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 0d822da2bdda30a6a79971f9d160c82a4566f6a6)
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     // Vector/Vector bitcast.
403     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
404       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
405 
406     // If the element type of the source/dest vectors are the same, but the
407     // parts vector has more elements than the value vector, then we have a
408     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
409     // elements we want.
410     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
411       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
412               ValueVT.getVectorElementCount().getKnownMinValue()) &&
413              (PartEVT.getVectorElementCount().isScalable() ==
414               ValueVT.getVectorElementCount().isScalable()) &&
415              "Cannot narrow, it would be a lossy transformation");
416       PartEVT =
417           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
418                            ValueVT.getVectorElementCount());
419       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
420                         DAG.getVectorIdxConstant(0, DL));
421       if (PartEVT == ValueVT)
422         return Val;
423     }
424 
425     // Promoted vector extract
426     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
427   }
428 
429   // Trivial bitcast if the types are the same size and the destination
430   // vector type is legal.
431   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
432       TLI.isTypeLegal(ValueVT))
433     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
434 
435   if (ValueVT.getVectorNumElements() != 1) {
436      // Certain ABIs require that vectors are passed as integers. For vectors
437      // are the same size, this is an obvious bitcast.
438      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
439        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
440      } else if (ValueVT.bitsLT(PartEVT)) {
441        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
442        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
443        // Drop the extra bits.
444        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
445        return DAG.getBitcast(ValueVT, Val);
446      }
447 
448      diagnosePossiblyInvalidConstraint(
449          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
450      return DAG.getUNDEF(ValueVT);
451   }
452 
453   // Handle cases such as i8 -> <1 x i1>
454   EVT ValueSVT = ValueVT.getVectorElementType();
455   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
456     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
457       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
458     else
459       Val = ValueVT.isFloatingPoint()
460                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
461                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
462   }
463 
464   return DAG.getBuildVector(ValueVT, DL, Val);
465 }
466 
467 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
468                                  SDValue Val, SDValue *Parts, unsigned NumParts,
469                                  MVT PartVT, const Value *V,
470                                  Optional<CallingConv::ID> CallConv);
471 
472 /// getCopyToParts - Create a series of nodes that contain the specified value
473 /// split into legal parts.  If the parts contain more bits than Val, then, for
474 /// integers, ExtendKind can be used to specify how to generate the extra bits.
475 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
476                            SDValue *Parts, unsigned NumParts, MVT PartVT,
477                            const Value *V,
478                            Optional<CallingConv::ID> CallConv = None,
479                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
480   // Let the target split the parts if it wants to
481   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
482   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
483                                       CallConv))
484     return;
485   EVT ValueVT = Val.getValueType();
486 
487   // Handle the vector case separately.
488   if (ValueVT.isVector())
489     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
490                                 CallConv);
491 
492   unsigned PartBits = PartVT.getSizeInBits();
493   unsigned OrigNumParts = NumParts;
494   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
495          "Copying to an illegal type!");
496 
497   if (NumParts == 0)
498     return;
499 
500   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
501   EVT PartEVT = PartVT;
502   if (PartEVT == ValueVT) {
503     assert(NumParts == 1 && "No-op copy with multiple parts!");
504     Parts[0] = Val;
505     return;
506   }
507 
508   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
509     // If the parts cover more bits than the value has, promote the value.
510     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
511       assert(NumParts == 1 && "Do not know what to promote to!");
512       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
513     } else {
514       if (ValueVT.isFloatingPoint()) {
515         // FP values need to be bitcast, then extended if they are being put
516         // into a larger container.
517         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
518         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
519       }
520       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
521              ValueVT.isInteger() &&
522              "Unknown mismatch!");
523       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
524       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
525       if (PartVT == MVT::x86mmx)
526         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
527     }
528   } else if (PartBits == ValueVT.getSizeInBits()) {
529     // Different types of the same size.
530     assert(NumParts == 1 && PartEVT != ValueVT);
531     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
532   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
533     // If the parts cover less bits than value has, truncate the value.
534     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
535            ValueVT.isInteger() &&
536            "Unknown mismatch!");
537     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
538     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
539     if (PartVT == MVT::x86mmx)
540       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
541   }
542 
543   // The value may have changed - recompute ValueVT.
544   ValueVT = Val.getValueType();
545   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
546          "Failed to tile the value with PartVT!");
547 
548   if (NumParts == 1) {
549     if (PartEVT != ValueVT) {
550       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
551                                         "scalar-to-vector conversion failed");
552       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
553     }
554 
555     Parts[0] = Val;
556     return;
557   }
558 
559   // Expand the value into multiple parts.
560   if (NumParts & (NumParts - 1)) {
561     // The number of parts is not a power of 2.  Split off and copy the tail.
562     assert(PartVT.isInteger() && ValueVT.isInteger() &&
563            "Do not know what to expand to!");
564     unsigned RoundParts = 1 << Log2_32(NumParts);
565     unsigned RoundBits = RoundParts * PartBits;
566     unsigned OddParts = NumParts - RoundParts;
567     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
568       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
569 
570     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
571                    CallConv);
572 
573     if (DAG.getDataLayout().isBigEndian())
574       // The odd parts were reversed by getCopyToParts - unreverse them.
575       std::reverse(Parts + RoundParts, Parts + NumParts);
576 
577     NumParts = RoundParts;
578     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
579     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
580   }
581 
582   // The number of parts is a power of 2.  Repeatedly bisect the value using
583   // EXTRACT_ELEMENT.
584   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
585                          EVT::getIntegerVT(*DAG.getContext(),
586                                            ValueVT.getSizeInBits()),
587                          Val);
588 
589   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
590     for (unsigned i = 0; i < NumParts; i += StepSize) {
591       unsigned ThisBits = StepSize * PartBits / 2;
592       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
593       SDValue &Part0 = Parts[i];
594       SDValue &Part1 = Parts[i+StepSize/2];
595 
596       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
597                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
598       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
599                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
600 
601       if (ThisBits == PartBits && ThisVT != PartVT) {
602         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
603         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
604       }
605     }
606   }
607 
608   if (DAG.getDataLayout().isBigEndian())
609     std::reverse(Parts, Parts + OrigNumParts);
610 }
611 
612 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
613                                      const SDLoc &DL, EVT PartVT) {
614   if (!PartVT.isVector())
615     return SDValue();
616 
617   EVT ValueVT = Val.getValueType();
618   ElementCount PartNumElts = PartVT.getVectorElementCount();
619   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
620 
621   // We only support widening vectors with equivalent element types and
622   // fixed/scalable properties. If a target needs to widen a fixed-length type
623   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
624   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
625       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
626       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
627     return SDValue();
628 
629   // Widening a scalable vector to another scalable vector is done by inserting
630   // the vector into a larger undef one.
631   if (PartNumElts.isScalable())
632     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
633                        Val, DAG.getVectorIdxConstant(0, DL));
634 
635   EVT ElementVT = PartVT.getVectorElementType();
636   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
637   // undef elements.
638   SmallVector<SDValue, 16> Ops;
639   DAG.ExtractVectorElements(Val, Ops);
640   SDValue EltUndef = DAG.getUNDEF(ElementVT);
641   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
642 
643   // FIXME: Use CONCAT for 2x -> 4x.
644   return DAG.getBuildVector(PartVT, DL, Ops);
645 }
646 
647 /// getCopyToPartsVector - Create a series of nodes that contain the specified
648 /// value split into legal parts.
649 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
650                                  SDValue Val, SDValue *Parts, unsigned NumParts,
651                                  MVT PartVT, const Value *V,
652                                  Optional<CallingConv::ID> CallConv) {
653   EVT ValueVT = Val.getValueType();
654   assert(ValueVT.isVector() && "Not a vector");
655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
656   const bool IsABIRegCopy = CallConv.hasValue();
657 
658   if (NumParts == 1) {
659     EVT PartEVT = PartVT;
660     if (PartEVT == ValueVT) {
661       // Nothing to do.
662     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
663       // Bitconvert vector->vector case.
664       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
665     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
666       Val = Widened;
667     } else if (PartVT.isVector() &&
668                PartEVT.getVectorElementType().bitsGE(
669                    ValueVT.getVectorElementType()) &&
670                PartEVT.getVectorElementCount() ==
671                    ValueVT.getVectorElementCount()) {
672 
673       // Promoted vector extract
674       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
675     } else {
676       if (ValueVT.getVectorElementCount().isScalar()) {
677         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
678                           DAG.getVectorIdxConstant(0, DL));
679       } else {
680         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
681         assert(PartVT.getFixedSizeInBits() > ValueSize &&
682                "lossy conversion of vector to scalar type");
683         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
684         Val = DAG.getBitcast(IntermediateType, Val);
685         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
686       }
687     }
688 
689     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
690     Parts[0] = Val;
691     return;
692   }
693 
694   // Handle a multi-element vector.
695   EVT IntermediateVT;
696   MVT RegisterVT;
697   unsigned NumIntermediates;
698   unsigned NumRegs;
699   if (IsABIRegCopy) {
700     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
701         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
702         NumIntermediates, RegisterVT);
703   } else {
704     NumRegs =
705         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
706                                    NumIntermediates, RegisterVT);
707   }
708 
709   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
710   NumParts = NumRegs; // Silence a compiler warning.
711   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
712 
713   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
714          "Mixing scalable and fixed vectors when copying in parts");
715 
716   Optional<ElementCount> DestEltCnt;
717 
718   if (IntermediateVT.isVector())
719     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
720   else
721     DestEltCnt = ElementCount::getFixed(NumIntermediates);
722 
723   EVT BuiltVectorTy = EVT::getVectorVT(
724       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
725 
726   if (ValueVT == BuiltVectorTy) {
727     // Nothing to do.
728   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
729     // Bitconvert vector->vector case.
730     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
731   } else {
732     if (BuiltVectorTy.getVectorElementType().bitsGT(
733             ValueVT.getVectorElementType())) {
734       // Integer promotion.
735       ValueVT = EVT::getVectorVT(*DAG.getContext(),
736                                  BuiltVectorTy.getVectorElementType(),
737                                  ValueVT.getVectorElementCount());
738       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
739     }
740 
741     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
742       Val = Widened;
743     }
744   }
745 
746   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
747 
748   // Split the vector into intermediate operands.
749   SmallVector<SDValue, 8> Ops(NumIntermediates);
750   for (unsigned i = 0; i != NumIntermediates; ++i) {
751     if (IntermediateVT.isVector()) {
752       // This does something sensible for scalable vectors - see the
753       // definition of EXTRACT_SUBVECTOR for further details.
754       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
755       Ops[i] =
756           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
757                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
758     } else {
759       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
760                            DAG.getVectorIdxConstant(i, DL));
761     }
762   }
763 
764   // Split the intermediate operands into legal parts.
765   if (NumParts == NumIntermediates) {
766     // If the register was not expanded, promote or copy the value,
767     // as appropriate.
768     for (unsigned i = 0; i != NumParts; ++i)
769       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
770   } else if (NumParts > 0) {
771     // If the intermediate type was expanded, split each the value into
772     // legal parts.
773     assert(NumIntermediates != 0 && "division by zero");
774     assert(NumParts % NumIntermediates == 0 &&
775            "Must expand into a divisible number of parts!");
776     unsigned Factor = NumParts / NumIntermediates;
777     for (unsigned i = 0; i != NumIntermediates; ++i)
778       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
779                      CallConv);
780   }
781 }
782 
783 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
784                            EVT valuevt, Optional<CallingConv::ID> CC)
785     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
786       RegCount(1, regs.size()), CallConv(CC) {}
787 
788 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
789                            const DataLayout &DL, unsigned Reg, Type *Ty,
790                            Optional<CallingConv::ID> CC) {
791   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
792 
793   CallConv = CC;
794 
795   for (EVT ValueVT : ValueVTs) {
796     unsigned NumRegs =
797         isABIMangled()
798             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
799             : TLI.getNumRegisters(Context, ValueVT);
800     MVT RegisterVT =
801         isABIMangled()
802             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
803             : TLI.getRegisterType(Context, ValueVT);
804     for (unsigned i = 0; i != NumRegs; ++i)
805       Regs.push_back(Reg + i);
806     RegVTs.push_back(RegisterVT);
807     RegCount.push_back(NumRegs);
808     Reg += NumRegs;
809   }
810 }
811 
812 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
813                                       FunctionLoweringInfo &FuncInfo,
814                                       const SDLoc &dl, SDValue &Chain,
815                                       SDValue *Flag, const Value *V) const {
816   // A Value with type {} or [0 x %t] needs no registers.
817   if (ValueVTs.empty())
818     return SDValue();
819 
820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
821 
822   // Assemble the legal parts into the final values.
823   SmallVector<SDValue, 4> Values(ValueVTs.size());
824   SmallVector<SDValue, 8> Parts;
825   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
826     // Copy the legal parts from the registers.
827     EVT ValueVT = ValueVTs[Value];
828     unsigned NumRegs = RegCount[Value];
829     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
830                                           *DAG.getContext(),
831                                           CallConv.getValue(), RegVTs[Value])
832                                     : RegVTs[Value];
833 
834     Parts.resize(NumRegs);
835     for (unsigned i = 0; i != NumRegs; ++i) {
836       SDValue P;
837       if (!Flag) {
838         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
839       } else {
840         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
841         *Flag = P.getValue(2);
842       }
843 
844       Chain = P.getValue(1);
845       Parts[i] = P;
846 
847       // If the source register was virtual and if we know something about it,
848       // add an assert node.
849       if (!Register::isVirtualRegister(Regs[Part + i]) ||
850           !RegisterVT.isInteger())
851         continue;
852 
853       const FunctionLoweringInfo::LiveOutInfo *LOI =
854         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
855       if (!LOI)
856         continue;
857 
858       unsigned RegSize = RegisterVT.getScalarSizeInBits();
859       unsigned NumSignBits = LOI->NumSignBits;
860       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
861 
862       if (NumZeroBits == RegSize) {
863         // The current value is a zero.
864         // Explicitly express that as it would be easier for
865         // optimizations to kick in.
866         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
867         continue;
868       }
869 
870       // FIXME: We capture more information than the dag can represent.  For
871       // now, just use the tightest assertzext/assertsext possible.
872       bool isSExt;
873       EVT FromVT(MVT::Other);
874       if (NumZeroBits) {
875         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
876         isSExt = false;
877       } else if (NumSignBits > 1) {
878         FromVT =
879             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
880         isSExt = true;
881       } else {
882         continue;
883       }
884       // Add an assertion node.
885       assert(FromVT != MVT::Other);
886       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
887                              RegisterVT, P, DAG.getValueType(FromVT));
888     }
889 
890     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
891                                      RegisterVT, ValueVT, V, CallConv);
892     Part += NumRegs;
893     Parts.clear();
894   }
895 
896   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
897 }
898 
899 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
900                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
901                                  const Value *V,
902                                  ISD::NodeType PreferredExtendType) const {
903   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
904   ISD::NodeType ExtendKind = PreferredExtendType;
905 
906   // Get the list of the values's legal parts.
907   unsigned NumRegs = Regs.size();
908   SmallVector<SDValue, 8> Parts(NumRegs);
909   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
910     unsigned NumParts = RegCount[Value];
911 
912     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
913                                           *DAG.getContext(),
914                                           CallConv.getValue(), RegVTs[Value])
915                                     : RegVTs[Value];
916 
917     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
918       ExtendKind = ISD::ZERO_EXTEND;
919 
920     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
921                    NumParts, RegisterVT, V, CallConv, ExtendKind);
922     Part += NumParts;
923   }
924 
925   // Copy the parts into the registers.
926   SmallVector<SDValue, 8> Chains(NumRegs);
927   for (unsigned i = 0; i != NumRegs; ++i) {
928     SDValue Part;
929     if (!Flag) {
930       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
931     } else {
932       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
933       *Flag = Part.getValue(1);
934     }
935 
936     Chains[i] = Part.getValue(0);
937   }
938 
939   if (NumRegs == 1 || Flag)
940     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
941     // flagged to it. That is the CopyToReg nodes and the user are considered
942     // a single scheduling unit. If we create a TokenFactor and return it as
943     // chain, then the TokenFactor is both a predecessor (operand) of the
944     // user as well as a successor (the TF operands are flagged to the user).
945     // c1, f1 = CopyToReg
946     // c2, f2 = CopyToReg
947     // c3     = TokenFactor c1, c2
948     // ...
949     //        = op c3, ..., f2
950     Chain = Chains[NumRegs-1];
951   else
952     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
953 }
954 
955 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
956                                         unsigned MatchingIdx, const SDLoc &dl,
957                                         SelectionDAG &DAG,
958                                         std::vector<SDValue> &Ops) const {
959   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
960 
961   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
962   if (HasMatching)
963     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
964   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
965     // Put the register class of the virtual registers in the flag word.  That
966     // way, later passes can recompute register class constraints for inline
967     // assembly as well as normal instructions.
968     // Don't do this for tied operands that can use the regclass information
969     // from the def.
970     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
971     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
972     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
973   }
974 
975   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
976   Ops.push_back(Res);
977 
978   if (Code == InlineAsm::Kind_Clobber) {
979     // Clobbers should always have a 1:1 mapping with registers, and may
980     // reference registers that have illegal (e.g. vector) types. Hence, we
981     // shouldn't try to apply any sort of splitting logic to them.
982     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
983            "No 1:1 mapping from clobbers to regs?");
984     Register SP = TLI.getStackPointerRegisterToSaveRestore();
985     (void)SP;
986     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
987       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
988       assert(
989           (Regs[I] != SP ||
990            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
991           "If we clobbered the stack pointer, MFI should know about it.");
992     }
993     return;
994   }
995 
996   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
997     MVT RegisterVT = RegVTs[Value];
998     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
999                                            RegisterVT);
1000     for (unsigned i = 0; i != NumRegs; ++i) {
1001       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1002       unsigned TheReg = Regs[Reg++];
1003       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1004     }
1005   }
1006 }
1007 
1008 SmallVector<std::pair<unsigned, TypeSize>, 4>
1009 RegsForValue::getRegsAndSizes() const {
1010   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1011   unsigned I = 0;
1012   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1013     unsigned RegCount = std::get<0>(CountAndVT);
1014     MVT RegisterVT = std::get<1>(CountAndVT);
1015     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1016     for (unsigned E = I + RegCount; I != E; ++I)
1017       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1018   }
1019   return OutVec;
1020 }
1021 
1022 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1023                                const TargetLibraryInfo *li) {
1024   AA = aa;
1025   GFI = gfi;
1026   LibInfo = li;
1027   DL = &DAG.getDataLayout();
1028   Context = DAG.getContext();
1029   LPadToCallSiteMap.clear();
1030   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1031 }
1032 
1033 void SelectionDAGBuilder::clear() {
1034   NodeMap.clear();
1035   UnusedArgNodeMap.clear();
1036   PendingLoads.clear();
1037   PendingExports.clear();
1038   PendingConstrainedFP.clear();
1039   PendingConstrainedFPStrict.clear();
1040   CurInst = nullptr;
1041   HasTailCall = false;
1042   SDNodeOrder = LowestSDNodeOrder;
1043   StatepointLowering.clear();
1044 }
1045 
1046 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1047   DanglingDebugInfoMap.clear();
1048 }
1049 
1050 // Update DAG root to include dependencies on Pending chains.
1051 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1052   SDValue Root = DAG.getRoot();
1053 
1054   if (Pending.empty())
1055     return Root;
1056 
1057   // Add current root to PendingChains, unless we already indirectly
1058   // depend on it.
1059   if (Root.getOpcode() != ISD::EntryToken) {
1060     unsigned i = 0, e = Pending.size();
1061     for (; i != e; ++i) {
1062       assert(Pending[i].getNode()->getNumOperands() > 1);
1063       if (Pending[i].getNode()->getOperand(0) == Root)
1064         break;  // Don't add the root if we already indirectly depend on it.
1065     }
1066 
1067     if (i == e)
1068       Pending.push_back(Root);
1069   }
1070 
1071   if (Pending.size() == 1)
1072     Root = Pending[0];
1073   else
1074     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1075 
1076   DAG.setRoot(Root);
1077   Pending.clear();
1078   return Root;
1079 }
1080 
1081 SDValue SelectionDAGBuilder::getMemoryRoot() {
1082   return updateRoot(PendingLoads);
1083 }
1084 
1085 SDValue SelectionDAGBuilder::getRoot() {
1086   // Chain up all pending constrained intrinsics together with all
1087   // pending loads, by simply appending them to PendingLoads and
1088   // then calling getMemoryRoot().
1089   PendingLoads.reserve(PendingLoads.size() +
1090                        PendingConstrainedFP.size() +
1091                        PendingConstrainedFPStrict.size());
1092   PendingLoads.append(PendingConstrainedFP.begin(),
1093                       PendingConstrainedFP.end());
1094   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1095                       PendingConstrainedFPStrict.end());
1096   PendingConstrainedFP.clear();
1097   PendingConstrainedFPStrict.clear();
1098   return getMemoryRoot();
1099 }
1100 
1101 SDValue SelectionDAGBuilder::getControlRoot() {
1102   // We need to emit pending fpexcept.strict constrained intrinsics,
1103   // so append them to the PendingExports list.
1104   PendingExports.append(PendingConstrainedFPStrict.begin(),
1105                         PendingConstrainedFPStrict.end());
1106   PendingConstrainedFPStrict.clear();
1107   return updateRoot(PendingExports);
1108 }
1109 
1110 void SelectionDAGBuilder::visit(const Instruction &I) {
1111   // Set up outgoing PHI node register values before emitting the terminator.
1112   if (I.isTerminator()) {
1113     HandlePHINodesInSuccessorBlocks(I.getParent());
1114   }
1115 
1116   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1117   if (!isa<DbgInfoIntrinsic>(I))
1118     ++SDNodeOrder;
1119 
1120   CurInst = &I;
1121 
1122   visit(I.getOpcode(), I);
1123 
1124   if (!I.isTerminator() && !HasTailCall &&
1125       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1126     CopyToExportRegsIfNeeded(&I);
1127 
1128   CurInst = nullptr;
1129 }
1130 
1131 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1132   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1133 }
1134 
1135 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1136   // Note: this doesn't use InstVisitor, because it has to work with
1137   // ConstantExpr's in addition to instructions.
1138   switch (Opcode) {
1139   default: llvm_unreachable("Unknown instruction type encountered!");
1140     // Build the switch statement using the Instruction.def file.
1141 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1142     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1143 #include "llvm/IR/Instruction.def"
1144   }
1145 }
1146 
1147 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1148                                                DebugLoc DL, unsigned Order) {
1149   // We treat variadic dbg_values differently at this stage.
1150   if (DI->hasArgList()) {
1151     // For variadic dbg_values we will now insert an undef.
1152     // FIXME: We can potentially recover these!
1153     SmallVector<SDDbgOperand, 2> Locs;
1154     for (const Value *V : DI->getValues()) {
1155       auto Undef = UndefValue::get(V->getType());
1156       Locs.push_back(SDDbgOperand::fromConst(Undef));
1157     }
1158     SDDbgValue *SDV = DAG.getDbgValueList(
1159         DI->getVariable(), DI->getExpression(), Locs, {},
1160         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1161     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1162   } else {
1163     // TODO: Dangling debug info will eventually either be resolved or produce
1164     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1165     // between the original dbg.value location and its resolved DBG_VALUE,
1166     // which we should ideally fill with an extra Undef DBG_VALUE.
1167     assert(DI->getNumVariableLocationOps() == 1 &&
1168            "DbgValueInst without an ArgList should have a single location "
1169            "operand.");
1170     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1171   }
1172 }
1173 
1174 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1175                                                 const DIExpression *Expr) {
1176   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1177     const DbgValueInst *DI = DDI.getDI();
1178     DIVariable *DanglingVariable = DI->getVariable();
1179     DIExpression *DanglingExpr = DI->getExpression();
1180     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1181       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1182       return true;
1183     }
1184     return false;
1185   };
1186 
1187   for (auto &DDIMI : DanglingDebugInfoMap) {
1188     DanglingDebugInfoVector &DDIV = DDIMI.second;
1189 
1190     // If debug info is to be dropped, run it through final checks to see
1191     // whether it can be salvaged.
1192     for (auto &DDI : DDIV)
1193       if (isMatchingDbgValue(DDI))
1194         salvageUnresolvedDbgValue(DDI);
1195 
1196     erase_if(DDIV, isMatchingDbgValue);
1197   }
1198 }
1199 
1200 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1201 // generate the debug data structures now that we've seen its definition.
1202 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1203                                                    SDValue Val) {
1204   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1205   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1206     return;
1207 
1208   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1209   for (auto &DDI : DDIV) {
1210     const DbgValueInst *DI = DDI.getDI();
1211     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1212     assert(DI && "Ill-formed DanglingDebugInfo");
1213     DebugLoc dl = DDI.getdl();
1214     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1215     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1216     DILocalVariable *Variable = DI->getVariable();
1217     DIExpression *Expr = DI->getExpression();
1218     assert(Variable->isValidLocationForIntrinsic(dl) &&
1219            "Expected inlined-at fields to agree");
1220     SDDbgValue *SDV;
1221     if (Val.getNode()) {
1222       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1223       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1224       // we couldn't resolve it directly when examining the DbgValue intrinsic
1225       // in the first place we should not be more successful here). Unless we
1226       // have some test case that prove this to be correct we should avoid
1227       // calling EmitFuncArgumentDbgValue here.
1228       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1229         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1230                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1231         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1232         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1233         // inserted after the definition of Val when emitting the instructions
1234         // after ISel. An alternative could be to teach
1235         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1236         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1237                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1238                    << ValSDNodeOrder << "\n");
1239         SDV = getDbgValue(Val, Variable, Expr, dl,
1240                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1241         DAG.AddDbgValue(SDV, false);
1242       } else
1243         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1244                           << "in EmitFuncArgumentDbgValue\n");
1245     } else {
1246       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1247       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1248       auto SDV =
1249           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1250       DAG.AddDbgValue(SDV, false);
1251     }
1252   }
1253   DDIV.clear();
1254 }
1255 
1256 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1257   // TODO: For the variadic implementation, instead of only checking the fail
1258   // state of `handleDebugValue`, we need know specifically which values were
1259   // invalid, so that we attempt to salvage only those values when processing
1260   // a DIArgList.
1261   assert(!DDI.getDI()->hasArgList() &&
1262          "Not implemented for variadic dbg_values");
1263   Value *V = DDI.getDI()->getValue(0);
1264   DILocalVariable *Var = DDI.getDI()->getVariable();
1265   DIExpression *Expr = DDI.getDI()->getExpression();
1266   DebugLoc DL = DDI.getdl();
1267   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1268   unsigned SDOrder = DDI.getSDNodeOrder();
1269   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1270   // that DW_OP_stack_value is desired.
1271   assert(isa<DbgValueInst>(DDI.getDI()));
1272   bool StackValue = true;
1273 
1274   // Can this Value can be encoded without any further work?
1275   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1276     return;
1277 
1278   // Attempt to salvage back through as many instructions as possible. Bail if
1279   // a non-instruction is seen, such as a constant expression or global
1280   // variable. FIXME: Further work could recover those too.
1281   while (isa<Instruction>(V)) {
1282     Instruction &VAsInst = *cast<Instruction>(V);
1283     // Temporary "0", awaiting real implementation.
1284     SmallVector<uint64_t, 16> Ops;
1285     SmallVector<Value *, 4> AdditionalValues;
1286     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1287                              AdditionalValues);
1288     // If we cannot salvage any further, and haven't yet found a suitable debug
1289     // expression, bail out.
1290     if (!V)
1291       break;
1292 
1293     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1294     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1295     // here for variadic dbg_values, remove that condition.
1296     if (!AdditionalValues.empty())
1297       break;
1298 
1299     // New value and expr now represent this debuginfo.
1300     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1301 
1302     // Some kind of simplification occurred: check whether the operand of the
1303     // salvaged debug expression can be encoded in this DAG.
1304     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1305                          /*IsVariadic=*/false)) {
1306       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1307                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1308       return;
1309     }
1310   }
1311 
1312   // This was the final opportunity to salvage this debug information, and it
1313   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1314   // any earlier variable location.
1315   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1316   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1317   DAG.AddDbgValue(SDV, false);
1318 
1319   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1320                     << "\n");
1321   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1322                     << "\n");
1323 }
1324 
1325 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1326                                            DILocalVariable *Var,
1327                                            DIExpression *Expr, DebugLoc dl,
1328                                            DebugLoc InstDL, unsigned Order,
1329                                            bool IsVariadic) {
1330   if (Values.empty())
1331     return true;
1332   SmallVector<SDDbgOperand> LocationOps;
1333   SmallVector<SDNode *> Dependencies;
1334   for (const Value *V : Values) {
1335     // Constant value.
1336     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1337         isa<ConstantPointerNull>(V)) {
1338       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1339       continue;
1340     }
1341 
1342     // If the Value is a frame index, we can create a FrameIndex debug value
1343     // without relying on the DAG at all.
1344     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1345       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1346       if (SI != FuncInfo.StaticAllocaMap.end()) {
1347         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1348         continue;
1349       }
1350     }
1351 
1352     // Do not use getValue() in here; we don't want to generate code at
1353     // this point if it hasn't been done yet.
1354     SDValue N = NodeMap[V];
1355     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1356       N = UnusedArgNodeMap[V];
1357     if (N.getNode()) {
1358       // Only emit func arg dbg value for non-variadic dbg.values for now.
1359       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1360         return true;
1361       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1362         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1363         // describe stack slot locations.
1364         //
1365         // Consider "int x = 0; int *px = &x;". There are two kinds of
1366         // interesting debug values here after optimization:
1367         //
1368         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1369         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1370         //
1371         // Both describe the direct values of their associated variables.
1372         Dependencies.push_back(N.getNode());
1373         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1374         continue;
1375       }
1376       LocationOps.emplace_back(
1377           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1378       continue;
1379     }
1380 
1381     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1382     // Special rules apply for the first dbg.values of parameter variables in a
1383     // function. Identify them by the fact they reference Argument Values, that
1384     // they're parameters, and they are parameters of the current function. We
1385     // need to let them dangle until they get an SDNode.
1386     bool IsParamOfFunc =
1387         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1388     if (IsParamOfFunc)
1389       return false;
1390 
1391     // The value is not used in this block yet (or it would have an SDNode).
1392     // We still want the value to appear for the user if possible -- if it has
1393     // an associated VReg, we can refer to that instead.
1394     auto VMI = FuncInfo.ValueMap.find(V);
1395     if (VMI != FuncInfo.ValueMap.end()) {
1396       unsigned Reg = VMI->second;
1397       // If this is a PHI node, it may be split up into several MI PHI nodes
1398       // (in FunctionLoweringInfo::set).
1399       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1400                        V->getType(), None);
1401       if (RFV.occupiesMultipleRegs()) {
1402         // FIXME: We could potentially support variadic dbg_values here.
1403         if (IsVariadic)
1404           return false;
1405         unsigned Offset = 0;
1406         unsigned BitsToDescribe = 0;
1407         if (auto VarSize = Var->getSizeInBits())
1408           BitsToDescribe = *VarSize;
1409         if (auto Fragment = Expr->getFragmentInfo())
1410           BitsToDescribe = Fragment->SizeInBits;
1411         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1412           // Bail out if all bits are described already.
1413           if (Offset >= BitsToDescribe)
1414             break;
1415           // TODO: handle scalable vectors.
1416           unsigned RegisterSize = RegAndSize.second;
1417           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1418                                       ? BitsToDescribe - Offset
1419                                       : RegisterSize;
1420           auto FragmentExpr = DIExpression::createFragmentExpression(
1421               Expr, Offset, FragmentSize);
1422           if (!FragmentExpr)
1423             continue;
1424           SDDbgValue *SDV = DAG.getVRegDbgValue(
1425               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1426           DAG.AddDbgValue(SDV, false);
1427           Offset += RegisterSize;
1428         }
1429         return true;
1430       }
1431       // We can use simple vreg locations for variadic dbg_values as well.
1432       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1433       continue;
1434     }
1435     // We failed to create a SDDbgOperand for V.
1436     return false;
1437   }
1438 
1439   // We have created a SDDbgOperand for each Value in Values.
1440   // Should use Order instead of SDNodeOrder?
1441   assert(!LocationOps.empty());
1442   SDDbgValue *SDV =
1443       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1444                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1445   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1446   return true;
1447 }
1448 
1449 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1450   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1451   for (auto &Pair : DanglingDebugInfoMap)
1452     for (auto &DDI : Pair.second)
1453       salvageUnresolvedDbgValue(DDI);
1454   clearDanglingDebugInfo();
1455 }
1456 
1457 /// getCopyFromRegs - If there was virtual register allocated for the value V
1458 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1459 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1460   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1461   SDValue Result;
1462 
1463   if (It != FuncInfo.ValueMap.end()) {
1464     Register InReg = It->second;
1465 
1466     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1467                      DAG.getDataLayout(), InReg, Ty,
1468                      None); // This is not an ABI copy.
1469     SDValue Chain = DAG.getEntryNode();
1470     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1471                                  V);
1472     resolveDanglingDebugInfo(V, Result);
1473   }
1474 
1475   return Result;
1476 }
1477 
1478 /// getValue - Return an SDValue for the given Value.
1479 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1480   // If we already have an SDValue for this value, use it. It's important
1481   // to do this first, so that we don't create a CopyFromReg if we already
1482   // have a regular SDValue.
1483   SDValue &N = NodeMap[V];
1484   if (N.getNode()) return N;
1485 
1486   // If there's a virtual register allocated and initialized for this
1487   // value, use it.
1488   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1489     return copyFromReg;
1490 
1491   // Otherwise create a new SDValue and remember it.
1492   SDValue Val = getValueImpl(V);
1493   NodeMap[V] = Val;
1494   resolveDanglingDebugInfo(V, Val);
1495   return Val;
1496 }
1497 
1498 /// getNonRegisterValue - Return an SDValue for the given Value, but
1499 /// don't look in FuncInfo.ValueMap for a virtual register.
1500 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1501   // If we already have an SDValue for this value, use it.
1502   SDValue &N = NodeMap[V];
1503   if (N.getNode()) {
1504     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1505       // Remove the debug location from the node as the node is about to be used
1506       // in a location which may differ from the original debug location.  This
1507       // is relevant to Constant and ConstantFP nodes because they can appear
1508       // as constant expressions inside PHI nodes.
1509       N->setDebugLoc(DebugLoc());
1510     }
1511     return N;
1512   }
1513 
1514   // Otherwise create a new SDValue and remember it.
1515   SDValue Val = getValueImpl(V);
1516   NodeMap[V] = Val;
1517   resolveDanglingDebugInfo(V, Val);
1518   return Val;
1519 }
1520 
1521 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1522 /// Create an SDValue for the given value.
1523 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1525 
1526   if (const Constant *C = dyn_cast<Constant>(V)) {
1527     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1528 
1529     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1530       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1531 
1532     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1533       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1534 
1535     if (isa<ConstantPointerNull>(C)) {
1536       unsigned AS = V->getType()->getPointerAddressSpace();
1537       return DAG.getConstant(0, getCurSDLoc(),
1538                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1539     }
1540 
1541     if (match(C, m_VScale(DAG.getDataLayout())))
1542       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1543 
1544     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1545       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1546 
1547     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1548       return DAG.getUNDEF(VT);
1549 
1550     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1551       visit(CE->getOpcode(), *CE);
1552       SDValue N1 = NodeMap[V];
1553       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1554       return N1;
1555     }
1556 
1557     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1558       SmallVector<SDValue, 4> Constants;
1559       for (const Use &U : C->operands()) {
1560         SDNode *Val = getValue(U).getNode();
1561         // If the operand is an empty aggregate, there are no values.
1562         if (!Val) continue;
1563         // Add each leaf value from the operand to the Constants list
1564         // to form a flattened list of all the values.
1565         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1566           Constants.push_back(SDValue(Val, i));
1567       }
1568 
1569       return DAG.getMergeValues(Constants, getCurSDLoc());
1570     }
1571 
1572     if (const ConstantDataSequential *CDS =
1573           dyn_cast<ConstantDataSequential>(C)) {
1574       SmallVector<SDValue, 4> Ops;
1575       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1576         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1577         // Add each leaf value from the operand to the Constants list
1578         // to form a flattened list of all the values.
1579         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1580           Ops.push_back(SDValue(Val, i));
1581       }
1582 
1583       if (isa<ArrayType>(CDS->getType()))
1584         return DAG.getMergeValues(Ops, getCurSDLoc());
1585       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1586     }
1587 
1588     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1589       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1590              "Unknown struct or array constant!");
1591 
1592       SmallVector<EVT, 4> ValueVTs;
1593       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1594       unsigned NumElts = ValueVTs.size();
1595       if (NumElts == 0)
1596         return SDValue(); // empty struct
1597       SmallVector<SDValue, 4> Constants(NumElts);
1598       for (unsigned i = 0; i != NumElts; ++i) {
1599         EVT EltVT = ValueVTs[i];
1600         if (isa<UndefValue>(C))
1601           Constants[i] = DAG.getUNDEF(EltVT);
1602         else if (EltVT.isFloatingPoint())
1603           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1604         else
1605           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1606       }
1607 
1608       return DAG.getMergeValues(Constants, getCurSDLoc());
1609     }
1610 
1611     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1612       return DAG.getBlockAddress(BA, VT);
1613 
1614     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1615       return getValue(Equiv->getGlobalValue());
1616 
1617     VectorType *VecTy = cast<VectorType>(V->getType());
1618 
1619     // Now that we know the number and type of the elements, get that number of
1620     // elements into the Ops array based on what kind of constant it is.
1621     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1622       SmallVector<SDValue, 16> Ops;
1623       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1624       for (unsigned i = 0; i != NumElements; ++i)
1625         Ops.push_back(getValue(CV->getOperand(i)));
1626 
1627       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1628     } else if (isa<ConstantAggregateZero>(C)) {
1629       EVT EltVT =
1630           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1631 
1632       SDValue Op;
1633       if (EltVT.isFloatingPoint())
1634         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1635       else
1636         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1637 
1638       if (isa<ScalableVectorType>(VecTy))
1639         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1640       else {
1641         SmallVector<SDValue, 16> Ops;
1642         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1643         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1644       }
1645     }
1646     llvm_unreachable("Unknown vector constant");
1647   }
1648 
1649   // If this is a static alloca, generate it as the frameindex instead of
1650   // computation.
1651   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1652     DenseMap<const AllocaInst*, int>::iterator SI =
1653       FuncInfo.StaticAllocaMap.find(AI);
1654     if (SI != FuncInfo.StaticAllocaMap.end())
1655       return DAG.getFrameIndex(SI->second,
1656                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1657   }
1658 
1659   // If this is an instruction which fast-isel has deferred, select it now.
1660   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1661     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1662 
1663     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1664                      Inst->getType(), None);
1665     SDValue Chain = DAG.getEntryNode();
1666     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1667   }
1668 
1669   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1670     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1671   }
1672   llvm_unreachable("Can't get register for value!");
1673 }
1674 
1675 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1676   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1677   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1678   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1679   bool IsSEH = isAsynchronousEHPersonality(Pers);
1680   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1681   if (!IsSEH)
1682     CatchPadMBB->setIsEHScopeEntry();
1683   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1684   if (IsMSVCCXX || IsCoreCLR)
1685     CatchPadMBB->setIsEHFuncletEntry();
1686 }
1687 
1688 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1689   // Update machine-CFG edge.
1690   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1691   FuncInfo.MBB->addSuccessor(TargetMBB);
1692   TargetMBB->setIsEHCatchretTarget(true);
1693   DAG.getMachineFunction().setHasEHCatchret(true);
1694 
1695   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1696   bool IsSEH = isAsynchronousEHPersonality(Pers);
1697   if (IsSEH) {
1698     // If this is not a fall-through branch or optimizations are switched off,
1699     // emit the branch.
1700     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1701         TM.getOptLevel() == CodeGenOpt::None)
1702       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1703                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1704     return;
1705   }
1706 
1707   // Figure out the funclet membership for the catchret's successor.
1708   // This will be used by the FuncletLayout pass to determine how to order the
1709   // BB's.
1710   // A 'catchret' returns to the outer scope's color.
1711   Value *ParentPad = I.getCatchSwitchParentPad();
1712   const BasicBlock *SuccessorColor;
1713   if (isa<ConstantTokenNone>(ParentPad))
1714     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1715   else
1716     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1717   assert(SuccessorColor && "No parent funclet for catchret!");
1718   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1719   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1720 
1721   // Create the terminator node.
1722   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1723                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1724                             DAG.getBasicBlock(SuccessorColorMBB));
1725   DAG.setRoot(Ret);
1726 }
1727 
1728 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1729   // Don't emit any special code for the cleanuppad instruction. It just marks
1730   // the start of an EH scope/funclet.
1731   FuncInfo.MBB->setIsEHScopeEntry();
1732   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1733   if (Pers != EHPersonality::Wasm_CXX) {
1734     FuncInfo.MBB->setIsEHFuncletEntry();
1735     FuncInfo.MBB->setIsCleanupFuncletEntry();
1736   }
1737 }
1738 
1739 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1740 // not match, it is OK to add only the first unwind destination catchpad to the
1741 // successors, because there will be at least one invoke instruction within the
1742 // catch scope that points to the next unwind destination, if one exists, so
1743 // CFGSort cannot mess up with BB sorting order.
1744 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1745 // call within them, and catchpads only consisting of 'catch (...)' have a
1746 // '__cxa_end_catch' call within them, both of which generate invokes in case
1747 // the next unwind destination exists, i.e., the next unwind destination is not
1748 // the caller.)
1749 //
1750 // Having at most one EH pad successor is also simpler and helps later
1751 // transformations.
1752 //
1753 // For example,
1754 // current:
1755 //   invoke void @foo to ... unwind label %catch.dispatch
1756 // catch.dispatch:
1757 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1758 // catch.start:
1759 //   ...
1760 //   ... in this BB or some other child BB dominated by this BB there will be an
1761 //   invoke that points to 'next' BB as an unwind destination
1762 //
1763 // next: ; We don't need to add this to 'current' BB's successor
1764 //   ...
1765 static void findWasmUnwindDestinations(
1766     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1767     BranchProbability Prob,
1768     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1769         &UnwindDests) {
1770   while (EHPadBB) {
1771     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1772     if (isa<CleanupPadInst>(Pad)) {
1773       // Stop on cleanup pads.
1774       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1775       UnwindDests.back().first->setIsEHScopeEntry();
1776       break;
1777     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1778       // Add the catchpad handlers to the possible destinations. We don't
1779       // continue to the unwind destination of the catchswitch for wasm.
1780       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1781         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1782         UnwindDests.back().first->setIsEHScopeEntry();
1783       }
1784       break;
1785     } else {
1786       continue;
1787     }
1788   }
1789 }
1790 
1791 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1792 /// many places it could ultimately go. In the IR, we have a single unwind
1793 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1794 /// This function skips over imaginary basic blocks that hold catchswitch
1795 /// instructions, and finds all the "real" machine
1796 /// basic block destinations. As those destinations may not be successors of
1797 /// EHPadBB, here we also calculate the edge probability to those destinations.
1798 /// The passed-in Prob is the edge probability to EHPadBB.
1799 static void findUnwindDestinations(
1800     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1801     BranchProbability Prob,
1802     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1803         &UnwindDests) {
1804   EHPersonality Personality =
1805     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1806   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1807   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1808   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1809   bool IsSEH = isAsynchronousEHPersonality(Personality);
1810 
1811   if (IsWasmCXX) {
1812     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1813     assert(UnwindDests.size() <= 1 &&
1814            "There should be at most one unwind destination for wasm");
1815     return;
1816   }
1817 
1818   while (EHPadBB) {
1819     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1820     BasicBlock *NewEHPadBB = nullptr;
1821     if (isa<LandingPadInst>(Pad)) {
1822       // Stop on landingpads. They are not funclets.
1823       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1824       break;
1825     } else if (isa<CleanupPadInst>(Pad)) {
1826       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1827       // personalities.
1828       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1829       UnwindDests.back().first->setIsEHScopeEntry();
1830       UnwindDests.back().first->setIsEHFuncletEntry();
1831       break;
1832     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1833       // Add the catchpad handlers to the possible destinations.
1834       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1835         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1836         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1837         if (IsMSVCCXX || IsCoreCLR)
1838           UnwindDests.back().first->setIsEHFuncletEntry();
1839         if (!IsSEH)
1840           UnwindDests.back().first->setIsEHScopeEntry();
1841       }
1842       NewEHPadBB = CatchSwitch->getUnwindDest();
1843     } else {
1844       continue;
1845     }
1846 
1847     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1848     if (BPI && NewEHPadBB)
1849       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1850     EHPadBB = NewEHPadBB;
1851   }
1852 }
1853 
1854 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1855   // Update successor info.
1856   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1857   auto UnwindDest = I.getUnwindDest();
1858   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1859   BranchProbability UnwindDestProb =
1860       (BPI && UnwindDest)
1861           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1862           : BranchProbability::getZero();
1863   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1864   for (auto &UnwindDest : UnwindDests) {
1865     UnwindDest.first->setIsEHPad();
1866     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1867   }
1868   FuncInfo.MBB->normalizeSuccProbs();
1869 
1870   // Create the terminator node.
1871   SDValue Ret =
1872       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1873   DAG.setRoot(Ret);
1874 }
1875 
1876 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1877   report_fatal_error("visitCatchSwitch not yet implemented!");
1878 }
1879 
1880 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1881   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1882   auto &DL = DAG.getDataLayout();
1883   SDValue Chain = getControlRoot();
1884   SmallVector<ISD::OutputArg, 8> Outs;
1885   SmallVector<SDValue, 8> OutVals;
1886 
1887   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1888   // lower
1889   //
1890   //   %val = call <ty> @llvm.experimental.deoptimize()
1891   //   ret <ty> %val
1892   //
1893   // differently.
1894   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1895     LowerDeoptimizingReturn();
1896     return;
1897   }
1898 
1899   if (!FuncInfo.CanLowerReturn) {
1900     unsigned DemoteReg = FuncInfo.DemoteRegister;
1901     const Function *F = I.getParent()->getParent();
1902 
1903     // Emit a store of the return value through the virtual register.
1904     // Leave Outs empty so that LowerReturn won't try to load return
1905     // registers the usual way.
1906     SmallVector<EVT, 1> PtrValueVTs;
1907     ComputeValueVTs(TLI, DL,
1908                     F->getReturnType()->getPointerTo(
1909                         DAG.getDataLayout().getAllocaAddrSpace()),
1910                     PtrValueVTs);
1911 
1912     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1913                                         DemoteReg, PtrValueVTs[0]);
1914     SDValue RetOp = getValue(I.getOperand(0));
1915 
1916     SmallVector<EVT, 4> ValueVTs, MemVTs;
1917     SmallVector<uint64_t, 4> Offsets;
1918     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1919                     &Offsets);
1920     unsigned NumValues = ValueVTs.size();
1921 
1922     SmallVector<SDValue, 4> Chains(NumValues);
1923     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1924     for (unsigned i = 0; i != NumValues; ++i) {
1925       // An aggregate return value cannot wrap around the address space, so
1926       // offsets to its parts don't wrap either.
1927       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1928                                            TypeSize::Fixed(Offsets[i]));
1929 
1930       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1931       if (MemVTs[i] != ValueVTs[i])
1932         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1933       Chains[i] = DAG.getStore(
1934           Chain, getCurSDLoc(), Val,
1935           // FIXME: better loc info would be nice.
1936           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1937           commonAlignment(BaseAlign, Offsets[i]));
1938     }
1939 
1940     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1941                         MVT::Other, Chains);
1942   } else if (I.getNumOperands() != 0) {
1943     SmallVector<EVT, 4> ValueVTs;
1944     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1945     unsigned NumValues = ValueVTs.size();
1946     if (NumValues) {
1947       SDValue RetOp = getValue(I.getOperand(0));
1948 
1949       const Function *F = I.getParent()->getParent();
1950 
1951       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1952           I.getOperand(0)->getType(), F->getCallingConv(),
1953           /*IsVarArg*/ false, DL);
1954 
1955       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1956       if (F->getAttributes().hasRetAttr(Attribute::SExt))
1957         ExtendKind = ISD::SIGN_EXTEND;
1958       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
1959         ExtendKind = ISD::ZERO_EXTEND;
1960 
1961       LLVMContext &Context = F->getContext();
1962       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
1963 
1964       for (unsigned j = 0; j != NumValues; ++j) {
1965         EVT VT = ValueVTs[j];
1966 
1967         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1968           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1969 
1970         CallingConv::ID CC = F->getCallingConv();
1971 
1972         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1973         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1974         SmallVector<SDValue, 4> Parts(NumParts);
1975         getCopyToParts(DAG, getCurSDLoc(),
1976                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1977                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1978 
1979         // 'inreg' on function refers to return value
1980         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1981         if (RetInReg)
1982           Flags.setInReg();
1983 
1984         if (I.getOperand(0)->getType()->isPointerTy()) {
1985           Flags.setPointer();
1986           Flags.setPointerAddrSpace(
1987               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1988         }
1989 
1990         if (NeedsRegBlock) {
1991           Flags.setInConsecutiveRegs();
1992           if (j == NumValues - 1)
1993             Flags.setInConsecutiveRegsLast();
1994         }
1995 
1996         // Propagate extension type if any
1997         if (ExtendKind == ISD::SIGN_EXTEND)
1998           Flags.setSExt();
1999         else if (ExtendKind == ISD::ZERO_EXTEND)
2000           Flags.setZExt();
2001 
2002         for (unsigned i = 0; i < NumParts; ++i) {
2003           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
2004                                         VT, /*isfixed=*/true, 0, 0));
2005           OutVals.push_back(Parts[i]);
2006         }
2007       }
2008     }
2009   }
2010 
2011   // Push in swifterror virtual register as the last element of Outs. This makes
2012   // sure swifterror virtual register will be returned in the swifterror
2013   // physical register.
2014   const Function *F = I.getParent()->getParent();
2015   if (TLI.supportSwiftError() &&
2016       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2017     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2018     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2019     Flags.setSwiftError();
2020     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
2021                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
2022                                   true /*isfixed*/, 1 /*origidx*/,
2023                                   0 /*partOffs*/));
2024     // Create SDNode for the swifterror virtual register.
2025     OutVals.push_back(
2026         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2027                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2028                         EVT(TLI.getPointerTy(DL))));
2029   }
2030 
2031   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2032   CallingConv::ID CallConv =
2033     DAG.getMachineFunction().getFunction().getCallingConv();
2034   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2035       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2036 
2037   // Verify that the target's LowerReturn behaved as expected.
2038   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2039          "LowerReturn didn't return a valid chain!");
2040 
2041   // Update the DAG with the new chain value resulting from return lowering.
2042   DAG.setRoot(Chain);
2043 }
2044 
2045 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2046 /// created for it, emit nodes to copy the value into the virtual
2047 /// registers.
2048 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2049   // Skip empty types
2050   if (V->getType()->isEmptyTy())
2051     return;
2052 
2053   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2054   if (VMI != FuncInfo.ValueMap.end()) {
2055     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2056     CopyValueToVirtualRegister(V, VMI->second);
2057   }
2058 }
2059 
2060 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2061 /// the current basic block, add it to ValueMap now so that we'll get a
2062 /// CopyTo/FromReg.
2063 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2064   // No need to export constants.
2065   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2066 
2067   // Already exported?
2068   if (FuncInfo.isExportedInst(V)) return;
2069 
2070   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2071   CopyValueToVirtualRegister(V, Reg);
2072 }
2073 
2074 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2075                                                      const BasicBlock *FromBB) {
2076   // The operands of the setcc have to be in this block.  We don't know
2077   // how to export them from some other block.
2078   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2079     // Can export from current BB.
2080     if (VI->getParent() == FromBB)
2081       return true;
2082 
2083     // Is already exported, noop.
2084     return FuncInfo.isExportedInst(V);
2085   }
2086 
2087   // If this is an argument, we can export it if the BB is the entry block or
2088   // if it is already exported.
2089   if (isa<Argument>(V)) {
2090     if (FromBB->isEntryBlock())
2091       return true;
2092 
2093     // Otherwise, can only export this if it is already exported.
2094     return FuncInfo.isExportedInst(V);
2095   }
2096 
2097   // Otherwise, constants can always be exported.
2098   return true;
2099 }
2100 
2101 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2102 BranchProbability
2103 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2104                                         const MachineBasicBlock *Dst) const {
2105   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2106   const BasicBlock *SrcBB = Src->getBasicBlock();
2107   const BasicBlock *DstBB = Dst->getBasicBlock();
2108   if (!BPI) {
2109     // If BPI is not available, set the default probability as 1 / N, where N is
2110     // the number of successors.
2111     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2112     return BranchProbability(1, SuccSize);
2113   }
2114   return BPI->getEdgeProbability(SrcBB, DstBB);
2115 }
2116 
2117 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2118                                                MachineBasicBlock *Dst,
2119                                                BranchProbability Prob) {
2120   if (!FuncInfo.BPI)
2121     Src->addSuccessorWithoutProb(Dst);
2122   else {
2123     if (Prob.isUnknown())
2124       Prob = getEdgeProbability(Src, Dst);
2125     Src->addSuccessor(Dst, Prob);
2126   }
2127 }
2128 
2129 static bool InBlock(const Value *V, const BasicBlock *BB) {
2130   if (const Instruction *I = dyn_cast<Instruction>(V))
2131     return I->getParent() == BB;
2132   return true;
2133 }
2134 
2135 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2136 /// This function emits a branch and is used at the leaves of an OR or an
2137 /// AND operator tree.
2138 void
2139 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2140                                                   MachineBasicBlock *TBB,
2141                                                   MachineBasicBlock *FBB,
2142                                                   MachineBasicBlock *CurBB,
2143                                                   MachineBasicBlock *SwitchBB,
2144                                                   BranchProbability TProb,
2145                                                   BranchProbability FProb,
2146                                                   bool InvertCond) {
2147   const BasicBlock *BB = CurBB->getBasicBlock();
2148 
2149   // If the leaf of the tree is a comparison, merge the condition into
2150   // the caseblock.
2151   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2152     // The operands of the cmp have to be in this block.  We don't know
2153     // how to export them from some other block.  If this is the first block
2154     // of the sequence, no exporting is needed.
2155     if (CurBB == SwitchBB ||
2156         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2157          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2158       ISD::CondCode Condition;
2159       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2160         ICmpInst::Predicate Pred =
2161             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2162         Condition = getICmpCondCode(Pred);
2163       } else {
2164         const FCmpInst *FC = cast<FCmpInst>(Cond);
2165         FCmpInst::Predicate Pred =
2166             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2167         Condition = getFCmpCondCode(Pred);
2168         if (TM.Options.NoNaNsFPMath)
2169           Condition = getFCmpCodeWithoutNaN(Condition);
2170       }
2171 
2172       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2173                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2174       SL->SwitchCases.push_back(CB);
2175       return;
2176     }
2177   }
2178 
2179   // Create a CaseBlock record representing this branch.
2180   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2181   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2182                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2183   SL->SwitchCases.push_back(CB);
2184 }
2185 
2186 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2187                                                MachineBasicBlock *TBB,
2188                                                MachineBasicBlock *FBB,
2189                                                MachineBasicBlock *CurBB,
2190                                                MachineBasicBlock *SwitchBB,
2191                                                Instruction::BinaryOps Opc,
2192                                                BranchProbability TProb,
2193                                                BranchProbability FProb,
2194                                                bool InvertCond) {
2195   // Skip over not part of the tree and remember to invert op and operands at
2196   // next level.
2197   Value *NotCond;
2198   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2199       InBlock(NotCond, CurBB->getBasicBlock())) {
2200     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2201                          !InvertCond);
2202     return;
2203   }
2204 
2205   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2206   const Value *BOpOp0, *BOpOp1;
2207   // Compute the effective opcode for Cond, taking into account whether it needs
2208   // to be inverted, e.g.
2209   //   and (not (or A, B)), C
2210   // gets lowered as
2211   //   and (and (not A, not B), C)
2212   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2213   if (BOp) {
2214     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2215                ? Instruction::And
2216                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2217                       ? Instruction::Or
2218                       : (Instruction::BinaryOps)0);
2219     if (InvertCond) {
2220       if (BOpc == Instruction::And)
2221         BOpc = Instruction::Or;
2222       else if (BOpc == Instruction::Or)
2223         BOpc = Instruction::And;
2224     }
2225   }
2226 
2227   // If this node is not part of the or/and tree, emit it as a branch.
2228   // Note that all nodes in the tree should have same opcode.
2229   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2230   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2231       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2232       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2233     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2234                                  TProb, FProb, InvertCond);
2235     return;
2236   }
2237 
2238   //  Create TmpBB after CurBB.
2239   MachineFunction::iterator BBI(CurBB);
2240   MachineFunction &MF = DAG.getMachineFunction();
2241   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2242   CurBB->getParent()->insert(++BBI, TmpBB);
2243 
2244   if (Opc == Instruction::Or) {
2245     // Codegen X | Y as:
2246     // BB1:
2247     //   jmp_if_X TBB
2248     //   jmp TmpBB
2249     // TmpBB:
2250     //   jmp_if_Y TBB
2251     //   jmp FBB
2252     //
2253 
2254     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2255     // The requirement is that
2256     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2257     //     = TrueProb for original BB.
2258     // Assuming the original probabilities are A and B, one choice is to set
2259     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2260     // A/(1+B) and 2B/(1+B). This choice assumes that
2261     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2262     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2263     // TmpBB, but the math is more complicated.
2264 
2265     auto NewTrueProb = TProb / 2;
2266     auto NewFalseProb = TProb / 2 + FProb;
2267     // Emit the LHS condition.
2268     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2269                          NewFalseProb, InvertCond);
2270 
2271     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2272     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2273     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2274     // Emit the RHS condition into TmpBB.
2275     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2276                          Probs[1], InvertCond);
2277   } else {
2278     assert(Opc == Instruction::And && "Unknown merge op!");
2279     // Codegen X & Y as:
2280     // BB1:
2281     //   jmp_if_X TmpBB
2282     //   jmp FBB
2283     // TmpBB:
2284     //   jmp_if_Y TBB
2285     //   jmp FBB
2286     //
2287     //  This requires creation of TmpBB after CurBB.
2288 
2289     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2290     // The requirement is that
2291     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2292     //     = FalseProb for original BB.
2293     // Assuming the original probabilities are A and B, one choice is to set
2294     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2295     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2296     // TrueProb for BB1 * FalseProb for TmpBB.
2297 
2298     auto NewTrueProb = TProb + FProb / 2;
2299     auto NewFalseProb = FProb / 2;
2300     // Emit the LHS condition.
2301     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2302                          NewFalseProb, InvertCond);
2303 
2304     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2305     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2306     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2307     // Emit the RHS condition into TmpBB.
2308     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2309                          Probs[1], InvertCond);
2310   }
2311 }
2312 
2313 /// If the set of cases should be emitted as a series of branches, return true.
2314 /// If we should emit this as a bunch of and/or'd together conditions, return
2315 /// false.
2316 bool
2317 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2318   if (Cases.size() != 2) return true;
2319 
2320   // If this is two comparisons of the same values or'd or and'd together, they
2321   // will get folded into a single comparison, so don't emit two blocks.
2322   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2323        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2324       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2325        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2326     return false;
2327   }
2328 
2329   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2330   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2331   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2332       Cases[0].CC == Cases[1].CC &&
2333       isa<Constant>(Cases[0].CmpRHS) &&
2334       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2335     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2336       return false;
2337     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2338       return false;
2339   }
2340 
2341   return true;
2342 }
2343 
2344 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2345   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2346 
2347   // Update machine-CFG edges.
2348   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2349 
2350   if (I.isUnconditional()) {
2351     // Update machine-CFG edges.
2352     BrMBB->addSuccessor(Succ0MBB);
2353 
2354     // If this is not a fall-through branch or optimizations are switched off,
2355     // emit the branch.
2356     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2357       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2358                               MVT::Other, getControlRoot(),
2359                               DAG.getBasicBlock(Succ0MBB)));
2360 
2361     return;
2362   }
2363 
2364   // If this condition is one of the special cases we handle, do special stuff
2365   // now.
2366   const Value *CondVal = I.getCondition();
2367   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2368 
2369   // If this is a series of conditions that are or'd or and'd together, emit
2370   // this as a sequence of branches instead of setcc's with and/or operations.
2371   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2372   // unpredictable branches, and vector extracts because those jumps are likely
2373   // expensive for any target), this should improve performance.
2374   // For example, instead of something like:
2375   //     cmp A, B
2376   //     C = seteq
2377   //     cmp D, E
2378   //     F = setle
2379   //     or C, F
2380   //     jnz foo
2381   // Emit:
2382   //     cmp A, B
2383   //     je foo
2384   //     cmp D, E
2385   //     jle foo
2386   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2387   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2388       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2389     Value *Vec;
2390     const Value *BOp0, *BOp1;
2391     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2392     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2393       Opcode = Instruction::And;
2394     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2395       Opcode = Instruction::Or;
2396 
2397     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2398                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2399       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2400                            getEdgeProbability(BrMBB, Succ0MBB),
2401                            getEdgeProbability(BrMBB, Succ1MBB),
2402                            /*InvertCond=*/false);
2403       // If the compares in later blocks need to use values not currently
2404       // exported from this block, export them now.  This block should always
2405       // be the first entry.
2406       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2407 
2408       // Allow some cases to be rejected.
2409       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2410         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2411           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2412           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2413         }
2414 
2415         // Emit the branch for this block.
2416         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2417         SL->SwitchCases.erase(SL->SwitchCases.begin());
2418         return;
2419       }
2420 
2421       // Okay, we decided not to do this, remove any inserted MBB's and clear
2422       // SwitchCases.
2423       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2424         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2425 
2426       SL->SwitchCases.clear();
2427     }
2428   }
2429 
2430   // Create a CaseBlock record representing this branch.
2431   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2432                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2433 
2434   // Use visitSwitchCase to actually insert the fast branch sequence for this
2435   // cond branch.
2436   visitSwitchCase(CB, BrMBB);
2437 }
2438 
2439 /// visitSwitchCase - Emits the necessary code to represent a single node in
2440 /// the binary search tree resulting from lowering a switch instruction.
2441 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2442                                           MachineBasicBlock *SwitchBB) {
2443   SDValue Cond;
2444   SDValue CondLHS = getValue(CB.CmpLHS);
2445   SDLoc dl = CB.DL;
2446 
2447   if (CB.CC == ISD::SETTRUE) {
2448     // Branch or fall through to TrueBB.
2449     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2450     SwitchBB->normalizeSuccProbs();
2451     if (CB.TrueBB != NextBlock(SwitchBB)) {
2452       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2453                               DAG.getBasicBlock(CB.TrueBB)));
2454     }
2455     return;
2456   }
2457 
2458   auto &TLI = DAG.getTargetLoweringInfo();
2459   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2460 
2461   // Build the setcc now.
2462   if (!CB.CmpMHS) {
2463     // Fold "(X == true)" to X and "(X == false)" to !X to
2464     // handle common cases produced by branch lowering.
2465     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2466         CB.CC == ISD::SETEQ)
2467       Cond = CondLHS;
2468     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2469              CB.CC == ISD::SETEQ) {
2470       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2471       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2472     } else {
2473       SDValue CondRHS = getValue(CB.CmpRHS);
2474 
2475       // If a pointer's DAG type is larger than its memory type then the DAG
2476       // values are zero-extended. This breaks signed comparisons so truncate
2477       // back to the underlying type before doing the compare.
2478       if (CondLHS.getValueType() != MemVT) {
2479         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2480         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2481       }
2482       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2483     }
2484   } else {
2485     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2486 
2487     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2488     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2489 
2490     SDValue CmpOp = getValue(CB.CmpMHS);
2491     EVT VT = CmpOp.getValueType();
2492 
2493     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2494       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2495                           ISD::SETLE);
2496     } else {
2497       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2498                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2499       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2500                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2501     }
2502   }
2503 
2504   // Update successor info
2505   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2506   // TrueBB and FalseBB are always different unless the incoming IR is
2507   // degenerate. This only happens when running llc on weird IR.
2508   if (CB.TrueBB != CB.FalseBB)
2509     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2510   SwitchBB->normalizeSuccProbs();
2511 
2512   // If the lhs block is the next block, invert the condition so that we can
2513   // fall through to the lhs instead of the rhs block.
2514   if (CB.TrueBB == NextBlock(SwitchBB)) {
2515     std::swap(CB.TrueBB, CB.FalseBB);
2516     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2517     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2518   }
2519 
2520   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2521                                MVT::Other, getControlRoot(), Cond,
2522                                DAG.getBasicBlock(CB.TrueBB));
2523 
2524   // Insert the false branch. Do this even if it's a fall through branch,
2525   // this makes it easier to do DAG optimizations which require inverting
2526   // the branch condition.
2527   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2528                        DAG.getBasicBlock(CB.FalseBB));
2529 
2530   DAG.setRoot(BrCond);
2531 }
2532 
2533 /// visitJumpTable - Emit JumpTable node in the current MBB
2534 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2535   // Emit the code for the jump table
2536   assert(JT.Reg != -1U && "Should lower JT Header first!");
2537   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2538   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2539                                      JT.Reg, PTy);
2540   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2541   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2542                                     MVT::Other, Index.getValue(1),
2543                                     Table, Index);
2544   DAG.setRoot(BrJumpTable);
2545 }
2546 
2547 /// visitJumpTableHeader - This function emits necessary code to produce index
2548 /// in the JumpTable from switch case.
2549 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2550                                                JumpTableHeader &JTH,
2551                                                MachineBasicBlock *SwitchBB) {
2552   SDLoc dl = getCurSDLoc();
2553 
2554   // Subtract the lowest switch case value from the value being switched on.
2555   SDValue SwitchOp = getValue(JTH.SValue);
2556   EVT VT = SwitchOp.getValueType();
2557   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2558                             DAG.getConstant(JTH.First, dl, VT));
2559 
2560   // The SDNode we just created, which holds the value being switched on minus
2561   // the smallest case value, needs to be copied to a virtual register so it
2562   // can be used as an index into the jump table in a subsequent basic block.
2563   // This value may be smaller or larger than the target's pointer type, and
2564   // therefore require extension or truncating.
2565   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2566   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2567 
2568   unsigned JumpTableReg =
2569       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2570   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2571                                     JumpTableReg, SwitchOp);
2572   JT.Reg = JumpTableReg;
2573 
2574   if (!JTH.OmitRangeCheck) {
2575     // Emit the range check for the jump table, and branch to the default block
2576     // for the switch statement if the value being switched on exceeds the
2577     // largest case in the switch.
2578     SDValue CMP = DAG.getSetCC(
2579         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2580                                    Sub.getValueType()),
2581         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2582 
2583     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2584                                  MVT::Other, CopyTo, CMP,
2585                                  DAG.getBasicBlock(JT.Default));
2586 
2587     // Avoid emitting unnecessary branches to the next block.
2588     if (JT.MBB != NextBlock(SwitchBB))
2589       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2590                            DAG.getBasicBlock(JT.MBB));
2591 
2592     DAG.setRoot(BrCond);
2593   } else {
2594     // Avoid emitting unnecessary branches to the next block.
2595     if (JT.MBB != NextBlock(SwitchBB))
2596       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2597                               DAG.getBasicBlock(JT.MBB)));
2598     else
2599       DAG.setRoot(CopyTo);
2600   }
2601 }
2602 
2603 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2604 /// variable if there exists one.
2605 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2606                                  SDValue &Chain) {
2607   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2608   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2609   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2610   MachineFunction &MF = DAG.getMachineFunction();
2611   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2612   MachineSDNode *Node =
2613       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2614   if (Global) {
2615     MachinePointerInfo MPInfo(Global);
2616     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2617                  MachineMemOperand::MODereferenceable;
2618     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2619         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2620     DAG.setNodeMemRefs(Node, {MemRef});
2621   }
2622   if (PtrTy != PtrMemTy)
2623     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2624   return SDValue(Node, 0);
2625 }
2626 
2627 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2628 /// tail spliced into a stack protector check success bb.
2629 ///
2630 /// For a high level explanation of how this fits into the stack protector
2631 /// generation see the comment on the declaration of class
2632 /// StackProtectorDescriptor.
2633 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2634                                                   MachineBasicBlock *ParentBB) {
2635 
2636   // First create the loads to the guard/stack slot for the comparison.
2637   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2638   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2639   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2640 
2641   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2642   int FI = MFI.getStackProtectorIndex();
2643 
2644   SDValue Guard;
2645   SDLoc dl = getCurSDLoc();
2646   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2647   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2648   Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2649 
2650   // Generate code to load the content of the guard slot.
2651   SDValue GuardVal = DAG.getLoad(
2652       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2653       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2654       MachineMemOperand::MOVolatile);
2655 
2656   if (TLI.useStackGuardXorFP())
2657     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2658 
2659   // Retrieve guard check function, nullptr if instrumentation is inlined.
2660   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2661     // The target provides a guard check function to validate the guard value.
2662     // Generate a call to that function with the content of the guard slot as
2663     // argument.
2664     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2665     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2666 
2667     TargetLowering::ArgListTy Args;
2668     TargetLowering::ArgListEntry Entry;
2669     Entry.Node = GuardVal;
2670     Entry.Ty = FnTy->getParamType(0);
2671     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2672       Entry.IsInReg = true;
2673     Args.push_back(Entry);
2674 
2675     TargetLowering::CallLoweringInfo CLI(DAG);
2676     CLI.setDebugLoc(getCurSDLoc())
2677         .setChain(DAG.getEntryNode())
2678         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2679                    getValue(GuardCheckFn), std::move(Args));
2680 
2681     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2682     DAG.setRoot(Result.second);
2683     return;
2684   }
2685 
2686   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2687   // Otherwise, emit a volatile load to retrieve the stack guard value.
2688   SDValue Chain = DAG.getEntryNode();
2689   if (TLI.useLoadStackGuardNode()) {
2690     Guard = getLoadStackGuard(DAG, dl, Chain);
2691   } else {
2692     const Value *IRGuard = TLI.getSDagStackGuard(M);
2693     SDValue GuardPtr = getValue(IRGuard);
2694 
2695     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2696                         MachinePointerInfo(IRGuard, 0), Align,
2697                         MachineMemOperand::MOVolatile);
2698   }
2699 
2700   // Perform the comparison via a getsetcc.
2701   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2702                                                         *DAG.getContext(),
2703                                                         Guard.getValueType()),
2704                              Guard, GuardVal, ISD::SETNE);
2705 
2706   // If the guard/stackslot do not equal, branch to failure MBB.
2707   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2708                                MVT::Other, GuardVal.getOperand(0),
2709                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2710   // Otherwise branch to success MBB.
2711   SDValue Br = DAG.getNode(ISD::BR, dl,
2712                            MVT::Other, BrCond,
2713                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2714 
2715   DAG.setRoot(Br);
2716 }
2717 
2718 /// Codegen the failure basic block for a stack protector check.
2719 ///
2720 /// A failure stack protector machine basic block consists simply of a call to
2721 /// __stack_chk_fail().
2722 ///
2723 /// For a high level explanation of how this fits into the stack protector
2724 /// generation see the comment on the declaration of class
2725 /// StackProtectorDescriptor.
2726 void
2727 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2728   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2729   TargetLowering::MakeLibCallOptions CallOptions;
2730   CallOptions.setDiscardResult(true);
2731   SDValue Chain =
2732       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2733                       None, CallOptions, getCurSDLoc()).second;
2734   // On PS4, the "return address" must still be within the calling function,
2735   // even if it's at the very end, so emit an explicit TRAP here.
2736   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2737   if (TM.getTargetTriple().isPS4CPU())
2738     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2739   // WebAssembly needs an unreachable instruction after a non-returning call,
2740   // because the function return type can be different from __stack_chk_fail's
2741   // return type (void).
2742   if (TM.getTargetTriple().isWasm())
2743     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2744 
2745   DAG.setRoot(Chain);
2746 }
2747 
2748 /// visitBitTestHeader - This function emits necessary code to produce value
2749 /// suitable for "bit tests"
2750 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2751                                              MachineBasicBlock *SwitchBB) {
2752   SDLoc dl = getCurSDLoc();
2753 
2754   // Subtract the minimum value.
2755   SDValue SwitchOp = getValue(B.SValue);
2756   EVT VT = SwitchOp.getValueType();
2757   SDValue RangeSub =
2758       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2759 
2760   // Determine the type of the test operands.
2761   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2762   bool UsePtrType = false;
2763   if (!TLI.isTypeLegal(VT)) {
2764     UsePtrType = true;
2765   } else {
2766     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2767       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2768         // Switch table case range are encoded into series of masks.
2769         // Just use pointer type, it's guaranteed to fit.
2770         UsePtrType = true;
2771         break;
2772       }
2773   }
2774   SDValue Sub = RangeSub;
2775   if (UsePtrType) {
2776     VT = TLI.getPointerTy(DAG.getDataLayout());
2777     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2778   }
2779 
2780   B.RegVT = VT.getSimpleVT();
2781   B.Reg = FuncInfo.CreateReg(B.RegVT);
2782   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2783 
2784   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2785 
2786   if (!B.OmitRangeCheck)
2787     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2788   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2789   SwitchBB->normalizeSuccProbs();
2790 
2791   SDValue Root = CopyTo;
2792   if (!B.OmitRangeCheck) {
2793     // Conditional branch to the default block.
2794     SDValue RangeCmp = DAG.getSetCC(dl,
2795         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2796                                RangeSub.getValueType()),
2797         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2798         ISD::SETUGT);
2799 
2800     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2801                        DAG.getBasicBlock(B.Default));
2802   }
2803 
2804   // Avoid emitting unnecessary branches to the next block.
2805   if (MBB != NextBlock(SwitchBB))
2806     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2807 
2808   DAG.setRoot(Root);
2809 }
2810 
2811 /// visitBitTestCase - this function produces one "bit test"
2812 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2813                                            MachineBasicBlock* NextMBB,
2814                                            BranchProbability BranchProbToNext,
2815                                            unsigned Reg,
2816                                            BitTestCase &B,
2817                                            MachineBasicBlock *SwitchBB) {
2818   SDLoc dl = getCurSDLoc();
2819   MVT VT = BB.RegVT;
2820   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2821   SDValue Cmp;
2822   unsigned PopCount = countPopulation(B.Mask);
2823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2824   if (PopCount == 1) {
2825     // Testing for a single bit; just compare the shift count with what it
2826     // would need to be to shift a 1 bit in that position.
2827     Cmp = DAG.getSetCC(
2828         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2829         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2830         ISD::SETEQ);
2831   } else if (PopCount == BB.Range) {
2832     // There is only one zero bit in the range, test for it directly.
2833     Cmp = DAG.getSetCC(
2834         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2835         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2836         ISD::SETNE);
2837   } else {
2838     // Make desired shift
2839     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2840                                     DAG.getConstant(1, dl, VT), ShiftOp);
2841 
2842     // Emit bit tests and jumps
2843     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2844                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2845     Cmp = DAG.getSetCC(
2846         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2847         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2848   }
2849 
2850   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2851   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2852   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2853   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2854   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2855   // one as they are relative probabilities (and thus work more like weights),
2856   // and hence we need to normalize them to let the sum of them become one.
2857   SwitchBB->normalizeSuccProbs();
2858 
2859   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2860                               MVT::Other, getControlRoot(),
2861                               Cmp, DAG.getBasicBlock(B.TargetBB));
2862 
2863   // Avoid emitting unnecessary branches to the next block.
2864   if (NextMBB != NextBlock(SwitchBB))
2865     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2866                         DAG.getBasicBlock(NextMBB));
2867 
2868   DAG.setRoot(BrAnd);
2869 }
2870 
2871 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2872   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2873 
2874   // Retrieve successors. Look through artificial IR level blocks like
2875   // catchswitch for successors.
2876   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2877   const BasicBlock *EHPadBB = I.getSuccessor(1);
2878 
2879   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2880   // have to do anything here to lower funclet bundles.
2881   assert(!I.hasOperandBundlesOtherThan(
2882              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2883               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2884               LLVMContext::OB_cfguardtarget,
2885               LLVMContext::OB_clang_arc_attachedcall}) &&
2886          "Cannot lower invokes with arbitrary operand bundles yet!");
2887 
2888   const Value *Callee(I.getCalledOperand());
2889   const Function *Fn = dyn_cast<Function>(Callee);
2890   if (isa<InlineAsm>(Callee))
2891     visitInlineAsm(I, EHPadBB);
2892   else if (Fn && Fn->isIntrinsic()) {
2893     switch (Fn->getIntrinsicID()) {
2894     default:
2895       llvm_unreachable("Cannot invoke this intrinsic");
2896     case Intrinsic::donothing:
2897       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2898     case Intrinsic::seh_try_begin:
2899     case Intrinsic::seh_scope_begin:
2900     case Intrinsic::seh_try_end:
2901     case Intrinsic::seh_scope_end:
2902       break;
2903     case Intrinsic::experimental_patchpoint_void:
2904     case Intrinsic::experimental_patchpoint_i64:
2905       visitPatchpoint(I, EHPadBB);
2906       break;
2907     case Intrinsic::experimental_gc_statepoint:
2908       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2909       break;
2910     case Intrinsic::wasm_rethrow: {
2911       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2912       // special because it can be invoked, so we manually lower it to a DAG
2913       // node here.
2914       SmallVector<SDValue, 8> Ops;
2915       Ops.push_back(getRoot()); // inchain
2916       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2917       Ops.push_back(
2918           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2919                                 TLI.getPointerTy(DAG.getDataLayout())));
2920       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2921       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2922       break;
2923     }
2924     }
2925   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2926     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2927     // Eventually we will support lowering the @llvm.experimental.deoptimize
2928     // intrinsic, and right now there are no plans to support other intrinsics
2929     // with deopt state.
2930     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2931   } else {
2932     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2933   }
2934 
2935   // If the value of the invoke is used outside of its defining block, make it
2936   // available as a virtual register.
2937   // We already took care of the exported value for the statepoint instruction
2938   // during call to the LowerStatepoint.
2939   if (!isa<GCStatepointInst>(I)) {
2940     CopyToExportRegsIfNeeded(&I);
2941   }
2942 
2943   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2944   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2945   BranchProbability EHPadBBProb =
2946       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2947           : BranchProbability::getZero();
2948   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2949 
2950   // Update successor info.
2951   addSuccessorWithProb(InvokeMBB, Return);
2952   for (auto &UnwindDest : UnwindDests) {
2953     UnwindDest.first->setIsEHPad();
2954     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2955   }
2956   InvokeMBB->normalizeSuccProbs();
2957 
2958   // Drop into normal successor.
2959   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2960                           DAG.getBasicBlock(Return)));
2961 }
2962 
2963 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2964   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2965 
2966   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2967   // have to do anything here to lower funclet bundles.
2968   assert(!I.hasOperandBundlesOtherThan(
2969              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2970          "Cannot lower callbrs with arbitrary operand bundles yet!");
2971 
2972   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2973   visitInlineAsm(I);
2974   CopyToExportRegsIfNeeded(&I);
2975 
2976   // Retrieve successors.
2977   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2978 
2979   // Update successor info.
2980   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2981   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2982     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2983     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2984     Target->setIsInlineAsmBrIndirectTarget();
2985   }
2986   CallBrMBB->normalizeSuccProbs();
2987 
2988   // Drop into default successor.
2989   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2990                           MVT::Other, getControlRoot(),
2991                           DAG.getBasicBlock(Return)));
2992 }
2993 
2994 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2995   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2996 }
2997 
2998 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2999   assert(FuncInfo.MBB->isEHPad() &&
3000          "Call to landingpad not in landing pad!");
3001 
3002   // If there aren't registers to copy the values into (e.g., during SjLj
3003   // exceptions), then don't bother to create these DAG nodes.
3004   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3005   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3006   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3007       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3008     return;
3009 
3010   // If landingpad's return type is token type, we don't create DAG nodes
3011   // for its exception pointer and selector value. The extraction of exception
3012   // pointer or selector value from token type landingpads is not currently
3013   // supported.
3014   if (LP.getType()->isTokenTy())
3015     return;
3016 
3017   SmallVector<EVT, 2> ValueVTs;
3018   SDLoc dl = getCurSDLoc();
3019   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3020   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3021 
3022   // Get the two live-in registers as SDValues. The physregs have already been
3023   // copied into virtual registers.
3024   SDValue Ops[2];
3025   if (FuncInfo.ExceptionPointerVirtReg) {
3026     Ops[0] = DAG.getZExtOrTrunc(
3027         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3028                            FuncInfo.ExceptionPointerVirtReg,
3029                            TLI.getPointerTy(DAG.getDataLayout())),
3030         dl, ValueVTs[0]);
3031   } else {
3032     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3033   }
3034   Ops[1] = DAG.getZExtOrTrunc(
3035       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3036                          FuncInfo.ExceptionSelectorVirtReg,
3037                          TLI.getPointerTy(DAG.getDataLayout())),
3038       dl, ValueVTs[1]);
3039 
3040   // Merge into one.
3041   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3042                             DAG.getVTList(ValueVTs), Ops);
3043   setValue(&LP, Res);
3044 }
3045 
3046 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3047                                            MachineBasicBlock *Last) {
3048   // Update JTCases.
3049   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
3050     if (SL->JTCases[i].first.HeaderBB == First)
3051       SL->JTCases[i].first.HeaderBB = Last;
3052 
3053   // Update BitTestCases.
3054   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
3055     if (SL->BitTestCases[i].Parent == First)
3056       SL->BitTestCases[i].Parent = Last;
3057 }
3058 
3059 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3060   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3061 
3062   // Update machine-CFG edges with unique successors.
3063   SmallSet<BasicBlock*, 32> Done;
3064   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3065     BasicBlock *BB = I.getSuccessor(i);
3066     bool Inserted = Done.insert(BB).second;
3067     if (!Inserted)
3068         continue;
3069 
3070     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3071     addSuccessorWithProb(IndirectBrMBB, Succ);
3072   }
3073   IndirectBrMBB->normalizeSuccProbs();
3074 
3075   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3076                           MVT::Other, getControlRoot(),
3077                           getValue(I.getAddress())));
3078 }
3079 
3080 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3081   if (!DAG.getTarget().Options.TrapUnreachable)
3082     return;
3083 
3084   // We may be able to ignore unreachable behind a noreturn call.
3085   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3086     const BasicBlock &BB = *I.getParent();
3087     if (&I != &BB.front()) {
3088       BasicBlock::const_iterator PredI =
3089         std::prev(BasicBlock::const_iterator(&I));
3090       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3091         if (Call->doesNotReturn())
3092           return;
3093       }
3094     }
3095   }
3096 
3097   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3098 }
3099 
3100 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3101   SDNodeFlags Flags;
3102 
3103   SDValue Op = getValue(I.getOperand(0));
3104   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3105                                     Op, Flags);
3106   setValue(&I, UnNodeValue);
3107 }
3108 
3109 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3110   SDNodeFlags Flags;
3111   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3112     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3113     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3114   }
3115   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3116     Flags.setExact(ExactOp->isExact());
3117   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3118     Flags.copyFMF(*FPOp);
3119 
3120   SDValue Op1 = getValue(I.getOperand(0));
3121   SDValue Op2 = getValue(I.getOperand(1));
3122   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3123                                      Op1, Op2, Flags);
3124   setValue(&I, BinNodeValue);
3125 }
3126 
3127 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3128   SDValue Op1 = getValue(I.getOperand(0));
3129   SDValue Op2 = getValue(I.getOperand(1));
3130 
3131   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3132       Op1.getValueType(), DAG.getDataLayout());
3133 
3134   // Coerce the shift amount to the right type if we can.
3135   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3136     unsigned ShiftSize = ShiftTy.getSizeInBits();
3137     unsigned Op2Size = Op2.getValueSizeInBits();
3138     SDLoc DL = getCurSDLoc();
3139 
3140     // If the operand is smaller than the shift count type, promote it.
3141     if (ShiftSize > Op2Size)
3142       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3143 
3144     // If the operand is larger than the shift count type but the shift
3145     // count type has enough bits to represent any shift value, truncate
3146     // it now. This is a common case and it exposes the truncate to
3147     // optimization early.
3148     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3149       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3150     // Otherwise we'll need to temporarily settle for some other convenient
3151     // type.  Type legalization will make adjustments once the shiftee is split.
3152     else
3153       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3154   }
3155 
3156   bool nuw = false;
3157   bool nsw = false;
3158   bool exact = false;
3159 
3160   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3161 
3162     if (const OverflowingBinaryOperator *OFBinOp =
3163             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3164       nuw = OFBinOp->hasNoUnsignedWrap();
3165       nsw = OFBinOp->hasNoSignedWrap();
3166     }
3167     if (const PossiblyExactOperator *ExactOp =
3168             dyn_cast<const PossiblyExactOperator>(&I))
3169       exact = ExactOp->isExact();
3170   }
3171   SDNodeFlags Flags;
3172   Flags.setExact(exact);
3173   Flags.setNoSignedWrap(nsw);
3174   Flags.setNoUnsignedWrap(nuw);
3175   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3176                             Flags);
3177   setValue(&I, Res);
3178 }
3179 
3180 void SelectionDAGBuilder::visitSDiv(const User &I) {
3181   SDValue Op1 = getValue(I.getOperand(0));
3182   SDValue Op2 = getValue(I.getOperand(1));
3183 
3184   SDNodeFlags Flags;
3185   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3186                  cast<PossiblyExactOperator>(&I)->isExact());
3187   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3188                            Op2, Flags));
3189 }
3190 
3191 void SelectionDAGBuilder::visitICmp(const User &I) {
3192   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3193   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3194     predicate = IC->getPredicate();
3195   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3196     predicate = ICmpInst::Predicate(IC->getPredicate());
3197   SDValue Op1 = getValue(I.getOperand(0));
3198   SDValue Op2 = getValue(I.getOperand(1));
3199   ISD::CondCode Opcode = getICmpCondCode(predicate);
3200 
3201   auto &TLI = DAG.getTargetLoweringInfo();
3202   EVT MemVT =
3203       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3204 
3205   // If a pointer's DAG type is larger than its memory type then the DAG values
3206   // are zero-extended. This breaks signed comparisons so truncate back to the
3207   // underlying type before doing the compare.
3208   if (Op1.getValueType() != MemVT) {
3209     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3210     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3211   }
3212 
3213   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3214                                                         I.getType());
3215   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3216 }
3217 
3218 void SelectionDAGBuilder::visitFCmp(const User &I) {
3219   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3220   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3221     predicate = FC->getPredicate();
3222   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3223     predicate = FCmpInst::Predicate(FC->getPredicate());
3224   SDValue Op1 = getValue(I.getOperand(0));
3225   SDValue Op2 = getValue(I.getOperand(1));
3226 
3227   ISD::CondCode Condition = getFCmpCondCode(predicate);
3228   auto *FPMO = cast<FPMathOperator>(&I);
3229   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3230     Condition = getFCmpCodeWithoutNaN(Condition);
3231 
3232   SDNodeFlags Flags;
3233   Flags.copyFMF(*FPMO);
3234   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3235 
3236   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3237                                                         I.getType());
3238   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3239 }
3240 
3241 // Check if the condition of the select has one use or two users that are both
3242 // selects with the same condition.
3243 static bool hasOnlySelectUsers(const Value *Cond) {
3244   return llvm::all_of(Cond->users(), [](const Value *V) {
3245     return isa<SelectInst>(V);
3246   });
3247 }
3248 
3249 void SelectionDAGBuilder::visitSelect(const User &I) {
3250   SmallVector<EVT, 4> ValueVTs;
3251   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3252                   ValueVTs);
3253   unsigned NumValues = ValueVTs.size();
3254   if (NumValues == 0) return;
3255 
3256   SmallVector<SDValue, 4> Values(NumValues);
3257   SDValue Cond     = getValue(I.getOperand(0));
3258   SDValue LHSVal   = getValue(I.getOperand(1));
3259   SDValue RHSVal   = getValue(I.getOperand(2));
3260   SmallVector<SDValue, 1> BaseOps(1, Cond);
3261   ISD::NodeType OpCode =
3262       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3263 
3264   bool IsUnaryAbs = false;
3265   bool Negate = false;
3266 
3267   SDNodeFlags Flags;
3268   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3269     Flags.copyFMF(*FPOp);
3270 
3271   // Min/max matching is only viable if all output VTs are the same.
3272   if (is_splat(ValueVTs)) {
3273     EVT VT = ValueVTs[0];
3274     LLVMContext &Ctx = *DAG.getContext();
3275     auto &TLI = DAG.getTargetLoweringInfo();
3276 
3277     // We care about the legality of the operation after it has been type
3278     // legalized.
3279     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3280       VT = TLI.getTypeToTransformTo(Ctx, VT);
3281 
3282     // If the vselect is legal, assume we want to leave this as a vector setcc +
3283     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3284     // min/max is legal on the scalar type.
3285     bool UseScalarMinMax = VT.isVector() &&
3286       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3287 
3288     Value *LHS, *RHS;
3289     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3290     ISD::NodeType Opc = ISD::DELETED_NODE;
3291     switch (SPR.Flavor) {
3292     case SPF_UMAX:    Opc = ISD::UMAX; break;
3293     case SPF_UMIN:    Opc = ISD::UMIN; break;
3294     case SPF_SMAX:    Opc = ISD::SMAX; break;
3295     case SPF_SMIN:    Opc = ISD::SMIN; break;
3296     case SPF_FMINNUM:
3297       switch (SPR.NaNBehavior) {
3298       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3299       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3300       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3301       case SPNB_RETURNS_ANY: {
3302         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3303           Opc = ISD::FMINNUM;
3304         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3305           Opc = ISD::FMINIMUM;
3306         else if (UseScalarMinMax)
3307           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3308             ISD::FMINNUM : ISD::FMINIMUM;
3309         break;
3310       }
3311       }
3312       break;
3313     case SPF_FMAXNUM:
3314       switch (SPR.NaNBehavior) {
3315       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3316       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3317       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3318       case SPNB_RETURNS_ANY:
3319 
3320         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3321           Opc = ISD::FMAXNUM;
3322         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3323           Opc = ISD::FMAXIMUM;
3324         else if (UseScalarMinMax)
3325           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3326             ISD::FMAXNUM : ISD::FMAXIMUM;
3327         break;
3328       }
3329       break;
3330     case SPF_NABS:
3331       Negate = true;
3332       LLVM_FALLTHROUGH;
3333     case SPF_ABS:
3334       IsUnaryAbs = true;
3335       Opc = ISD::ABS;
3336       break;
3337     default: break;
3338     }
3339 
3340     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3341         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3342          (UseScalarMinMax &&
3343           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3344         // If the underlying comparison instruction is used by any other
3345         // instruction, the consumed instructions won't be destroyed, so it is
3346         // not profitable to convert to a min/max.
3347         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3348       OpCode = Opc;
3349       LHSVal = getValue(LHS);
3350       RHSVal = getValue(RHS);
3351       BaseOps.clear();
3352     }
3353 
3354     if (IsUnaryAbs) {
3355       OpCode = Opc;
3356       LHSVal = getValue(LHS);
3357       BaseOps.clear();
3358     }
3359   }
3360 
3361   if (IsUnaryAbs) {
3362     for (unsigned i = 0; i != NumValues; ++i) {
3363       SDLoc dl = getCurSDLoc();
3364       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3365       Values[i] =
3366           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3367       if (Negate)
3368         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3369                                 Values[i]);
3370     }
3371   } else {
3372     for (unsigned i = 0; i != NumValues; ++i) {
3373       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3374       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3375       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3376       Values[i] = DAG.getNode(
3377           OpCode, getCurSDLoc(),
3378           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3379     }
3380   }
3381 
3382   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3383                            DAG.getVTList(ValueVTs), Values));
3384 }
3385 
3386 void SelectionDAGBuilder::visitTrunc(const User &I) {
3387   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3388   SDValue N = getValue(I.getOperand(0));
3389   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3390                                                         I.getType());
3391   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3392 }
3393 
3394 void SelectionDAGBuilder::visitZExt(const User &I) {
3395   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3396   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3397   SDValue N = getValue(I.getOperand(0));
3398   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3399                                                         I.getType());
3400   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3401 }
3402 
3403 void SelectionDAGBuilder::visitSExt(const User &I) {
3404   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3405   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3406   SDValue N = getValue(I.getOperand(0));
3407   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3408                                                         I.getType());
3409   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3410 }
3411 
3412 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3413   // FPTrunc is never a no-op cast, no need to check
3414   SDValue N = getValue(I.getOperand(0));
3415   SDLoc dl = getCurSDLoc();
3416   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3417   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3418   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3419                            DAG.getTargetConstant(
3420                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3421 }
3422 
3423 void SelectionDAGBuilder::visitFPExt(const User &I) {
3424   // FPExt is never a no-op cast, no need to check
3425   SDValue N = getValue(I.getOperand(0));
3426   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3427                                                         I.getType());
3428   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3429 }
3430 
3431 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3432   // FPToUI is never a no-op cast, no need to check
3433   SDValue N = getValue(I.getOperand(0));
3434   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3435                                                         I.getType());
3436   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3437 }
3438 
3439 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3440   // FPToSI is never a no-op cast, no need to check
3441   SDValue N = getValue(I.getOperand(0));
3442   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3443                                                         I.getType());
3444   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3445 }
3446 
3447 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3448   // UIToFP is never a no-op cast, no need to check
3449   SDValue N = getValue(I.getOperand(0));
3450   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3451                                                         I.getType());
3452   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3453 }
3454 
3455 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3456   // SIToFP is never a no-op cast, no need to check
3457   SDValue N = getValue(I.getOperand(0));
3458   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3459                                                         I.getType());
3460   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3461 }
3462 
3463 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3464   // What to do depends on the size of the integer and the size of the pointer.
3465   // We can either truncate, zero extend, or no-op, accordingly.
3466   SDValue N = getValue(I.getOperand(0));
3467   auto &TLI = DAG.getTargetLoweringInfo();
3468   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3469                                                         I.getType());
3470   EVT PtrMemVT =
3471       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3472   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3473   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3474   setValue(&I, N);
3475 }
3476 
3477 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3478   // What to do depends on the size of the integer and the size of the pointer.
3479   // We can either truncate, zero extend, or no-op, accordingly.
3480   SDValue N = getValue(I.getOperand(0));
3481   auto &TLI = DAG.getTargetLoweringInfo();
3482   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3483   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3484   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3485   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3486   setValue(&I, N);
3487 }
3488 
3489 void SelectionDAGBuilder::visitBitCast(const User &I) {
3490   SDValue N = getValue(I.getOperand(0));
3491   SDLoc dl = getCurSDLoc();
3492   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3493                                                         I.getType());
3494 
3495   // BitCast assures us that source and destination are the same size so this is
3496   // either a BITCAST or a no-op.
3497   if (DestVT != N.getValueType())
3498     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3499                              DestVT, N)); // convert types.
3500   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3501   // might fold any kind of constant expression to an integer constant and that
3502   // is not what we are looking for. Only recognize a bitcast of a genuine
3503   // constant integer as an opaque constant.
3504   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3505     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3506                                  /*isOpaque*/true));
3507   else
3508     setValue(&I, N);            // noop cast.
3509 }
3510 
3511 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3513   const Value *SV = I.getOperand(0);
3514   SDValue N = getValue(SV);
3515   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3516 
3517   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3518   unsigned DestAS = I.getType()->getPointerAddressSpace();
3519 
3520   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3521     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3522 
3523   setValue(&I, N);
3524 }
3525 
3526 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3528   SDValue InVec = getValue(I.getOperand(0));
3529   SDValue InVal = getValue(I.getOperand(1));
3530   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3531                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3532   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3533                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3534                            InVec, InVal, InIdx));
3535 }
3536 
3537 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3538   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3539   SDValue InVec = getValue(I.getOperand(0));
3540   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3541                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3542   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3543                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3544                            InVec, InIdx));
3545 }
3546 
3547 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3548   SDValue Src1 = getValue(I.getOperand(0));
3549   SDValue Src2 = getValue(I.getOperand(1));
3550   ArrayRef<int> Mask;
3551   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3552     Mask = SVI->getShuffleMask();
3553   else
3554     Mask = cast<ConstantExpr>(I).getShuffleMask();
3555   SDLoc DL = getCurSDLoc();
3556   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3557   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3558   EVT SrcVT = Src1.getValueType();
3559 
3560   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3561       VT.isScalableVector()) {
3562     // Canonical splat form of first element of first input vector.
3563     SDValue FirstElt =
3564         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3565                     DAG.getVectorIdxConstant(0, DL));
3566     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3567     return;
3568   }
3569 
3570   // For now, we only handle splats for scalable vectors.
3571   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3572   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3573   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3574 
3575   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3576   unsigned MaskNumElts = Mask.size();
3577 
3578   if (SrcNumElts == MaskNumElts) {
3579     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3580     return;
3581   }
3582 
3583   // Normalize the shuffle vector since mask and vector length don't match.
3584   if (SrcNumElts < MaskNumElts) {
3585     // Mask is longer than the source vectors. We can use concatenate vector to
3586     // make the mask and vectors lengths match.
3587 
3588     if (MaskNumElts % SrcNumElts == 0) {
3589       // Mask length is a multiple of the source vector length.
3590       // Check if the shuffle is some kind of concatenation of the input
3591       // vectors.
3592       unsigned NumConcat = MaskNumElts / SrcNumElts;
3593       bool IsConcat = true;
3594       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3595       for (unsigned i = 0; i != MaskNumElts; ++i) {
3596         int Idx = Mask[i];
3597         if (Idx < 0)
3598           continue;
3599         // Ensure the indices in each SrcVT sized piece are sequential and that
3600         // the same source is used for the whole piece.
3601         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3602             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3603              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3604           IsConcat = false;
3605           break;
3606         }
3607         // Remember which source this index came from.
3608         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3609       }
3610 
3611       // The shuffle is concatenating multiple vectors together. Just emit
3612       // a CONCAT_VECTORS operation.
3613       if (IsConcat) {
3614         SmallVector<SDValue, 8> ConcatOps;
3615         for (auto Src : ConcatSrcs) {
3616           if (Src < 0)
3617             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3618           else if (Src == 0)
3619             ConcatOps.push_back(Src1);
3620           else
3621             ConcatOps.push_back(Src2);
3622         }
3623         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3624         return;
3625       }
3626     }
3627 
3628     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3629     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3630     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3631                                     PaddedMaskNumElts);
3632 
3633     // Pad both vectors with undefs to make them the same length as the mask.
3634     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3635 
3636     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3637     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3638     MOps1[0] = Src1;
3639     MOps2[0] = Src2;
3640 
3641     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3642     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3643 
3644     // Readjust mask for new input vector length.
3645     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3646     for (unsigned i = 0; i != MaskNumElts; ++i) {
3647       int Idx = Mask[i];
3648       if (Idx >= (int)SrcNumElts)
3649         Idx -= SrcNumElts - PaddedMaskNumElts;
3650       MappedOps[i] = Idx;
3651     }
3652 
3653     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3654 
3655     // If the concatenated vector was padded, extract a subvector with the
3656     // correct number of elements.
3657     if (MaskNumElts != PaddedMaskNumElts)
3658       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3659                            DAG.getVectorIdxConstant(0, DL));
3660 
3661     setValue(&I, Result);
3662     return;
3663   }
3664 
3665   if (SrcNumElts > MaskNumElts) {
3666     // Analyze the access pattern of the vector to see if we can extract
3667     // two subvectors and do the shuffle.
3668     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3669     bool CanExtract = true;
3670     for (int Idx : Mask) {
3671       unsigned Input = 0;
3672       if (Idx < 0)
3673         continue;
3674 
3675       if (Idx >= (int)SrcNumElts) {
3676         Input = 1;
3677         Idx -= SrcNumElts;
3678       }
3679 
3680       // If all the indices come from the same MaskNumElts sized portion of
3681       // the sources we can use extract. Also make sure the extract wouldn't
3682       // extract past the end of the source.
3683       int NewStartIdx = alignDown(Idx, MaskNumElts);
3684       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3685           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3686         CanExtract = false;
3687       // Make sure we always update StartIdx as we use it to track if all
3688       // elements are undef.
3689       StartIdx[Input] = NewStartIdx;
3690     }
3691 
3692     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3693       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3694       return;
3695     }
3696     if (CanExtract) {
3697       // Extract appropriate subvector and generate a vector shuffle
3698       for (unsigned Input = 0; Input < 2; ++Input) {
3699         SDValue &Src = Input == 0 ? Src1 : Src2;
3700         if (StartIdx[Input] < 0)
3701           Src = DAG.getUNDEF(VT);
3702         else {
3703           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3704                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3705         }
3706       }
3707 
3708       // Calculate new mask.
3709       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3710       for (int &Idx : MappedOps) {
3711         if (Idx >= (int)SrcNumElts)
3712           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3713         else if (Idx >= 0)
3714           Idx -= StartIdx[0];
3715       }
3716 
3717       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3718       return;
3719     }
3720   }
3721 
3722   // We can't use either concat vectors or extract subvectors so fall back to
3723   // replacing the shuffle with extract and build vector.
3724   // to insert and build vector.
3725   EVT EltVT = VT.getVectorElementType();
3726   SmallVector<SDValue,8> Ops;
3727   for (int Idx : Mask) {
3728     SDValue Res;
3729 
3730     if (Idx < 0) {
3731       Res = DAG.getUNDEF(EltVT);
3732     } else {
3733       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3734       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3735 
3736       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3737                         DAG.getVectorIdxConstant(Idx, DL));
3738     }
3739 
3740     Ops.push_back(Res);
3741   }
3742 
3743   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3744 }
3745 
3746 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3747   ArrayRef<unsigned> Indices;
3748   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3749     Indices = IV->getIndices();
3750   else
3751     Indices = cast<ConstantExpr>(&I)->getIndices();
3752 
3753   const Value *Op0 = I.getOperand(0);
3754   const Value *Op1 = I.getOperand(1);
3755   Type *AggTy = I.getType();
3756   Type *ValTy = Op1->getType();
3757   bool IntoUndef = isa<UndefValue>(Op0);
3758   bool FromUndef = isa<UndefValue>(Op1);
3759 
3760   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3761 
3762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3763   SmallVector<EVT, 4> AggValueVTs;
3764   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3765   SmallVector<EVT, 4> ValValueVTs;
3766   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3767 
3768   unsigned NumAggValues = AggValueVTs.size();
3769   unsigned NumValValues = ValValueVTs.size();
3770   SmallVector<SDValue, 4> Values(NumAggValues);
3771 
3772   // Ignore an insertvalue that produces an empty object
3773   if (!NumAggValues) {
3774     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3775     return;
3776   }
3777 
3778   SDValue Agg = getValue(Op0);
3779   unsigned i = 0;
3780   // Copy the beginning value(s) from the original aggregate.
3781   for (; i != LinearIndex; ++i)
3782     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3783                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3784   // Copy values from the inserted value(s).
3785   if (NumValValues) {
3786     SDValue Val = getValue(Op1);
3787     for (; i != LinearIndex + NumValValues; ++i)
3788       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3789                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3790   }
3791   // Copy remaining value(s) from the original aggregate.
3792   for (; i != NumAggValues; ++i)
3793     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3794                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3795 
3796   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3797                            DAG.getVTList(AggValueVTs), Values));
3798 }
3799 
3800 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3801   ArrayRef<unsigned> Indices;
3802   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3803     Indices = EV->getIndices();
3804   else
3805     Indices = cast<ConstantExpr>(&I)->getIndices();
3806 
3807   const Value *Op0 = I.getOperand(0);
3808   Type *AggTy = Op0->getType();
3809   Type *ValTy = I.getType();
3810   bool OutOfUndef = isa<UndefValue>(Op0);
3811 
3812   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3813 
3814   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3815   SmallVector<EVT, 4> ValValueVTs;
3816   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3817 
3818   unsigned NumValValues = ValValueVTs.size();
3819 
3820   // Ignore a extractvalue that produces an empty object
3821   if (!NumValValues) {
3822     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3823     return;
3824   }
3825 
3826   SmallVector<SDValue, 4> Values(NumValValues);
3827 
3828   SDValue Agg = getValue(Op0);
3829   // Copy out the selected value(s).
3830   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3831     Values[i - LinearIndex] =
3832       OutOfUndef ?
3833         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3834         SDValue(Agg.getNode(), Agg.getResNo() + i);
3835 
3836   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3837                            DAG.getVTList(ValValueVTs), Values));
3838 }
3839 
3840 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3841   Value *Op0 = I.getOperand(0);
3842   // Note that the pointer operand may be a vector of pointers. Take the scalar
3843   // element which holds a pointer.
3844   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3845   SDValue N = getValue(Op0);
3846   SDLoc dl = getCurSDLoc();
3847   auto &TLI = DAG.getTargetLoweringInfo();
3848 
3849   // Normalize Vector GEP - all scalar operands should be converted to the
3850   // splat vector.
3851   bool IsVectorGEP = I.getType()->isVectorTy();
3852   ElementCount VectorElementCount =
3853       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3854                   : ElementCount::getFixed(0);
3855 
3856   if (IsVectorGEP && !N.getValueType().isVector()) {
3857     LLVMContext &Context = *DAG.getContext();
3858     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3859     if (VectorElementCount.isScalable())
3860       N = DAG.getSplatVector(VT, dl, N);
3861     else
3862       N = DAG.getSplatBuildVector(VT, dl, N);
3863   }
3864 
3865   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3866        GTI != E; ++GTI) {
3867     const Value *Idx = GTI.getOperand();
3868     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3869       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3870       if (Field) {
3871         // N = N + Offset
3872         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3873 
3874         // In an inbounds GEP with an offset that is nonnegative even when
3875         // interpreted as signed, assume there is no unsigned overflow.
3876         SDNodeFlags Flags;
3877         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3878           Flags.setNoUnsignedWrap(true);
3879 
3880         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3881                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3882       }
3883     } else {
3884       // IdxSize is the width of the arithmetic according to IR semantics.
3885       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3886       // (and fix up the result later).
3887       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3888       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3889       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3890       // We intentionally mask away the high bits here; ElementSize may not
3891       // fit in IdxTy.
3892       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3893       bool ElementScalable = ElementSize.isScalable();
3894 
3895       // If this is a scalar constant or a splat vector of constants,
3896       // handle it quickly.
3897       const auto *C = dyn_cast<Constant>(Idx);
3898       if (C && isa<VectorType>(C->getType()))
3899         C = C->getSplatValue();
3900 
3901       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3902       if (CI && CI->isZero())
3903         continue;
3904       if (CI && !ElementScalable) {
3905         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3906         LLVMContext &Context = *DAG.getContext();
3907         SDValue OffsVal;
3908         if (IsVectorGEP)
3909           OffsVal = DAG.getConstant(
3910               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3911         else
3912           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3913 
3914         // In an inbounds GEP with an offset that is nonnegative even when
3915         // interpreted as signed, assume there is no unsigned overflow.
3916         SDNodeFlags Flags;
3917         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3918           Flags.setNoUnsignedWrap(true);
3919 
3920         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3921 
3922         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3923         continue;
3924       }
3925 
3926       // N = N + Idx * ElementMul;
3927       SDValue IdxN = getValue(Idx);
3928 
3929       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3930         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3931                                   VectorElementCount);
3932         if (VectorElementCount.isScalable())
3933           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3934         else
3935           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3936       }
3937 
3938       // If the index is smaller or larger than intptr_t, truncate or extend
3939       // it.
3940       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3941 
3942       if (ElementScalable) {
3943         EVT VScaleTy = N.getValueType().getScalarType();
3944         SDValue VScale = DAG.getNode(
3945             ISD::VSCALE, dl, VScaleTy,
3946             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3947         if (IsVectorGEP)
3948           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3949         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3950       } else {
3951         // If this is a multiply by a power of two, turn it into a shl
3952         // immediately.  This is a very common case.
3953         if (ElementMul != 1) {
3954           if (ElementMul.isPowerOf2()) {
3955             unsigned Amt = ElementMul.logBase2();
3956             IdxN = DAG.getNode(ISD::SHL, dl,
3957                                N.getValueType(), IdxN,
3958                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3959           } else {
3960             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3961                                             IdxN.getValueType());
3962             IdxN = DAG.getNode(ISD::MUL, dl,
3963                                N.getValueType(), IdxN, Scale);
3964           }
3965         }
3966       }
3967 
3968       N = DAG.getNode(ISD::ADD, dl,
3969                       N.getValueType(), N, IdxN);
3970     }
3971   }
3972 
3973   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3974   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3975   if (IsVectorGEP) {
3976     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3977     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3978   }
3979 
3980   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3981     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3982 
3983   setValue(&I, N);
3984 }
3985 
3986 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3987   // If this is a fixed sized alloca in the entry block of the function,
3988   // allocate it statically on the stack.
3989   if (FuncInfo.StaticAllocaMap.count(&I))
3990     return;   // getValue will auto-populate this.
3991 
3992   SDLoc dl = getCurSDLoc();
3993   Type *Ty = I.getAllocatedType();
3994   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3995   auto &DL = DAG.getDataLayout();
3996   uint64_t TySize = DL.getTypeAllocSize(Ty);
3997   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3998 
3999   SDValue AllocSize = getValue(I.getArraySize());
4000 
4001   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4002   if (AllocSize.getValueType() != IntPtr)
4003     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4004 
4005   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4006                           AllocSize,
4007                           DAG.getConstant(TySize, dl, IntPtr));
4008 
4009   // Handle alignment.  If the requested alignment is less than or equal to
4010   // the stack alignment, ignore it.  If the size is greater than or equal to
4011   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4012   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4013   if (*Alignment <= StackAlign)
4014     Alignment = None;
4015 
4016   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4017   // Round the size of the allocation up to the stack alignment size
4018   // by add SA-1 to the size. This doesn't overflow because we're computing
4019   // an address inside an alloca.
4020   SDNodeFlags Flags;
4021   Flags.setNoUnsignedWrap(true);
4022   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4023                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4024 
4025   // Mask out the low bits for alignment purposes.
4026   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4027                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4028 
4029   SDValue Ops[] = {
4030       getRoot(), AllocSize,
4031       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4032   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4033   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4034   setValue(&I, DSA);
4035   DAG.setRoot(DSA.getValue(1));
4036 
4037   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4038 }
4039 
4040 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4041   if (I.isAtomic())
4042     return visitAtomicLoad(I);
4043 
4044   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4045   const Value *SV = I.getOperand(0);
4046   if (TLI.supportSwiftError()) {
4047     // Swifterror values can come from either a function parameter with
4048     // swifterror attribute or an alloca with swifterror attribute.
4049     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4050       if (Arg->hasSwiftErrorAttr())
4051         return visitLoadFromSwiftError(I);
4052     }
4053 
4054     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4055       if (Alloca->isSwiftError())
4056         return visitLoadFromSwiftError(I);
4057     }
4058   }
4059 
4060   SDValue Ptr = getValue(SV);
4061 
4062   Type *Ty = I.getType();
4063   Align Alignment = I.getAlign();
4064 
4065   AAMDNodes AAInfo;
4066   I.getAAMetadata(AAInfo);
4067   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4068 
4069   SmallVector<EVT, 4> ValueVTs, MemVTs;
4070   SmallVector<uint64_t, 4> Offsets;
4071   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4072   unsigned NumValues = ValueVTs.size();
4073   if (NumValues == 0)
4074     return;
4075 
4076   bool isVolatile = I.isVolatile();
4077 
4078   SDValue Root;
4079   bool ConstantMemory = false;
4080   if (isVolatile)
4081     // Serialize volatile loads with other side effects.
4082     Root = getRoot();
4083   else if (NumValues > MaxParallelChains)
4084     Root = getMemoryRoot();
4085   else if (AA &&
4086            AA->pointsToConstantMemory(MemoryLocation(
4087                SV,
4088                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4089                AAInfo))) {
4090     // Do not serialize (non-volatile) loads of constant memory with anything.
4091     Root = DAG.getEntryNode();
4092     ConstantMemory = true;
4093   } else {
4094     // Do not serialize non-volatile loads against each other.
4095     Root = DAG.getRoot();
4096   }
4097 
4098   SDLoc dl = getCurSDLoc();
4099 
4100   if (isVolatile)
4101     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4102 
4103   // An aggregate load cannot wrap around the address space, so offsets to its
4104   // parts don't wrap either.
4105   SDNodeFlags Flags;
4106   Flags.setNoUnsignedWrap(true);
4107 
4108   SmallVector<SDValue, 4> Values(NumValues);
4109   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4110   EVT PtrVT = Ptr.getValueType();
4111 
4112   MachineMemOperand::Flags MMOFlags
4113     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4114 
4115   unsigned ChainI = 0;
4116   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4117     // Serializing loads here may result in excessive register pressure, and
4118     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4119     // could recover a bit by hoisting nodes upward in the chain by recognizing
4120     // they are side-effect free or do not alias. The optimizer should really
4121     // avoid this case by converting large object/array copies to llvm.memcpy
4122     // (MaxParallelChains should always remain as failsafe).
4123     if (ChainI == MaxParallelChains) {
4124       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4125       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4126                                   makeArrayRef(Chains.data(), ChainI));
4127       Root = Chain;
4128       ChainI = 0;
4129     }
4130     SDValue A = DAG.getNode(ISD::ADD, dl,
4131                             PtrVT, Ptr,
4132                             DAG.getConstant(Offsets[i], dl, PtrVT),
4133                             Flags);
4134 
4135     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4136                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4137                             MMOFlags, AAInfo, Ranges);
4138     Chains[ChainI] = L.getValue(1);
4139 
4140     if (MemVTs[i] != ValueVTs[i])
4141       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4142 
4143     Values[i] = L;
4144   }
4145 
4146   if (!ConstantMemory) {
4147     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4148                                 makeArrayRef(Chains.data(), ChainI));
4149     if (isVolatile)
4150       DAG.setRoot(Chain);
4151     else
4152       PendingLoads.push_back(Chain);
4153   }
4154 
4155   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4156                            DAG.getVTList(ValueVTs), Values));
4157 }
4158 
4159 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4160   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4161          "call visitStoreToSwiftError when backend supports swifterror");
4162 
4163   SmallVector<EVT, 4> ValueVTs;
4164   SmallVector<uint64_t, 4> Offsets;
4165   const Value *SrcV = I.getOperand(0);
4166   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4167                   SrcV->getType(), ValueVTs, &Offsets);
4168   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4169          "expect a single EVT for swifterror");
4170 
4171   SDValue Src = getValue(SrcV);
4172   // Create a virtual register, then update the virtual register.
4173   Register VReg =
4174       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4175   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4176   // Chain can be getRoot or getControlRoot.
4177   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4178                                       SDValue(Src.getNode(), Src.getResNo()));
4179   DAG.setRoot(CopyNode);
4180 }
4181 
4182 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4183   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4184          "call visitLoadFromSwiftError when backend supports swifterror");
4185 
4186   assert(!I.isVolatile() &&
4187          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4188          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4189          "Support volatile, non temporal, invariant for load_from_swift_error");
4190 
4191   const Value *SV = I.getOperand(0);
4192   Type *Ty = I.getType();
4193   AAMDNodes AAInfo;
4194   I.getAAMetadata(AAInfo);
4195   assert(
4196       (!AA ||
4197        !AA->pointsToConstantMemory(MemoryLocation(
4198            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4199            AAInfo))) &&
4200       "load_from_swift_error should not be constant memory");
4201 
4202   SmallVector<EVT, 4> ValueVTs;
4203   SmallVector<uint64_t, 4> Offsets;
4204   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4205                   ValueVTs, &Offsets);
4206   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4207          "expect a single EVT for swifterror");
4208 
4209   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4210   SDValue L = DAG.getCopyFromReg(
4211       getRoot(), getCurSDLoc(),
4212       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4213 
4214   setValue(&I, L);
4215 }
4216 
4217 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4218   if (I.isAtomic())
4219     return visitAtomicStore(I);
4220 
4221   const Value *SrcV = I.getOperand(0);
4222   const Value *PtrV = I.getOperand(1);
4223 
4224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4225   if (TLI.supportSwiftError()) {
4226     // Swifterror values can come from either a function parameter with
4227     // swifterror attribute or an alloca with swifterror attribute.
4228     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4229       if (Arg->hasSwiftErrorAttr())
4230         return visitStoreToSwiftError(I);
4231     }
4232 
4233     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4234       if (Alloca->isSwiftError())
4235         return visitStoreToSwiftError(I);
4236     }
4237   }
4238 
4239   SmallVector<EVT, 4> ValueVTs, MemVTs;
4240   SmallVector<uint64_t, 4> Offsets;
4241   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4242                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4243   unsigned NumValues = ValueVTs.size();
4244   if (NumValues == 0)
4245     return;
4246 
4247   // Get the lowered operands. Note that we do this after
4248   // checking if NumResults is zero, because with zero results
4249   // the operands won't have values in the map.
4250   SDValue Src = getValue(SrcV);
4251   SDValue Ptr = getValue(PtrV);
4252 
4253   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4254   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4255   SDLoc dl = getCurSDLoc();
4256   Align Alignment = I.getAlign();
4257   AAMDNodes AAInfo;
4258   I.getAAMetadata(AAInfo);
4259 
4260   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4261 
4262   // An aggregate load cannot wrap around the address space, so offsets to its
4263   // parts don't wrap either.
4264   SDNodeFlags Flags;
4265   Flags.setNoUnsignedWrap(true);
4266 
4267   unsigned ChainI = 0;
4268   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4269     // See visitLoad comments.
4270     if (ChainI == MaxParallelChains) {
4271       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4272                                   makeArrayRef(Chains.data(), ChainI));
4273       Root = Chain;
4274       ChainI = 0;
4275     }
4276     SDValue Add =
4277         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4278     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4279     if (MemVTs[i] != ValueVTs[i])
4280       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4281     SDValue St =
4282         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4283                      Alignment, MMOFlags, AAInfo);
4284     Chains[ChainI] = St;
4285   }
4286 
4287   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4288                                   makeArrayRef(Chains.data(), ChainI));
4289   DAG.setRoot(StoreNode);
4290 }
4291 
4292 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4293                                            bool IsCompressing) {
4294   SDLoc sdl = getCurSDLoc();
4295 
4296   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4297                                MaybeAlign &Alignment) {
4298     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4299     Src0 = I.getArgOperand(0);
4300     Ptr = I.getArgOperand(1);
4301     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4302     Mask = I.getArgOperand(3);
4303   };
4304   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4305                                     MaybeAlign &Alignment) {
4306     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4307     Src0 = I.getArgOperand(0);
4308     Ptr = I.getArgOperand(1);
4309     Mask = I.getArgOperand(2);
4310     Alignment = None;
4311   };
4312 
4313   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4314   MaybeAlign Alignment;
4315   if (IsCompressing)
4316     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4317   else
4318     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4319 
4320   SDValue Ptr = getValue(PtrOperand);
4321   SDValue Src0 = getValue(Src0Operand);
4322   SDValue Mask = getValue(MaskOperand);
4323   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4324 
4325   EVT VT = Src0.getValueType();
4326   if (!Alignment)
4327     Alignment = DAG.getEVTAlign(VT);
4328 
4329   AAMDNodes AAInfo;
4330   I.getAAMetadata(AAInfo);
4331 
4332   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4333       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4334       // TODO: Make MachineMemOperands aware of scalable
4335       // vectors.
4336       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4337   SDValue StoreNode =
4338       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4339                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4340   DAG.setRoot(StoreNode);
4341   setValue(&I, StoreNode);
4342 }
4343 
4344 // Get a uniform base for the Gather/Scatter intrinsic.
4345 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4346 // We try to represent it as a base pointer + vector of indices.
4347 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4348 // The first operand of the GEP may be a single pointer or a vector of pointers
4349 // Example:
4350 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4351 //  or
4352 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4353 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4354 //
4355 // When the first GEP operand is a single pointer - it is the uniform base we
4356 // are looking for. If first operand of the GEP is a splat vector - we
4357 // extract the splat value and use it as a uniform base.
4358 // In all other cases the function returns 'false'.
4359 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4360                            ISD::MemIndexType &IndexType, SDValue &Scale,
4361                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4362   SelectionDAG& DAG = SDB->DAG;
4363   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4364   const DataLayout &DL = DAG.getDataLayout();
4365 
4366   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4367 
4368   // Handle splat constant pointer.
4369   if (auto *C = dyn_cast<Constant>(Ptr)) {
4370     C = C->getSplatValue();
4371     if (!C)
4372       return false;
4373 
4374     Base = SDB->getValue(C);
4375 
4376     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4377     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4378     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4379     IndexType = ISD::SIGNED_SCALED;
4380     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4381     return true;
4382   }
4383 
4384   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4385   if (!GEP || GEP->getParent() != CurBB)
4386     return false;
4387 
4388   if (GEP->getNumOperands() != 2)
4389     return false;
4390 
4391   const Value *BasePtr = GEP->getPointerOperand();
4392   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4393 
4394   // Make sure the base is scalar and the index is a vector.
4395   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4396     return false;
4397 
4398   Base = SDB->getValue(BasePtr);
4399   Index = SDB->getValue(IndexVal);
4400   IndexType = ISD::SIGNED_SCALED;
4401   Scale = DAG.getTargetConstant(
4402               DL.getTypeAllocSize(GEP->getResultElementType()),
4403               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4404   return true;
4405 }
4406 
4407 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4408   SDLoc sdl = getCurSDLoc();
4409 
4410   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4411   const Value *Ptr = I.getArgOperand(1);
4412   SDValue Src0 = getValue(I.getArgOperand(0));
4413   SDValue Mask = getValue(I.getArgOperand(3));
4414   EVT VT = Src0.getValueType();
4415   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4416                         ->getMaybeAlignValue()
4417                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4418   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4419 
4420   AAMDNodes AAInfo;
4421   I.getAAMetadata(AAInfo);
4422 
4423   SDValue Base;
4424   SDValue Index;
4425   ISD::MemIndexType IndexType;
4426   SDValue Scale;
4427   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4428                                     I.getParent());
4429 
4430   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4431   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4432       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4433       // TODO: Make MachineMemOperands aware of scalable
4434       // vectors.
4435       MemoryLocation::UnknownSize, Alignment, AAInfo);
4436   if (!UniformBase) {
4437     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4438     Index = getValue(Ptr);
4439     IndexType = ISD::SIGNED_UNSCALED;
4440     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4441   }
4442 
4443   EVT IdxVT = Index.getValueType();
4444   EVT EltTy = IdxVT.getVectorElementType();
4445   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4446     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4447     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4448   }
4449 
4450   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4451   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4452                                          Ops, MMO, IndexType, false);
4453   DAG.setRoot(Scatter);
4454   setValue(&I, Scatter);
4455 }
4456 
4457 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4458   SDLoc sdl = getCurSDLoc();
4459 
4460   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4461                               MaybeAlign &Alignment) {
4462     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4463     Ptr = I.getArgOperand(0);
4464     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4465     Mask = I.getArgOperand(2);
4466     Src0 = I.getArgOperand(3);
4467   };
4468   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4469                                  MaybeAlign &Alignment) {
4470     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4471     Ptr = I.getArgOperand(0);
4472     Alignment = None;
4473     Mask = I.getArgOperand(1);
4474     Src0 = I.getArgOperand(2);
4475   };
4476 
4477   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4478   MaybeAlign Alignment;
4479   if (IsExpanding)
4480     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4481   else
4482     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4483 
4484   SDValue Ptr = getValue(PtrOperand);
4485   SDValue Src0 = getValue(Src0Operand);
4486   SDValue Mask = getValue(MaskOperand);
4487   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4488 
4489   EVT VT = Src0.getValueType();
4490   if (!Alignment)
4491     Alignment = DAG.getEVTAlign(VT);
4492 
4493   AAMDNodes AAInfo;
4494   I.getAAMetadata(AAInfo);
4495   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4496 
4497   // Do not serialize masked loads of constant memory with anything.
4498   MemoryLocation ML;
4499   if (VT.isScalableVector())
4500     ML = MemoryLocation::getAfter(PtrOperand);
4501   else
4502     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4503                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4504                            AAInfo);
4505   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4506 
4507   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4508 
4509   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4510       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4511       // TODO: Make MachineMemOperands aware of scalable
4512       // vectors.
4513       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4514 
4515   SDValue Load =
4516       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4517                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4518   if (AddToChain)
4519     PendingLoads.push_back(Load.getValue(1));
4520   setValue(&I, Load);
4521 }
4522 
4523 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4524   SDLoc sdl = getCurSDLoc();
4525 
4526   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4527   const Value *Ptr = I.getArgOperand(0);
4528   SDValue Src0 = getValue(I.getArgOperand(3));
4529   SDValue Mask = getValue(I.getArgOperand(2));
4530 
4531   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4532   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4533   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4534                         ->getMaybeAlignValue()
4535                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4536 
4537   AAMDNodes AAInfo;
4538   I.getAAMetadata(AAInfo);
4539   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4540 
4541   SDValue Root = DAG.getRoot();
4542   SDValue Base;
4543   SDValue Index;
4544   ISD::MemIndexType IndexType;
4545   SDValue Scale;
4546   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4547                                     I.getParent());
4548   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4549   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4550       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4551       // TODO: Make MachineMemOperands aware of scalable
4552       // vectors.
4553       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4554 
4555   if (!UniformBase) {
4556     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4557     Index = getValue(Ptr);
4558     IndexType = ISD::SIGNED_UNSCALED;
4559     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4560   }
4561 
4562   EVT IdxVT = Index.getValueType();
4563   EVT EltTy = IdxVT.getVectorElementType();
4564   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4565     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4566     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4567   }
4568 
4569   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4570   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4571                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4572 
4573   PendingLoads.push_back(Gather.getValue(1));
4574   setValue(&I, Gather);
4575 }
4576 
4577 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4578   SDLoc dl = getCurSDLoc();
4579   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4580   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4581   SyncScope::ID SSID = I.getSyncScopeID();
4582 
4583   SDValue InChain = getRoot();
4584 
4585   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4586   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4587 
4588   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4589   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4590 
4591   MachineFunction &MF = DAG.getMachineFunction();
4592   MachineMemOperand *MMO = MF.getMachineMemOperand(
4593       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4594       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4595       FailureOrdering);
4596 
4597   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4598                                    dl, MemVT, VTs, InChain,
4599                                    getValue(I.getPointerOperand()),
4600                                    getValue(I.getCompareOperand()),
4601                                    getValue(I.getNewValOperand()), MMO);
4602 
4603   SDValue OutChain = L.getValue(2);
4604 
4605   setValue(&I, L);
4606   DAG.setRoot(OutChain);
4607 }
4608 
4609 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4610   SDLoc dl = getCurSDLoc();
4611   ISD::NodeType NT;
4612   switch (I.getOperation()) {
4613   default: llvm_unreachable("Unknown atomicrmw operation");
4614   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4615   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4616   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4617   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4618   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4619   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4620   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4621   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4622   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4623   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4624   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4625   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4626   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4627   }
4628   AtomicOrdering Ordering = I.getOrdering();
4629   SyncScope::ID SSID = I.getSyncScopeID();
4630 
4631   SDValue InChain = getRoot();
4632 
4633   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4635   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4636 
4637   MachineFunction &MF = DAG.getMachineFunction();
4638   MachineMemOperand *MMO = MF.getMachineMemOperand(
4639       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4640       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4641 
4642   SDValue L =
4643     DAG.getAtomic(NT, dl, MemVT, InChain,
4644                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4645                   MMO);
4646 
4647   SDValue OutChain = L.getValue(1);
4648 
4649   setValue(&I, L);
4650   DAG.setRoot(OutChain);
4651 }
4652 
4653 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4654   SDLoc dl = getCurSDLoc();
4655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4656   SDValue Ops[3];
4657   Ops[0] = getRoot();
4658   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4659                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4660   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4661                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4662   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4663 }
4664 
4665 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4666   SDLoc dl = getCurSDLoc();
4667   AtomicOrdering Order = I.getOrdering();
4668   SyncScope::ID SSID = I.getSyncScopeID();
4669 
4670   SDValue InChain = getRoot();
4671 
4672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4673   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4674   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4675 
4676   if (!TLI.supportsUnalignedAtomics() &&
4677       I.getAlignment() < MemVT.getSizeInBits() / 8)
4678     report_fatal_error("Cannot generate unaligned atomic load");
4679 
4680   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4681 
4682   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4683       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4684       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4685 
4686   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4687 
4688   SDValue Ptr = getValue(I.getPointerOperand());
4689 
4690   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4691     // TODO: Once this is better exercised by tests, it should be merged with
4692     // the normal path for loads to prevent future divergence.
4693     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4694     if (MemVT != VT)
4695       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4696 
4697     setValue(&I, L);
4698     SDValue OutChain = L.getValue(1);
4699     if (!I.isUnordered())
4700       DAG.setRoot(OutChain);
4701     else
4702       PendingLoads.push_back(OutChain);
4703     return;
4704   }
4705 
4706   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4707                             Ptr, MMO);
4708 
4709   SDValue OutChain = L.getValue(1);
4710   if (MemVT != VT)
4711     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4712 
4713   setValue(&I, L);
4714   DAG.setRoot(OutChain);
4715 }
4716 
4717 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4718   SDLoc dl = getCurSDLoc();
4719 
4720   AtomicOrdering Ordering = I.getOrdering();
4721   SyncScope::ID SSID = I.getSyncScopeID();
4722 
4723   SDValue InChain = getRoot();
4724 
4725   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4726   EVT MemVT =
4727       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4728 
4729   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4730     report_fatal_error("Cannot generate unaligned atomic store");
4731 
4732   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4733 
4734   MachineFunction &MF = DAG.getMachineFunction();
4735   MachineMemOperand *MMO = MF.getMachineMemOperand(
4736       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4737       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4738 
4739   SDValue Val = getValue(I.getValueOperand());
4740   if (Val.getValueType() != MemVT)
4741     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4742   SDValue Ptr = getValue(I.getPointerOperand());
4743 
4744   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4745     // TODO: Once this is better exercised by tests, it should be merged with
4746     // the normal path for stores to prevent future divergence.
4747     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4748     DAG.setRoot(S);
4749     return;
4750   }
4751   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4752                                    Ptr, Val, MMO);
4753 
4754 
4755   DAG.setRoot(OutChain);
4756 }
4757 
4758 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4759 /// node.
4760 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4761                                                unsigned Intrinsic) {
4762   // Ignore the callsite's attributes. A specific call site may be marked with
4763   // readnone, but the lowering code will expect the chain based on the
4764   // definition.
4765   const Function *F = I.getCalledFunction();
4766   bool HasChain = !F->doesNotAccessMemory();
4767   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4768 
4769   // Build the operand list.
4770   SmallVector<SDValue, 8> Ops;
4771   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4772     if (OnlyLoad) {
4773       // We don't need to serialize loads against other loads.
4774       Ops.push_back(DAG.getRoot());
4775     } else {
4776       Ops.push_back(getRoot());
4777     }
4778   }
4779 
4780   // Info is set by getTgtMemInstrinsic
4781   TargetLowering::IntrinsicInfo Info;
4782   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4783   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4784                                                DAG.getMachineFunction(),
4785                                                Intrinsic);
4786 
4787   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4788   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4789       Info.opc == ISD::INTRINSIC_W_CHAIN)
4790     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4791                                         TLI.getPointerTy(DAG.getDataLayout())));
4792 
4793   // Add all operands of the call to the operand list.
4794   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4795     const Value *Arg = I.getArgOperand(i);
4796     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4797       Ops.push_back(getValue(Arg));
4798       continue;
4799     }
4800 
4801     // Use TargetConstant instead of a regular constant for immarg.
4802     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4803     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4804       assert(CI->getBitWidth() <= 64 &&
4805              "large intrinsic immediates not handled");
4806       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4807     } else {
4808       Ops.push_back(
4809           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4810     }
4811   }
4812 
4813   SmallVector<EVT, 4> ValueVTs;
4814   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4815 
4816   if (HasChain)
4817     ValueVTs.push_back(MVT::Other);
4818 
4819   SDVTList VTs = DAG.getVTList(ValueVTs);
4820 
4821   // Propagate fast-math-flags from IR to node(s).
4822   SDNodeFlags Flags;
4823   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4824     Flags.copyFMF(*FPMO);
4825   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4826 
4827   // Create the node.
4828   SDValue Result;
4829   if (IsTgtIntrinsic) {
4830     // This is target intrinsic that touches memory
4831     AAMDNodes AAInfo;
4832     I.getAAMetadata(AAInfo);
4833     Result =
4834         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4835                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4836                                 Info.align, Info.flags, Info.size, AAInfo);
4837   } else if (!HasChain) {
4838     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4839   } else if (!I.getType()->isVoidTy()) {
4840     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4841   } else {
4842     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4843   }
4844 
4845   if (HasChain) {
4846     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4847     if (OnlyLoad)
4848       PendingLoads.push_back(Chain);
4849     else
4850       DAG.setRoot(Chain);
4851   }
4852 
4853   if (!I.getType()->isVoidTy()) {
4854     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4855       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4856       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4857     } else
4858       Result = lowerRangeToAssertZExt(DAG, I, Result);
4859 
4860     MaybeAlign Alignment = I.getRetAlign();
4861     if (!Alignment)
4862       Alignment = F->getAttributes().getRetAlignment();
4863     // Insert `assertalign` node if there's an alignment.
4864     if (InsertAssertAlign && Alignment) {
4865       Result =
4866           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4867     }
4868 
4869     setValue(&I, Result);
4870   }
4871 }
4872 
4873 /// GetSignificand - Get the significand and build it into a floating-point
4874 /// number with exponent of 1:
4875 ///
4876 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4877 ///
4878 /// where Op is the hexadecimal representation of floating point value.
4879 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4880   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4881                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4882   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4883                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4884   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4885 }
4886 
4887 /// GetExponent - Get the exponent:
4888 ///
4889 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4890 ///
4891 /// where Op is the hexadecimal representation of floating point value.
4892 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4893                            const TargetLowering &TLI, const SDLoc &dl) {
4894   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4895                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4896   SDValue t1 = DAG.getNode(
4897       ISD::SRL, dl, MVT::i32, t0,
4898       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4899   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4900                            DAG.getConstant(127, dl, MVT::i32));
4901   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4902 }
4903 
4904 /// getF32Constant - Get 32-bit floating point constant.
4905 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4906                               const SDLoc &dl) {
4907   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4908                            MVT::f32);
4909 }
4910 
4911 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4912                                        SelectionDAG &DAG) {
4913   // TODO: What fast-math-flags should be set on the floating-point nodes?
4914 
4915   //   IntegerPartOfX = ((int32_t)(t0);
4916   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4917 
4918   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4919   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4920   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4921 
4922   //   IntegerPartOfX <<= 23;
4923   IntegerPartOfX = DAG.getNode(
4924       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4925       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4926                                   DAG.getDataLayout())));
4927 
4928   SDValue TwoToFractionalPartOfX;
4929   if (LimitFloatPrecision <= 6) {
4930     // For floating-point precision of 6:
4931     //
4932     //   TwoToFractionalPartOfX =
4933     //     0.997535578f +
4934     //       (0.735607626f + 0.252464424f * x) * x;
4935     //
4936     // error 0.0144103317, which is 6 bits
4937     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4938                              getF32Constant(DAG, 0x3e814304, dl));
4939     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4940                              getF32Constant(DAG, 0x3f3c50c8, dl));
4941     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4942     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4943                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4944   } else if (LimitFloatPrecision <= 12) {
4945     // For floating-point precision of 12:
4946     //
4947     //   TwoToFractionalPartOfX =
4948     //     0.999892986f +
4949     //       (0.696457318f +
4950     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4951     //
4952     // error 0.000107046256, which is 13 to 14 bits
4953     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4954                              getF32Constant(DAG, 0x3da235e3, dl));
4955     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4956                              getF32Constant(DAG, 0x3e65b8f3, dl));
4957     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4958     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4959                              getF32Constant(DAG, 0x3f324b07, dl));
4960     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4961     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4962                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4963   } else { // LimitFloatPrecision <= 18
4964     // For floating-point precision of 18:
4965     //
4966     //   TwoToFractionalPartOfX =
4967     //     0.999999982f +
4968     //       (0.693148872f +
4969     //         (0.240227044f +
4970     //           (0.554906021e-1f +
4971     //             (0.961591928e-2f +
4972     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4973     // error 2.47208000*10^(-7), which is better than 18 bits
4974     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4975                              getF32Constant(DAG, 0x3924b03e, dl));
4976     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4977                              getF32Constant(DAG, 0x3ab24b87, dl));
4978     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4979     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4980                              getF32Constant(DAG, 0x3c1d8c17, dl));
4981     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4982     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4983                              getF32Constant(DAG, 0x3d634a1d, dl));
4984     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4985     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4986                              getF32Constant(DAG, 0x3e75fe14, dl));
4987     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4988     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4989                               getF32Constant(DAG, 0x3f317234, dl));
4990     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4991     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4992                                          getF32Constant(DAG, 0x3f800000, dl));
4993   }
4994 
4995   // Add the exponent into the result in integer domain.
4996   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4997   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4998                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4999 }
5000 
5001 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5002 /// limited-precision mode.
5003 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5004                          const TargetLowering &TLI, SDNodeFlags Flags) {
5005   if (Op.getValueType() == MVT::f32 &&
5006       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5007 
5008     // Put the exponent in the right bit position for later addition to the
5009     // final result:
5010     //
5011     // t0 = Op * log2(e)
5012 
5013     // TODO: What fast-math-flags should be set here?
5014     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5015                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5016     return getLimitedPrecisionExp2(t0, dl, DAG);
5017   }
5018 
5019   // No special expansion.
5020   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5021 }
5022 
5023 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5024 /// limited-precision mode.
5025 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5026                          const TargetLowering &TLI, SDNodeFlags Flags) {
5027   // TODO: What fast-math-flags should be set on the floating-point nodes?
5028 
5029   if (Op.getValueType() == MVT::f32 &&
5030       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5031     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5032 
5033     // Scale the exponent by log(2).
5034     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5035     SDValue LogOfExponent =
5036         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5037                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5038 
5039     // Get the significand and build it into a floating-point number with
5040     // exponent of 1.
5041     SDValue X = GetSignificand(DAG, Op1, dl);
5042 
5043     SDValue LogOfMantissa;
5044     if (LimitFloatPrecision <= 6) {
5045       // For floating-point precision of 6:
5046       //
5047       //   LogofMantissa =
5048       //     -1.1609546f +
5049       //       (1.4034025f - 0.23903021f * x) * x;
5050       //
5051       // error 0.0034276066, which is better than 8 bits
5052       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5053                                getF32Constant(DAG, 0xbe74c456, dl));
5054       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5055                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5056       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5057       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5058                                   getF32Constant(DAG, 0x3f949a29, dl));
5059     } else if (LimitFloatPrecision <= 12) {
5060       // For floating-point precision of 12:
5061       //
5062       //   LogOfMantissa =
5063       //     -1.7417939f +
5064       //       (2.8212026f +
5065       //         (-1.4699568f +
5066       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5067       //
5068       // error 0.000061011436, which is 14 bits
5069       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5070                                getF32Constant(DAG, 0xbd67b6d6, dl));
5071       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5072                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5073       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5074       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5075                                getF32Constant(DAG, 0x3fbc278b, dl));
5076       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5077       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5078                                getF32Constant(DAG, 0x40348e95, dl));
5079       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5080       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5081                                   getF32Constant(DAG, 0x3fdef31a, dl));
5082     } else { // LimitFloatPrecision <= 18
5083       // For floating-point precision of 18:
5084       //
5085       //   LogOfMantissa =
5086       //     -2.1072184f +
5087       //       (4.2372794f +
5088       //         (-3.7029485f +
5089       //           (2.2781945f +
5090       //             (-0.87823314f +
5091       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5092       //
5093       // error 0.0000023660568, which is better than 18 bits
5094       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5095                                getF32Constant(DAG, 0xbc91e5ac, dl));
5096       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5097                                getF32Constant(DAG, 0x3e4350aa, dl));
5098       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5099       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5100                                getF32Constant(DAG, 0x3f60d3e3, dl));
5101       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5102       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5103                                getF32Constant(DAG, 0x4011cdf0, dl));
5104       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5105       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5106                                getF32Constant(DAG, 0x406cfd1c, dl));
5107       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5108       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5109                                getF32Constant(DAG, 0x408797cb, dl));
5110       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5111       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5112                                   getF32Constant(DAG, 0x4006dcab, dl));
5113     }
5114 
5115     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5116   }
5117 
5118   // No special expansion.
5119   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5120 }
5121 
5122 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5123 /// limited-precision mode.
5124 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5125                           const TargetLowering &TLI, SDNodeFlags Flags) {
5126   // TODO: What fast-math-flags should be set on the floating-point nodes?
5127 
5128   if (Op.getValueType() == MVT::f32 &&
5129       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5130     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5131 
5132     // Get the exponent.
5133     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5134 
5135     // Get the significand and build it into a floating-point number with
5136     // exponent of 1.
5137     SDValue X = GetSignificand(DAG, Op1, dl);
5138 
5139     // Different possible minimax approximations of significand in
5140     // floating-point for various degrees of accuracy over [1,2].
5141     SDValue Log2ofMantissa;
5142     if (LimitFloatPrecision <= 6) {
5143       // For floating-point precision of 6:
5144       //
5145       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5146       //
5147       // error 0.0049451742, which is more than 7 bits
5148       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5149                                getF32Constant(DAG, 0xbeb08fe0, dl));
5150       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5151                                getF32Constant(DAG, 0x40019463, dl));
5152       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5153       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5154                                    getF32Constant(DAG, 0x3fd6633d, dl));
5155     } else if (LimitFloatPrecision <= 12) {
5156       // For floating-point precision of 12:
5157       //
5158       //   Log2ofMantissa =
5159       //     -2.51285454f +
5160       //       (4.07009056f +
5161       //         (-2.12067489f +
5162       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5163       //
5164       // error 0.0000876136000, which is better than 13 bits
5165       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5166                                getF32Constant(DAG, 0xbda7262e, dl));
5167       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5168                                getF32Constant(DAG, 0x3f25280b, dl));
5169       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5170       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5171                                getF32Constant(DAG, 0x4007b923, dl));
5172       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5173       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5174                                getF32Constant(DAG, 0x40823e2f, dl));
5175       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5176       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5177                                    getF32Constant(DAG, 0x4020d29c, dl));
5178     } else { // LimitFloatPrecision <= 18
5179       // For floating-point precision of 18:
5180       //
5181       //   Log2ofMantissa =
5182       //     -3.0400495f +
5183       //       (6.1129976f +
5184       //         (-5.3420409f +
5185       //           (3.2865683f +
5186       //             (-1.2669343f +
5187       //               (0.27515199f -
5188       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5189       //
5190       // error 0.0000018516, which is better than 18 bits
5191       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5192                                getF32Constant(DAG, 0xbcd2769e, dl));
5193       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5194                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5195       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5196       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5197                                getF32Constant(DAG, 0x3fa22ae7, dl));
5198       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5199       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5200                                getF32Constant(DAG, 0x40525723, dl));
5201       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5202       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5203                                getF32Constant(DAG, 0x40aaf200, dl));
5204       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5205       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5206                                getF32Constant(DAG, 0x40c39dad, dl));
5207       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5208       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5209                                    getF32Constant(DAG, 0x4042902c, dl));
5210     }
5211 
5212     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5213   }
5214 
5215   // No special expansion.
5216   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5217 }
5218 
5219 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5220 /// limited-precision mode.
5221 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5222                            const TargetLowering &TLI, SDNodeFlags Flags) {
5223   // TODO: What fast-math-flags should be set on the floating-point nodes?
5224 
5225   if (Op.getValueType() == MVT::f32 &&
5226       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5227     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5228 
5229     // Scale the exponent by log10(2) [0.30102999f].
5230     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5231     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5232                                         getF32Constant(DAG, 0x3e9a209a, dl));
5233 
5234     // Get the significand and build it into a floating-point number with
5235     // exponent of 1.
5236     SDValue X = GetSignificand(DAG, Op1, dl);
5237 
5238     SDValue Log10ofMantissa;
5239     if (LimitFloatPrecision <= 6) {
5240       // For floating-point precision of 6:
5241       //
5242       //   Log10ofMantissa =
5243       //     -0.50419619f +
5244       //       (0.60948995f - 0.10380950f * x) * x;
5245       //
5246       // error 0.0014886165, which is 6 bits
5247       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5248                                getF32Constant(DAG, 0xbdd49a13, dl));
5249       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5250                                getF32Constant(DAG, 0x3f1c0789, dl));
5251       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5252       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5253                                     getF32Constant(DAG, 0x3f011300, dl));
5254     } else if (LimitFloatPrecision <= 12) {
5255       // For floating-point precision of 12:
5256       //
5257       //   Log10ofMantissa =
5258       //     -0.64831180f +
5259       //       (0.91751397f +
5260       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5261       //
5262       // error 0.00019228036, which is better than 12 bits
5263       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5264                                getF32Constant(DAG, 0x3d431f31, dl));
5265       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5266                                getF32Constant(DAG, 0x3ea21fb2, dl));
5267       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5268       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5269                                getF32Constant(DAG, 0x3f6ae232, dl));
5270       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5271       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5272                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5273     } else { // LimitFloatPrecision <= 18
5274       // For floating-point precision of 18:
5275       //
5276       //   Log10ofMantissa =
5277       //     -0.84299375f +
5278       //       (1.5327582f +
5279       //         (-1.0688956f +
5280       //           (0.49102474f +
5281       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5282       //
5283       // error 0.0000037995730, which is better than 18 bits
5284       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5285                                getF32Constant(DAG, 0x3c5d51ce, dl));
5286       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5287                                getF32Constant(DAG, 0x3e00685a, dl));
5288       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5289       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5290                                getF32Constant(DAG, 0x3efb6798, dl));
5291       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5292       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5293                                getF32Constant(DAG, 0x3f88d192, dl));
5294       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5295       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5296                                getF32Constant(DAG, 0x3fc4316c, dl));
5297       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5298       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5299                                     getF32Constant(DAG, 0x3f57ce70, dl));
5300     }
5301 
5302     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5303   }
5304 
5305   // No special expansion.
5306   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5307 }
5308 
5309 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5310 /// limited-precision mode.
5311 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5312                           const TargetLowering &TLI, SDNodeFlags Flags) {
5313   if (Op.getValueType() == MVT::f32 &&
5314       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5315     return getLimitedPrecisionExp2(Op, dl, DAG);
5316 
5317   // No special expansion.
5318   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5319 }
5320 
5321 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5322 /// limited-precision mode with x == 10.0f.
5323 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5324                          SelectionDAG &DAG, const TargetLowering &TLI,
5325                          SDNodeFlags Flags) {
5326   bool IsExp10 = false;
5327   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5328       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5329     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5330       APFloat Ten(10.0f);
5331       IsExp10 = LHSC->isExactlyValue(Ten);
5332     }
5333   }
5334 
5335   // TODO: What fast-math-flags should be set on the FMUL node?
5336   if (IsExp10) {
5337     // Put the exponent in the right bit position for later addition to the
5338     // final result:
5339     //
5340     //   #define LOG2OF10 3.3219281f
5341     //   t0 = Op * LOG2OF10;
5342     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5343                              getF32Constant(DAG, 0x40549a78, dl));
5344     return getLimitedPrecisionExp2(t0, dl, DAG);
5345   }
5346 
5347   // No special expansion.
5348   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5349 }
5350 
5351 /// ExpandPowI - Expand a llvm.powi intrinsic.
5352 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5353                           SelectionDAG &DAG) {
5354   // If RHS is a constant, we can expand this out to a multiplication tree,
5355   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5356   // optimizing for size, we only want to do this if the expansion would produce
5357   // a small number of multiplies, otherwise we do the full expansion.
5358   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5359     // Get the exponent as a positive value.
5360     unsigned Val = RHSC->getSExtValue();
5361     if ((int)Val < 0) Val = -Val;
5362 
5363     // powi(x, 0) -> 1.0
5364     if (Val == 0)
5365       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5366 
5367     bool OptForSize = DAG.shouldOptForSize();
5368     if (!OptForSize ||
5369         // If optimizing for size, don't insert too many multiplies.
5370         // This inserts up to 5 multiplies.
5371         countPopulation(Val) + Log2_32(Val) < 7) {
5372       // We use the simple binary decomposition method to generate the multiply
5373       // sequence.  There are more optimal ways to do this (for example,
5374       // powi(x,15) generates one more multiply than it should), but this has
5375       // the benefit of being both really simple and much better than a libcall.
5376       SDValue Res;  // Logically starts equal to 1.0
5377       SDValue CurSquare = LHS;
5378       // TODO: Intrinsics should have fast-math-flags that propagate to these
5379       // nodes.
5380       while (Val) {
5381         if (Val & 1) {
5382           if (Res.getNode())
5383             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5384           else
5385             Res = CurSquare;  // 1.0*CurSquare.
5386         }
5387 
5388         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5389                                 CurSquare, CurSquare);
5390         Val >>= 1;
5391       }
5392 
5393       // If the original was negative, invert the result, producing 1/(x*x*x).
5394       if (RHSC->getSExtValue() < 0)
5395         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5396                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5397       return Res;
5398     }
5399   }
5400 
5401   // Otherwise, expand to a libcall.
5402   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5403 }
5404 
5405 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5406                             SDValue LHS, SDValue RHS, SDValue Scale,
5407                             SelectionDAG &DAG, const TargetLowering &TLI) {
5408   EVT VT = LHS.getValueType();
5409   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5410   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5411   LLVMContext &Ctx = *DAG.getContext();
5412 
5413   // If the type is legal but the operation isn't, this node might survive all
5414   // the way to operation legalization. If we end up there and we do not have
5415   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5416   // node.
5417 
5418   // Coax the legalizer into expanding the node during type legalization instead
5419   // by bumping the size by one bit. This will force it to Promote, enabling the
5420   // early expansion and avoiding the need to expand later.
5421 
5422   // We don't have to do this if Scale is 0; that can always be expanded, unless
5423   // it's a saturating signed operation. Those can experience true integer
5424   // division overflow, a case which we must avoid.
5425 
5426   // FIXME: We wouldn't have to do this (or any of the early
5427   // expansion/promotion) if it was possible to expand a libcall of an
5428   // illegal type during operation legalization. But it's not, so things
5429   // get a bit hacky.
5430   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5431   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5432       (TLI.isTypeLegal(VT) ||
5433        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5434     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5435         Opcode, VT, ScaleInt);
5436     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5437       EVT PromVT;
5438       if (VT.isScalarInteger())
5439         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5440       else if (VT.isVector()) {
5441         PromVT = VT.getVectorElementType();
5442         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5443         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5444       } else
5445         llvm_unreachable("Wrong VT for DIVFIX?");
5446       if (Signed) {
5447         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5448         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5449       } else {
5450         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5451         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5452       }
5453       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5454       // For saturating operations, we need to shift up the LHS to get the
5455       // proper saturation width, and then shift down again afterwards.
5456       if (Saturating)
5457         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5458                           DAG.getConstant(1, DL, ShiftTy));
5459       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5460       if (Saturating)
5461         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5462                           DAG.getConstant(1, DL, ShiftTy));
5463       return DAG.getZExtOrTrunc(Res, DL, VT);
5464     }
5465   }
5466 
5467   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5468 }
5469 
5470 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5471 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5472 static void
5473 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5474                      const SDValue &N) {
5475   switch (N.getOpcode()) {
5476   case ISD::CopyFromReg: {
5477     SDValue Op = N.getOperand(1);
5478     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5479                       Op.getValueType().getSizeInBits());
5480     return;
5481   }
5482   case ISD::BITCAST:
5483   case ISD::AssertZext:
5484   case ISD::AssertSext:
5485   case ISD::TRUNCATE:
5486     getUnderlyingArgRegs(Regs, N.getOperand(0));
5487     return;
5488   case ISD::BUILD_PAIR:
5489   case ISD::BUILD_VECTOR:
5490   case ISD::CONCAT_VECTORS:
5491     for (SDValue Op : N->op_values())
5492       getUnderlyingArgRegs(Regs, Op);
5493     return;
5494   default:
5495     return;
5496   }
5497 }
5498 
5499 /// If the DbgValueInst is a dbg_value of a function argument, create the
5500 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5501 /// instruction selection, they will be inserted to the entry BB.
5502 /// We don't currently support this for variadic dbg_values, as they shouldn't
5503 /// appear for function arguments or in the prologue.
5504 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5505     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5506     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5507   const Argument *Arg = dyn_cast<Argument>(V);
5508   if (!Arg)
5509     return false;
5510 
5511   MachineFunction &MF = DAG.getMachineFunction();
5512   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5513 
5514   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5515   // we've been asked to pursue.
5516   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5517                               bool Indirect) {
5518     if (Reg.isVirtual() && TM.Options.ValueTrackingVariableLocations) {
5519       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5520       // pointing at the VReg, which will be patched up later.
5521       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5522       auto MIB = BuildMI(MF, DL, Inst);
5523       MIB.addReg(Reg, RegState::Debug);
5524       MIB.addImm(0);
5525       MIB.addMetadata(Variable);
5526       auto *NewDIExpr = FragExpr;
5527       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5528       // the DIExpression.
5529       if (Indirect)
5530         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5531       MIB.addMetadata(NewDIExpr);
5532       return MIB;
5533     } else {
5534       // Create a completely standard DBG_VALUE.
5535       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5536       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5537     }
5538   };
5539 
5540   if (!IsDbgDeclare) {
5541     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5542     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5543     // the entry block.
5544     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5545     if (!IsInEntryBlock)
5546       return false;
5547 
5548     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5549     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5550     // variable that also is a param.
5551     //
5552     // Although, if we are at the top of the entry block already, we can still
5553     // emit using ArgDbgValue. This might catch some situations when the
5554     // dbg.value refers to an argument that isn't used in the entry block, so
5555     // any CopyToReg node would be optimized out and the only way to express
5556     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5557     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5558     // we should only emit as ArgDbgValue if the Variable is an argument to the
5559     // current function, and the dbg.value intrinsic is found in the entry
5560     // block.
5561     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5562         !DL->getInlinedAt();
5563     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5564     if (!IsInPrologue && !VariableIsFunctionInputArg)
5565       return false;
5566 
5567     // Here we assume that a function argument on IR level only can be used to
5568     // describe one input parameter on source level. If we for example have
5569     // source code like this
5570     //
5571     //    struct A { long x, y; };
5572     //    void foo(struct A a, long b) {
5573     //      ...
5574     //      b = a.x;
5575     //      ...
5576     //    }
5577     //
5578     // and IR like this
5579     //
5580     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5581     //  entry:
5582     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5583     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5584     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5585     //    ...
5586     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5587     //    ...
5588     //
5589     // then the last dbg.value is describing a parameter "b" using a value that
5590     // is an argument. But since we already has used %a1 to describe a parameter
5591     // we should not handle that last dbg.value here (that would result in an
5592     // incorrect hoisting of the DBG_VALUE to the function entry).
5593     // Notice that we allow one dbg.value per IR level argument, to accommodate
5594     // for the situation with fragments above.
5595     if (VariableIsFunctionInputArg) {
5596       unsigned ArgNo = Arg->getArgNo();
5597       if (ArgNo >= FuncInfo.DescribedArgs.size())
5598         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5599       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5600         return false;
5601       FuncInfo.DescribedArgs.set(ArgNo);
5602     }
5603   }
5604 
5605   bool IsIndirect = false;
5606   Optional<MachineOperand> Op;
5607   // Some arguments' frame index is recorded during argument lowering.
5608   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5609   if (FI != std::numeric_limits<int>::max())
5610     Op = MachineOperand::CreateFI(FI);
5611 
5612   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5613   if (!Op && N.getNode()) {
5614     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5615     Register Reg;
5616     if (ArgRegsAndSizes.size() == 1)
5617       Reg = ArgRegsAndSizes.front().first;
5618 
5619     if (Reg && Reg.isVirtual()) {
5620       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5621       Register PR = RegInfo.getLiveInPhysReg(Reg);
5622       if (PR)
5623         Reg = PR;
5624     }
5625     if (Reg) {
5626       Op = MachineOperand::CreateReg(Reg, false);
5627       IsIndirect = IsDbgDeclare;
5628     }
5629   }
5630 
5631   if (!Op && N.getNode()) {
5632     // Check if frame index is available.
5633     SDValue LCandidate = peekThroughBitcasts(N);
5634     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5635       if (FrameIndexSDNode *FINode =
5636           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5637         Op = MachineOperand::CreateFI(FINode->getIndex());
5638   }
5639 
5640   if (!Op) {
5641     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5642     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5643                                          SplitRegs) {
5644       unsigned Offset = 0;
5645       for (auto RegAndSize : SplitRegs) {
5646         // If the expression is already a fragment, the current register
5647         // offset+size might extend beyond the fragment. In this case, only
5648         // the register bits that are inside the fragment are relevant.
5649         int RegFragmentSizeInBits = RegAndSize.second;
5650         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5651           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5652           // The register is entirely outside the expression fragment,
5653           // so is irrelevant for debug info.
5654           if (Offset >= ExprFragmentSizeInBits)
5655             break;
5656           // The register is partially outside the expression fragment, only
5657           // the low bits within the fragment are relevant for debug info.
5658           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5659             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5660           }
5661         }
5662 
5663         auto FragmentExpr = DIExpression::createFragmentExpression(
5664             Expr, Offset, RegFragmentSizeInBits);
5665         Offset += RegAndSize.second;
5666         // If a valid fragment expression cannot be created, the variable's
5667         // correct value cannot be determined and so it is set as Undef.
5668         if (!FragmentExpr) {
5669           SDDbgValue *SDV = DAG.getConstantDbgValue(
5670               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5671           DAG.AddDbgValue(SDV, false);
5672           continue;
5673         }
5674         MachineInstr *NewMI =
5675             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
5676         FuncInfo.ArgDbgValues.push_back(NewMI);
5677       }
5678     };
5679 
5680     // Check if ValueMap has reg number.
5681     DenseMap<const Value *, Register>::const_iterator
5682       VMI = FuncInfo.ValueMap.find(V);
5683     if (VMI != FuncInfo.ValueMap.end()) {
5684       const auto &TLI = DAG.getTargetLoweringInfo();
5685       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5686                        V->getType(), None);
5687       if (RFV.occupiesMultipleRegs()) {
5688         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5689         return true;
5690       }
5691 
5692       Op = MachineOperand::CreateReg(VMI->second, false);
5693       IsIndirect = IsDbgDeclare;
5694     } else if (ArgRegsAndSizes.size() > 1) {
5695       // This was split due to the calling convention, and no virtual register
5696       // mapping exists for the value.
5697       splitMultiRegDbgValue(ArgRegsAndSizes);
5698       return true;
5699     }
5700   }
5701 
5702   if (!Op)
5703     return false;
5704 
5705   assert(Variable->isValidLocationForIntrinsic(DL) &&
5706          "Expected inlined-at fields to agree");
5707   MachineInstr *NewMI = nullptr;
5708 
5709   if (Op->isReg())
5710     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5711   else
5712     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5713                     Variable, Expr);
5714 
5715   FuncInfo.ArgDbgValues.push_back(NewMI);
5716   return true;
5717 }
5718 
5719 /// Return the appropriate SDDbgValue based on N.
5720 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5721                                              DILocalVariable *Variable,
5722                                              DIExpression *Expr,
5723                                              const DebugLoc &dl,
5724                                              unsigned DbgSDNodeOrder) {
5725   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5726     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5727     // stack slot locations.
5728     //
5729     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5730     // debug values here after optimization:
5731     //
5732     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5733     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5734     //
5735     // Both describe the direct values of their associated variables.
5736     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5737                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5738   }
5739   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5740                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5741 }
5742 
5743 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5744   switch (Intrinsic) {
5745   case Intrinsic::smul_fix:
5746     return ISD::SMULFIX;
5747   case Intrinsic::umul_fix:
5748     return ISD::UMULFIX;
5749   case Intrinsic::smul_fix_sat:
5750     return ISD::SMULFIXSAT;
5751   case Intrinsic::umul_fix_sat:
5752     return ISD::UMULFIXSAT;
5753   case Intrinsic::sdiv_fix:
5754     return ISD::SDIVFIX;
5755   case Intrinsic::udiv_fix:
5756     return ISD::UDIVFIX;
5757   case Intrinsic::sdiv_fix_sat:
5758     return ISD::SDIVFIXSAT;
5759   case Intrinsic::udiv_fix_sat:
5760     return ISD::UDIVFIXSAT;
5761   default:
5762     llvm_unreachable("Unhandled fixed point intrinsic");
5763   }
5764 }
5765 
5766 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5767                                            const char *FunctionName) {
5768   assert(FunctionName && "FunctionName must not be nullptr");
5769   SDValue Callee = DAG.getExternalSymbol(
5770       FunctionName,
5771       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5772   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5773 }
5774 
5775 /// Given a @llvm.call.preallocated.setup, return the corresponding
5776 /// preallocated call.
5777 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5778   assert(cast<CallBase>(PreallocatedSetup)
5779                  ->getCalledFunction()
5780                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5781          "expected call_preallocated_setup Value");
5782   for (auto *U : PreallocatedSetup->users()) {
5783     auto *UseCall = cast<CallBase>(U);
5784     const Function *Fn = UseCall->getCalledFunction();
5785     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5786       return UseCall;
5787     }
5788   }
5789   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5790 }
5791 
5792 /// Lower the call to the specified intrinsic function.
5793 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5794                                              unsigned Intrinsic) {
5795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5796   SDLoc sdl = getCurSDLoc();
5797   DebugLoc dl = getCurDebugLoc();
5798   SDValue Res;
5799 
5800   SDNodeFlags Flags;
5801   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5802     Flags.copyFMF(*FPOp);
5803 
5804   switch (Intrinsic) {
5805   default:
5806     // By default, turn this into a target intrinsic node.
5807     visitTargetIntrinsic(I, Intrinsic);
5808     return;
5809   case Intrinsic::vscale: {
5810     match(&I, m_VScale(DAG.getDataLayout()));
5811     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5812     setValue(&I,
5813              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5814     return;
5815   }
5816   case Intrinsic::vastart:  visitVAStart(I); return;
5817   case Intrinsic::vaend:    visitVAEnd(I); return;
5818   case Intrinsic::vacopy:   visitVACopy(I); return;
5819   case Intrinsic::returnaddress:
5820     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5821                              TLI.getPointerTy(DAG.getDataLayout()),
5822                              getValue(I.getArgOperand(0))));
5823     return;
5824   case Intrinsic::addressofreturnaddress:
5825     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5826                              TLI.getPointerTy(DAG.getDataLayout())));
5827     return;
5828   case Intrinsic::sponentry:
5829     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5830                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5831     return;
5832   case Intrinsic::frameaddress:
5833     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5834                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5835                              getValue(I.getArgOperand(0))));
5836     return;
5837   case Intrinsic::read_volatile_register:
5838   case Intrinsic::read_register: {
5839     Value *Reg = I.getArgOperand(0);
5840     SDValue Chain = getRoot();
5841     SDValue RegName =
5842         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5843     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5844     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5845       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5846     setValue(&I, Res);
5847     DAG.setRoot(Res.getValue(1));
5848     return;
5849   }
5850   case Intrinsic::write_register: {
5851     Value *Reg = I.getArgOperand(0);
5852     Value *RegValue = I.getArgOperand(1);
5853     SDValue Chain = getRoot();
5854     SDValue RegName =
5855         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5856     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5857                             RegName, getValue(RegValue)));
5858     return;
5859   }
5860   case Intrinsic::memcpy: {
5861     const auto &MCI = cast<MemCpyInst>(I);
5862     SDValue Op1 = getValue(I.getArgOperand(0));
5863     SDValue Op2 = getValue(I.getArgOperand(1));
5864     SDValue Op3 = getValue(I.getArgOperand(2));
5865     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5866     Align DstAlign = MCI.getDestAlign().valueOrOne();
5867     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5868     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5869     bool isVol = MCI.isVolatile();
5870     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5871     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5872     // node.
5873     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5874     AAMDNodes AAInfo;
5875     I.getAAMetadata(AAInfo);
5876     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5877                                /* AlwaysInline */ false, isTC,
5878                                MachinePointerInfo(I.getArgOperand(0)),
5879                                MachinePointerInfo(I.getArgOperand(1)), AAInfo);
5880     updateDAGForMaybeTailCall(MC);
5881     return;
5882   }
5883   case Intrinsic::memcpy_inline: {
5884     const auto &MCI = cast<MemCpyInlineInst>(I);
5885     SDValue Dst = getValue(I.getArgOperand(0));
5886     SDValue Src = getValue(I.getArgOperand(1));
5887     SDValue Size = getValue(I.getArgOperand(2));
5888     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5889     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5890     Align DstAlign = MCI.getDestAlign().valueOrOne();
5891     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5892     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5893     bool isVol = MCI.isVolatile();
5894     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5895     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5896     // node.
5897     AAMDNodes AAInfo;
5898     I.getAAMetadata(AAInfo);
5899     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5900                                /* AlwaysInline */ true, isTC,
5901                                MachinePointerInfo(I.getArgOperand(0)),
5902                                MachinePointerInfo(I.getArgOperand(1)), AAInfo);
5903     updateDAGForMaybeTailCall(MC);
5904     return;
5905   }
5906   case Intrinsic::memset: {
5907     const auto &MSI = cast<MemSetInst>(I);
5908     SDValue Op1 = getValue(I.getArgOperand(0));
5909     SDValue Op2 = getValue(I.getArgOperand(1));
5910     SDValue Op3 = getValue(I.getArgOperand(2));
5911     // @llvm.memset defines 0 and 1 to both mean no alignment.
5912     Align Alignment = MSI.getDestAlign().valueOrOne();
5913     bool isVol = MSI.isVolatile();
5914     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5915     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5916     AAMDNodes AAInfo;
5917     I.getAAMetadata(AAInfo);
5918     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5919                                MachinePointerInfo(I.getArgOperand(0)), AAInfo);
5920     updateDAGForMaybeTailCall(MS);
5921     return;
5922   }
5923   case Intrinsic::memmove: {
5924     const auto &MMI = cast<MemMoveInst>(I);
5925     SDValue Op1 = getValue(I.getArgOperand(0));
5926     SDValue Op2 = getValue(I.getArgOperand(1));
5927     SDValue Op3 = getValue(I.getArgOperand(2));
5928     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5929     Align DstAlign = MMI.getDestAlign().valueOrOne();
5930     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5931     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5932     bool isVol = MMI.isVolatile();
5933     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5934     // FIXME: Support passing different dest/src alignments to the memmove DAG
5935     // node.
5936     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5937     AAMDNodes AAInfo;
5938     I.getAAMetadata(AAInfo);
5939     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5940                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5941                                 MachinePointerInfo(I.getArgOperand(1)), AAInfo);
5942     updateDAGForMaybeTailCall(MM);
5943     return;
5944   }
5945   case Intrinsic::memcpy_element_unordered_atomic: {
5946     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5947     SDValue Dst = getValue(MI.getRawDest());
5948     SDValue Src = getValue(MI.getRawSource());
5949     SDValue Length = getValue(MI.getLength());
5950 
5951     unsigned DstAlign = MI.getDestAlignment();
5952     unsigned SrcAlign = MI.getSourceAlignment();
5953     Type *LengthTy = MI.getLength()->getType();
5954     unsigned ElemSz = MI.getElementSizeInBytes();
5955     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5956     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5957                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5958                                      MachinePointerInfo(MI.getRawDest()),
5959                                      MachinePointerInfo(MI.getRawSource()));
5960     updateDAGForMaybeTailCall(MC);
5961     return;
5962   }
5963   case Intrinsic::memmove_element_unordered_atomic: {
5964     auto &MI = cast<AtomicMemMoveInst>(I);
5965     SDValue Dst = getValue(MI.getRawDest());
5966     SDValue Src = getValue(MI.getRawSource());
5967     SDValue Length = getValue(MI.getLength());
5968 
5969     unsigned DstAlign = MI.getDestAlignment();
5970     unsigned SrcAlign = MI.getSourceAlignment();
5971     Type *LengthTy = MI.getLength()->getType();
5972     unsigned ElemSz = MI.getElementSizeInBytes();
5973     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5974     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5975                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5976                                       MachinePointerInfo(MI.getRawDest()),
5977                                       MachinePointerInfo(MI.getRawSource()));
5978     updateDAGForMaybeTailCall(MC);
5979     return;
5980   }
5981   case Intrinsic::memset_element_unordered_atomic: {
5982     auto &MI = cast<AtomicMemSetInst>(I);
5983     SDValue Dst = getValue(MI.getRawDest());
5984     SDValue Val = getValue(MI.getValue());
5985     SDValue Length = getValue(MI.getLength());
5986 
5987     unsigned DstAlign = MI.getDestAlignment();
5988     Type *LengthTy = MI.getLength()->getType();
5989     unsigned ElemSz = MI.getElementSizeInBytes();
5990     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5991     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5992                                      LengthTy, ElemSz, isTC,
5993                                      MachinePointerInfo(MI.getRawDest()));
5994     updateDAGForMaybeTailCall(MC);
5995     return;
5996   }
5997   case Intrinsic::call_preallocated_setup: {
5998     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5999     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6000     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6001                               getRoot(), SrcValue);
6002     setValue(&I, Res);
6003     DAG.setRoot(Res);
6004     return;
6005   }
6006   case Intrinsic::call_preallocated_arg: {
6007     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6008     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6009     SDValue Ops[3];
6010     Ops[0] = getRoot();
6011     Ops[1] = SrcValue;
6012     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6013                                    MVT::i32); // arg index
6014     SDValue Res = DAG.getNode(
6015         ISD::PREALLOCATED_ARG, sdl,
6016         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6017     setValue(&I, Res);
6018     DAG.setRoot(Res.getValue(1));
6019     return;
6020   }
6021   case Intrinsic::dbg_addr:
6022   case Intrinsic::dbg_declare: {
6023     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6024     // they are non-variadic.
6025     const auto &DI = cast<DbgVariableIntrinsic>(I);
6026     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6027     DILocalVariable *Variable = DI.getVariable();
6028     DIExpression *Expression = DI.getExpression();
6029     dropDanglingDebugInfo(Variable, Expression);
6030     assert(Variable && "Missing variable");
6031     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6032                       << "\n");
6033     // Check if address has undef value.
6034     const Value *Address = DI.getVariableLocationOp(0);
6035     if (!Address || isa<UndefValue>(Address) ||
6036         (Address->use_empty() && !isa<Argument>(Address))) {
6037       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6038                         << " (bad/undef/unused-arg address)\n");
6039       return;
6040     }
6041 
6042     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6043 
6044     // Check if this variable can be described by a frame index, typically
6045     // either as a static alloca or a byval parameter.
6046     int FI = std::numeric_limits<int>::max();
6047     if (const auto *AI =
6048             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6049       if (AI->isStaticAlloca()) {
6050         auto I = FuncInfo.StaticAllocaMap.find(AI);
6051         if (I != FuncInfo.StaticAllocaMap.end())
6052           FI = I->second;
6053       }
6054     } else if (const auto *Arg = dyn_cast<Argument>(
6055                    Address->stripInBoundsConstantOffsets())) {
6056       FI = FuncInfo.getArgumentFrameIndex(Arg);
6057     }
6058 
6059     // llvm.dbg.addr is control dependent and always generates indirect
6060     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6061     // the MachineFunction variable table.
6062     if (FI != std::numeric_limits<int>::max()) {
6063       if (Intrinsic == Intrinsic::dbg_addr) {
6064         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6065             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6066             dl, SDNodeOrder);
6067         DAG.AddDbgValue(SDV, isParameter);
6068       } else {
6069         LLVM_DEBUG(dbgs() << "Skipping " << DI
6070                           << " (variable info stashed in MF side table)\n");
6071       }
6072       return;
6073     }
6074 
6075     SDValue &N = NodeMap[Address];
6076     if (!N.getNode() && isa<Argument>(Address))
6077       // Check unused arguments map.
6078       N = UnusedArgNodeMap[Address];
6079     SDDbgValue *SDV;
6080     if (N.getNode()) {
6081       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6082         Address = BCI->getOperand(0);
6083       // Parameters are handled specially.
6084       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6085       if (isParameter && FINode) {
6086         // Byval parameter. We have a frame index at this point.
6087         SDV =
6088             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6089                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6090       } else if (isa<Argument>(Address)) {
6091         // Address is an argument, so try to emit its dbg value using
6092         // virtual register info from the FuncInfo.ValueMap.
6093         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6094         return;
6095       } else {
6096         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6097                               true, dl, SDNodeOrder);
6098       }
6099       DAG.AddDbgValue(SDV, isParameter);
6100     } else {
6101       // If Address is an argument then try to emit its dbg value using
6102       // virtual register info from the FuncInfo.ValueMap.
6103       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6104                                     N)) {
6105         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6106                           << " (could not emit func-arg dbg_value)\n");
6107       }
6108     }
6109     return;
6110   }
6111   case Intrinsic::dbg_label: {
6112     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6113     DILabel *Label = DI.getLabel();
6114     assert(Label && "Missing label");
6115 
6116     SDDbgLabel *SDV;
6117     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6118     DAG.AddDbgLabel(SDV);
6119     return;
6120   }
6121   case Intrinsic::dbg_value: {
6122     const DbgValueInst &DI = cast<DbgValueInst>(I);
6123     assert(DI.getVariable() && "Missing variable");
6124 
6125     DILocalVariable *Variable = DI.getVariable();
6126     DIExpression *Expression = DI.getExpression();
6127     dropDanglingDebugInfo(Variable, Expression);
6128     SmallVector<Value *, 4> Values(DI.getValues());
6129     if (Values.empty())
6130       return;
6131 
6132     if (std::count(Values.begin(), Values.end(), nullptr))
6133       return;
6134 
6135     bool IsVariadic = DI.hasArgList();
6136     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6137                           SDNodeOrder, IsVariadic))
6138       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6139     return;
6140   }
6141 
6142   case Intrinsic::eh_typeid_for: {
6143     // Find the type id for the given typeinfo.
6144     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6145     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6146     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6147     setValue(&I, Res);
6148     return;
6149   }
6150 
6151   case Intrinsic::eh_return_i32:
6152   case Intrinsic::eh_return_i64:
6153     DAG.getMachineFunction().setCallsEHReturn(true);
6154     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6155                             MVT::Other,
6156                             getControlRoot(),
6157                             getValue(I.getArgOperand(0)),
6158                             getValue(I.getArgOperand(1))));
6159     return;
6160   case Intrinsic::eh_unwind_init:
6161     DAG.getMachineFunction().setCallsUnwindInit(true);
6162     return;
6163   case Intrinsic::eh_dwarf_cfa:
6164     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6165                              TLI.getPointerTy(DAG.getDataLayout()),
6166                              getValue(I.getArgOperand(0))));
6167     return;
6168   case Intrinsic::eh_sjlj_callsite: {
6169     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6170     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6171     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6172     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6173 
6174     MMI.setCurrentCallSite(CI->getZExtValue());
6175     return;
6176   }
6177   case Intrinsic::eh_sjlj_functioncontext: {
6178     // Get and store the index of the function context.
6179     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6180     AllocaInst *FnCtx =
6181       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6182     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6183     MFI.setFunctionContextIndex(FI);
6184     return;
6185   }
6186   case Intrinsic::eh_sjlj_setjmp: {
6187     SDValue Ops[2];
6188     Ops[0] = getRoot();
6189     Ops[1] = getValue(I.getArgOperand(0));
6190     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6191                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6192     setValue(&I, Op.getValue(0));
6193     DAG.setRoot(Op.getValue(1));
6194     return;
6195   }
6196   case Intrinsic::eh_sjlj_longjmp:
6197     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6198                             getRoot(), getValue(I.getArgOperand(0))));
6199     return;
6200   case Intrinsic::eh_sjlj_setup_dispatch:
6201     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6202                             getRoot()));
6203     return;
6204   case Intrinsic::masked_gather:
6205     visitMaskedGather(I);
6206     return;
6207   case Intrinsic::masked_load:
6208     visitMaskedLoad(I);
6209     return;
6210   case Intrinsic::masked_scatter:
6211     visitMaskedScatter(I);
6212     return;
6213   case Intrinsic::masked_store:
6214     visitMaskedStore(I);
6215     return;
6216   case Intrinsic::masked_expandload:
6217     visitMaskedLoad(I, true /* IsExpanding */);
6218     return;
6219   case Intrinsic::masked_compressstore:
6220     visitMaskedStore(I, true /* IsCompressing */);
6221     return;
6222   case Intrinsic::powi:
6223     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6224                             getValue(I.getArgOperand(1)), DAG));
6225     return;
6226   case Intrinsic::log:
6227     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6228     return;
6229   case Intrinsic::log2:
6230     setValue(&I,
6231              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6232     return;
6233   case Intrinsic::log10:
6234     setValue(&I,
6235              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6236     return;
6237   case Intrinsic::exp:
6238     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6239     return;
6240   case Intrinsic::exp2:
6241     setValue(&I,
6242              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6243     return;
6244   case Intrinsic::pow:
6245     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6246                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6247     return;
6248   case Intrinsic::sqrt:
6249   case Intrinsic::fabs:
6250   case Intrinsic::sin:
6251   case Intrinsic::cos:
6252   case Intrinsic::floor:
6253   case Intrinsic::ceil:
6254   case Intrinsic::trunc:
6255   case Intrinsic::rint:
6256   case Intrinsic::nearbyint:
6257   case Intrinsic::round:
6258   case Intrinsic::roundeven:
6259   case Intrinsic::canonicalize: {
6260     unsigned Opcode;
6261     switch (Intrinsic) {
6262     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6263     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6264     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6265     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6266     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6267     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6268     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6269     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6270     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6271     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6272     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6273     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6274     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6275     }
6276 
6277     setValue(&I, DAG.getNode(Opcode, sdl,
6278                              getValue(I.getArgOperand(0)).getValueType(),
6279                              getValue(I.getArgOperand(0)), Flags));
6280     return;
6281   }
6282   case Intrinsic::lround:
6283   case Intrinsic::llround:
6284   case Intrinsic::lrint:
6285   case Intrinsic::llrint: {
6286     unsigned Opcode;
6287     switch (Intrinsic) {
6288     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6289     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6290     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6291     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6292     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6293     }
6294 
6295     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6296     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6297                              getValue(I.getArgOperand(0))));
6298     return;
6299   }
6300   case Intrinsic::minnum:
6301     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6302                              getValue(I.getArgOperand(0)).getValueType(),
6303                              getValue(I.getArgOperand(0)),
6304                              getValue(I.getArgOperand(1)), Flags));
6305     return;
6306   case Intrinsic::maxnum:
6307     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6308                              getValue(I.getArgOperand(0)).getValueType(),
6309                              getValue(I.getArgOperand(0)),
6310                              getValue(I.getArgOperand(1)), Flags));
6311     return;
6312   case Intrinsic::minimum:
6313     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6314                              getValue(I.getArgOperand(0)).getValueType(),
6315                              getValue(I.getArgOperand(0)),
6316                              getValue(I.getArgOperand(1)), Flags));
6317     return;
6318   case Intrinsic::maximum:
6319     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6320                              getValue(I.getArgOperand(0)).getValueType(),
6321                              getValue(I.getArgOperand(0)),
6322                              getValue(I.getArgOperand(1)), Flags));
6323     return;
6324   case Intrinsic::copysign:
6325     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6326                              getValue(I.getArgOperand(0)).getValueType(),
6327                              getValue(I.getArgOperand(0)),
6328                              getValue(I.getArgOperand(1)), Flags));
6329     return;
6330   case Intrinsic::arithmetic_fence: {
6331     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6332                              getValue(I.getArgOperand(0)).getValueType(),
6333                              getValue(I.getArgOperand(0)), Flags));
6334     return;
6335   }
6336   case Intrinsic::fma:
6337     setValue(&I, DAG.getNode(
6338                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6339                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6340                      getValue(I.getArgOperand(2)), Flags));
6341     return;
6342 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6343   case Intrinsic::INTRINSIC:
6344 #include "llvm/IR/ConstrainedOps.def"
6345     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6346     return;
6347 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6348 #include "llvm/IR/VPIntrinsics.def"
6349     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6350     return;
6351   case Intrinsic::fmuladd: {
6352     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6353     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6354         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6355       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6356                                getValue(I.getArgOperand(0)).getValueType(),
6357                                getValue(I.getArgOperand(0)),
6358                                getValue(I.getArgOperand(1)),
6359                                getValue(I.getArgOperand(2)), Flags));
6360     } else {
6361       // TODO: Intrinsic calls should have fast-math-flags.
6362       SDValue Mul = DAG.getNode(
6363           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6364           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6365       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6366                                 getValue(I.getArgOperand(0)).getValueType(),
6367                                 Mul, getValue(I.getArgOperand(2)), Flags);
6368       setValue(&I, Add);
6369     }
6370     return;
6371   }
6372   case Intrinsic::convert_to_fp16:
6373     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6374                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6375                                          getValue(I.getArgOperand(0)),
6376                                          DAG.getTargetConstant(0, sdl,
6377                                                                MVT::i32))));
6378     return;
6379   case Intrinsic::convert_from_fp16:
6380     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6381                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6382                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6383                                          getValue(I.getArgOperand(0)))));
6384     return;
6385   case Intrinsic::fptosi_sat: {
6386     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6387     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6388                              getValue(I.getArgOperand(0)),
6389                              DAG.getValueType(VT.getScalarType())));
6390     return;
6391   }
6392   case Intrinsic::fptoui_sat: {
6393     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6394     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6395                              getValue(I.getArgOperand(0)),
6396                              DAG.getValueType(VT.getScalarType())));
6397     return;
6398   }
6399   case Intrinsic::set_rounding:
6400     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6401                       {getRoot(), getValue(I.getArgOperand(0))});
6402     setValue(&I, Res);
6403     DAG.setRoot(Res.getValue(0));
6404     return;
6405   case Intrinsic::pcmarker: {
6406     SDValue Tmp = getValue(I.getArgOperand(0));
6407     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6408     return;
6409   }
6410   case Intrinsic::isnan: {
6411     const DataLayout DLayout = DAG.getDataLayout();
6412     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6413     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6414     MachineFunction &MF = DAG.getMachineFunction();
6415     const Function &F = MF.getFunction();
6416     SDValue Op = getValue(I.getArgOperand(0));
6417     SDNodeFlags Flags;
6418     Flags.setNoFPExcept(
6419         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6420 
6421     // If ISD::ISNAN should be expanded, do it right now, because the expansion
6422     // can use illegal types. Making expansion early allows to legalize these
6423     // types prior to selection.
6424     if (!TLI.isOperationLegalOrCustom(ISD::ISNAN, ArgVT)) {
6425       SDValue Result = TLI.expandISNAN(DestVT, Op, Flags, sdl, DAG);
6426       setValue(&I, Result);
6427       return;
6428     }
6429 
6430     SDValue V = DAG.getNode(ISD::ISNAN, sdl, DestVT, Op, Flags);
6431     setValue(&I, V);
6432     return;
6433   }
6434   case Intrinsic::readcyclecounter: {
6435     SDValue Op = getRoot();
6436     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6437                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6438     setValue(&I, Res);
6439     DAG.setRoot(Res.getValue(1));
6440     return;
6441   }
6442   case Intrinsic::bitreverse:
6443     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6444                              getValue(I.getArgOperand(0)).getValueType(),
6445                              getValue(I.getArgOperand(0))));
6446     return;
6447   case Intrinsic::bswap:
6448     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6449                              getValue(I.getArgOperand(0)).getValueType(),
6450                              getValue(I.getArgOperand(0))));
6451     return;
6452   case Intrinsic::cttz: {
6453     SDValue Arg = getValue(I.getArgOperand(0));
6454     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6455     EVT Ty = Arg.getValueType();
6456     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6457                              sdl, Ty, Arg));
6458     return;
6459   }
6460   case Intrinsic::ctlz: {
6461     SDValue Arg = getValue(I.getArgOperand(0));
6462     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6463     EVT Ty = Arg.getValueType();
6464     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6465                              sdl, Ty, Arg));
6466     return;
6467   }
6468   case Intrinsic::ctpop: {
6469     SDValue Arg = getValue(I.getArgOperand(0));
6470     EVT Ty = Arg.getValueType();
6471     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6472     return;
6473   }
6474   case Intrinsic::fshl:
6475   case Intrinsic::fshr: {
6476     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6477     SDValue X = getValue(I.getArgOperand(0));
6478     SDValue Y = getValue(I.getArgOperand(1));
6479     SDValue Z = getValue(I.getArgOperand(2));
6480     EVT VT = X.getValueType();
6481 
6482     if (X == Y) {
6483       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6484       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6485     } else {
6486       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6487       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6488     }
6489     return;
6490   }
6491   case Intrinsic::sadd_sat: {
6492     SDValue Op1 = getValue(I.getArgOperand(0));
6493     SDValue Op2 = getValue(I.getArgOperand(1));
6494     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6495     return;
6496   }
6497   case Intrinsic::uadd_sat: {
6498     SDValue Op1 = getValue(I.getArgOperand(0));
6499     SDValue Op2 = getValue(I.getArgOperand(1));
6500     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6501     return;
6502   }
6503   case Intrinsic::ssub_sat: {
6504     SDValue Op1 = getValue(I.getArgOperand(0));
6505     SDValue Op2 = getValue(I.getArgOperand(1));
6506     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6507     return;
6508   }
6509   case Intrinsic::usub_sat: {
6510     SDValue Op1 = getValue(I.getArgOperand(0));
6511     SDValue Op2 = getValue(I.getArgOperand(1));
6512     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6513     return;
6514   }
6515   case Intrinsic::sshl_sat: {
6516     SDValue Op1 = getValue(I.getArgOperand(0));
6517     SDValue Op2 = getValue(I.getArgOperand(1));
6518     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6519     return;
6520   }
6521   case Intrinsic::ushl_sat: {
6522     SDValue Op1 = getValue(I.getArgOperand(0));
6523     SDValue Op2 = getValue(I.getArgOperand(1));
6524     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6525     return;
6526   }
6527   case Intrinsic::smul_fix:
6528   case Intrinsic::umul_fix:
6529   case Intrinsic::smul_fix_sat:
6530   case Intrinsic::umul_fix_sat: {
6531     SDValue Op1 = getValue(I.getArgOperand(0));
6532     SDValue Op2 = getValue(I.getArgOperand(1));
6533     SDValue Op3 = getValue(I.getArgOperand(2));
6534     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6535                              Op1.getValueType(), Op1, Op2, Op3));
6536     return;
6537   }
6538   case Intrinsic::sdiv_fix:
6539   case Intrinsic::udiv_fix:
6540   case Intrinsic::sdiv_fix_sat:
6541   case Intrinsic::udiv_fix_sat: {
6542     SDValue Op1 = getValue(I.getArgOperand(0));
6543     SDValue Op2 = getValue(I.getArgOperand(1));
6544     SDValue Op3 = getValue(I.getArgOperand(2));
6545     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6546                               Op1, Op2, Op3, DAG, TLI));
6547     return;
6548   }
6549   case Intrinsic::smax: {
6550     SDValue Op1 = getValue(I.getArgOperand(0));
6551     SDValue Op2 = getValue(I.getArgOperand(1));
6552     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6553     return;
6554   }
6555   case Intrinsic::smin: {
6556     SDValue Op1 = getValue(I.getArgOperand(0));
6557     SDValue Op2 = getValue(I.getArgOperand(1));
6558     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6559     return;
6560   }
6561   case Intrinsic::umax: {
6562     SDValue Op1 = getValue(I.getArgOperand(0));
6563     SDValue Op2 = getValue(I.getArgOperand(1));
6564     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6565     return;
6566   }
6567   case Intrinsic::umin: {
6568     SDValue Op1 = getValue(I.getArgOperand(0));
6569     SDValue Op2 = getValue(I.getArgOperand(1));
6570     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6571     return;
6572   }
6573   case Intrinsic::abs: {
6574     // TODO: Preserve "int min is poison" arg in SDAG?
6575     SDValue Op1 = getValue(I.getArgOperand(0));
6576     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6577     return;
6578   }
6579   case Intrinsic::stacksave: {
6580     SDValue Op = getRoot();
6581     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6582     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6583     setValue(&I, Res);
6584     DAG.setRoot(Res.getValue(1));
6585     return;
6586   }
6587   case Intrinsic::stackrestore:
6588     Res = getValue(I.getArgOperand(0));
6589     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6590     return;
6591   case Intrinsic::get_dynamic_area_offset: {
6592     SDValue Op = getRoot();
6593     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6594     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6595     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6596     // target.
6597     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6598       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6599                          " intrinsic!");
6600     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6601                       Op);
6602     DAG.setRoot(Op);
6603     setValue(&I, Res);
6604     return;
6605   }
6606   case Intrinsic::stackguard: {
6607     MachineFunction &MF = DAG.getMachineFunction();
6608     const Module &M = *MF.getFunction().getParent();
6609     SDValue Chain = getRoot();
6610     if (TLI.useLoadStackGuardNode()) {
6611       Res = getLoadStackGuard(DAG, sdl, Chain);
6612     } else {
6613       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6614       const Value *Global = TLI.getSDagStackGuard(M);
6615       Align Align = DL->getPrefTypeAlign(Global->getType());
6616       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6617                         MachinePointerInfo(Global, 0), Align,
6618                         MachineMemOperand::MOVolatile);
6619     }
6620     if (TLI.useStackGuardXorFP())
6621       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6622     DAG.setRoot(Chain);
6623     setValue(&I, Res);
6624     return;
6625   }
6626   case Intrinsic::stackprotector: {
6627     // Emit code into the DAG to store the stack guard onto the stack.
6628     MachineFunction &MF = DAG.getMachineFunction();
6629     MachineFrameInfo &MFI = MF.getFrameInfo();
6630     SDValue Src, Chain = getRoot();
6631 
6632     if (TLI.useLoadStackGuardNode())
6633       Src = getLoadStackGuard(DAG, sdl, Chain);
6634     else
6635       Src = getValue(I.getArgOperand(0));   // The guard's value.
6636 
6637     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6638 
6639     int FI = FuncInfo.StaticAllocaMap[Slot];
6640     MFI.setStackProtectorIndex(FI);
6641     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6642 
6643     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6644 
6645     // Store the stack protector onto the stack.
6646     Res = DAG.getStore(
6647         Chain, sdl, Src, FIN,
6648         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6649         MaybeAlign(), MachineMemOperand::MOVolatile);
6650     setValue(&I, Res);
6651     DAG.setRoot(Res);
6652     return;
6653   }
6654   case Intrinsic::objectsize:
6655     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6656 
6657   case Intrinsic::is_constant:
6658     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6659 
6660   case Intrinsic::annotation:
6661   case Intrinsic::ptr_annotation:
6662   case Intrinsic::launder_invariant_group:
6663   case Intrinsic::strip_invariant_group:
6664     // Drop the intrinsic, but forward the value
6665     setValue(&I, getValue(I.getOperand(0)));
6666     return;
6667 
6668   case Intrinsic::assume:
6669   case Intrinsic::experimental_noalias_scope_decl:
6670   case Intrinsic::var_annotation:
6671   case Intrinsic::sideeffect:
6672     // Discard annotate attributes, noalias scope declarations, assumptions, and
6673     // artificial side-effects.
6674     return;
6675 
6676   case Intrinsic::codeview_annotation: {
6677     // Emit a label associated with this metadata.
6678     MachineFunction &MF = DAG.getMachineFunction();
6679     MCSymbol *Label =
6680         MF.getMMI().getContext().createTempSymbol("annotation", true);
6681     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6682     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6683     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6684     DAG.setRoot(Res);
6685     return;
6686   }
6687 
6688   case Intrinsic::init_trampoline: {
6689     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6690 
6691     SDValue Ops[6];
6692     Ops[0] = getRoot();
6693     Ops[1] = getValue(I.getArgOperand(0));
6694     Ops[2] = getValue(I.getArgOperand(1));
6695     Ops[3] = getValue(I.getArgOperand(2));
6696     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6697     Ops[5] = DAG.getSrcValue(F);
6698 
6699     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6700 
6701     DAG.setRoot(Res);
6702     return;
6703   }
6704   case Intrinsic::adjust_trampoline:
6705     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6706                              TLI.getPointerTy(DAG.getDataLayout()),
6707                              getValue(I.getArgOperand(0))));
6708     return;
6709   case Intrinsic::gcroot: {
6710     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6711            "only valid in functions with gc specified, enforced by Verifier");
6712     assert(GFI && "implied by previous");
6713     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6714     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6715 
6716     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6717     GFI->addStackRoot(FI->getIndex(), TypeMap);
6718     return;
6719   }
6720   case Intrinsic::gcread:
6721   case Intrinsic::gcwrite:
6722     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6723   case Intrinsic::flt_rounds:
6724     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6725     setValue(&I, Res);
6726     DAG.setRoot(Res.getValue(1));
6727     return;
6728 
6729   case Intrinsic::expect:
6730     // Just replace __builtin_expect(exp, c) with EXP.
6731     setValue(&I, getValue(I.getArgOperand(0)));
6732     return;
6733 
6734   case Intrinsic::ubsantrap:
6735   case Intrinsic::debugtrap:
6736   case Intrinsic::trap: {
6737     StringRef TrapFuncName =
6738         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6739     if (TrapFuncName.empty()) {
6740       switch (Intrinsic) {
6741       case Intrinsic::trap:
6742         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6743         break;
6744       case Intrinsic::debugtrap:
6745         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6746         break;
6747       case Intrinsic::ubsantrap:
6748         DAG.setRoot(DAG.getNode(
6749             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6750             DAG.getTargetConstant(
6751                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6752                 MVT::i32)));
6753         break;
6754       default: llvm_unreachable("unknown trap intrinsic");
6755       }
6756       return;
6757     }
6758     TargetLowering::ArgListTy Args;
6759     if (Intrinsic == Intrinsic::ubsantrap) {
6760       Args.push_back(TargetLoweringBase::ArgListEntry());
6761       Args[0].Val = I.getArgOperand(0);
6762       Args[0].Node = getValue(Args[0].Val);
6763       Args[0].Ty = Args[0].Val->getType();
6764     }
6765 
6766     TargetLowering::CallLoweringInfo CLI(DAG);
6767     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6768         CallingConv::C, I.getType(),
6769         DAG.getExternalSymbol(TrapFuncName.data(),
6770                               TLI.getPointerTy(DAG.getDataLayout())),
6771         std::move(Args));
6772 
6773     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6774     DAG.setRoot(Result.second);
6775     return;
6776   }
6777 
6778   case Intrinsic::uadd_with_overflow:
6779   case Intrinsic::sadd_with_overflow:
6780   case Intrinsic::usub_with_overflow:
6781   case Intrinsic::ssub_with_overflow:
6782   case Intrinsic::umul_with_overflow:
6783   case Intrinsic::smul_with_overflow: {
6784     ISD::NodeType Op;
6785     switch (Intrinsic) {
6786     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6787     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6788     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6789     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6790     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6791     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6792     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6793     }
6794     SDValue Op1 = getValue(I.getArgOperand(0));
6795     SDValue Op2 = getValue(I.getArgOperand(1));
6796 
6797     EVT ResultVT = Op1.getValueType();
6798     EVT OverflowVT = MVT::i1;
6799     if (ResultVT.isVector())
6800       OverflowVT = EVT::getVectorVT(
6801           *Context, OverflowVT, ResultVT.getVectorElementCount());
6802 
6803     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6804     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6805     return;
6806   }
6807   case Intrinsic::prefetch: {
6808     SDValue Ops[5];
6809     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6810     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6811     Ops[0] = DAG.getRoot();
6812     Ops[1] = getValue(I.getArgOperand(0));
6813     Ops[2] = getValue(I.getArgOperand(1));
6814     Ops[3] = getValue(I.getArgOperand(2));
6815     Ops[4] = getValue(I.getArgOperand(3));
6816     SDValue Result = DAG.getMemIntrinsicNode(
6817         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6818         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6819         /* align */ None, Flags);
6820 
6821     // Chain the prefetch in parallell with any pending loads, to stay out of
6822     // the way of later optimizations.
6823     PendingLoads.push_back(Result);
6824     Result = getRoot();
6825     DAG.setRoot(Result);
6826     return;
6827   }
6828   case Intrinsic::lifetime_start:
6829   case Intrinsic::lifetime_end: {
6830     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6831     // Stack coloring is not enabled in O0, discard region information.
6832     if (TM.getOptLevel() == CodeGenOpt::None)
6833       return;
6834 
6835     const int64_t ObjectSize =
6836         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6837     Value *const ObjectPtr = I.getArgOperand(1);
6838     SmallVector<const Value *, 4> Allocas;
6839     getUnderlyingObjects(ObjectPtr, Allocas);
6840 
6841     for (const Value *Alloca : Allocas) {
6842       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6843 
6844       // Could not find an Alloca.
6845       if (!LifetimeObject)
6846         continue;
6847 
6848       // First check that the Alloca is static, otherwise it won't have a
6849       // valid frame index.
6850       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6851       if (SI == FuncInfo.StaticAllocaMap.end())
6852         return;
6853 
6854       const int FrameIndex = SI->second;
6855       int64_t Offset;
6856       if (GetPointerBaseWithConstantOffset(
6857               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6858         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6859       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6860                                 Offset);
6861       DAG.setRoot(Res);
6862     }
6863     return;
6864   }
6865   case Intrinsic::pseudoprobe: {
6866     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6867     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6868     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6869     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6870     DAG.setRoot(Res);
6871     return;
6872   }
6873   case Intrinsic::invariant_start:
6874     // Discard region information.
6875     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6876     return;
6877   case Intrinsic::invariant_end:
6878     // Discard region information.
6879     return;
6880   case Intrinsic::clear_cache:
6881     /// FunctionName may be null.
6882     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6883       lowerCallToExternalSymbol(I, FunctionName);
6884     return;
6885   case Intrinsic::donothing:
6886   case Intrinsic::seh_try_begin:
6887   case Intrinsic::seh_scope_begin:
6888   case Intrinsic::seh_try_end:
6889   case Intrinsic::seh_scope_end:
6890     // ignore
6891     return;
6892   case Intrinsic::experimental_stackmap:
6893     visitStackmap(I);
6894     return;
6895   case Intrinsic::experimental_patchpoint_void:
6896   case Intrinsic::experimental_patchpoint_i64:
6897     visitPatchpoint(I);
6898     return;
6899   case Intrinsic::experimental_gc_statepoint:
6900     LowerStatepoint(cast<GCStatepointInst>(I));
6901     return;
6902   case Intrinsic::experimental_gc_result:
6903     visitGCResult(cast<GCResultInst>(I));
6904     return;
6905   case Intrinsic::experimental_gc_relocate:
6906     visitGCRelocate(cast<GCRelocateInst>(I));
6907     return;
6908   case Intrinsic::instrprof_increment:
6909     llvm_unreachable("instrprof failed to lower an increment");
6910   case Intrinsic::instrprof_value_profile:
6911     llvm_unreachable("instrprof failed to lower a value profiling call");
6912   case Intrinsic::localescape: {
6913     MachineFunction &MF = DAG.getMachineFunction();
6914     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6915 
6916     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6917     // is the same on all targets.
6918     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6919       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6920       if (isa<ConstantPointerNull>(Arg))
6921         continue; // Skip null pointers. They represent a hole in index space.
6922       AllocaInst *Slot = cast<AllocaInst>(Arg);
6923       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6924              "can only escape static allocas");
6925       int FI = FuncInfo.StaticAllocaMap[Slot];
6926       MCSymbol *FrameAllocSym =
6927           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6928               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6929       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6930               TII->get(TargetOpcode::LOCAL_ESCAPE))
6931           .addSym(FrameAllocSym)
6932           .addFrameIndex(FI);
6933     }
6934 
6935     return;
6936   }
6937 
6938   case Intrinsic::localrecover: {
6939     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6940     MachineFunction &MF = DAG.getMachineFunction();
6941 
6942     // Get the symbol that defines the frame offset.
6943     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6944     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6945     unsigned IdxVal =
6946         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6947     MCSymbol *FrameAllocSym =
6948         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6949             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6950 
6951     Value *FP = I.getArgOperand(1);
6952     SDValue FPVal = getValue(FP);
6953     EVT PtrVT = FPVal.getValueType();
6954 
6955     // Create a MCSymbol for the label to avoid any target lowering
6956     // that would make this PC relative.
6957     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6958     SDValue OffsetVal =
6959         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6960 
6961     // Add the offset to the FP.
6962     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6963     setValue(&I, Add);
6964 
6965     return;
6966   }
6967 
6968   case Intrinsic::eh_exceptionpointer:
6969   case Intrinsic::eh_exceptioncode: {
6970     // Get the exception pointer vreg, copy from it, and resize it to fit.
6971     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6972     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6973     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6974     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6975     SDValue N =
6976         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6977     if (Intrinsic == Intrinsic::eh_exceptioncode)
6978       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6979     setValue(&I, N);
6980     return;
6981   }
6982   case Intrinsic::xray_customevent: {
6983     // Here we want to make sure that the intrinsic behaves as if it has a
6984     // specific calling convention, and only for x86_64.
6985     // FIXME: Support other platforms later.
6986     const auto &Triple = DAG.getTarget().getTargetTriple();
6987     if (Triple.getArch() != Triple::x86_64)
6988       return;
6989 
6990     SDLoc DL = getCurSDLoc();
6991     SmallVector<SDValue, 8> Ops;
6992 
6993     // We want to say that we always want the arguments in registers.
6994     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6995     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6996     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6997     SDValue Chain = getRoot();
6998     Ops.push_back(LogEntryVal);
6999     Ops.push_back(StrSizeVal);
7000     Ops.push_back(Chain);
7001 
7002     // We need to enforce the calling convention for the callsite, so that
7003     // argument ordering is enforced correctly, and that register allocation can
7004     // see that some registers may be assumed clobbered and have to preserve
7005     // them across calls to the intrinsic.
7006     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7007                                            DL, NodeTys, Ops);
7008     SDValue patchableNode = SDValue(MN, 0);
7009     DAG.setRoot(patchableNode);
7010     setValue(&I, patchableNode);
7011     return;
7012   }
7013   case Intrinsic::xray_typedevent: {
7014     // Here we want to make sure that the intrinsic behaves as if it has a
7015     // specific calling convention, and only for x86_64.
7016     // FIXME: Support other platforms later.
7017     const auto &Triple = DAG.getTarget().getTargetTriple();
7018     if (Triple.getArch() != Triple::x86_64)
7019       return;
7020 
7021     SDLoc DL = getCurSDLoc();
7022     SmallVector<SDValue, 8> Ops;
7023 
7024     // We want to say that we always want the arguments in registers.
7025     // It's unclear to me how manipulating the selection DAG here forces callers
7026     // to provide arguments in registers instead of on the stack.
7027     SDValue LogTypeId = getValue(I.getArgOperand(0));
7028     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7029     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7030     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7031     SDValue Chain = getRoot();
7032     Ops.push_back(LogTypeId);
7033     Ops.push_back(LogEntryVal);
7034     Ops.push_back(StrSizeVal);
7035     Ops.push_back(Chain);
7036 
7037     // We need to enforce the calling convention for the callsite, so that
7038     // argument ordering is enforced correctly, and that register allocation can
7039     // see that some registers may be assumed clobbered and have to preserve
7040     // them across calls to the intrinsic.
7041     MachineSDNode *MN = DAG.getMachineNode(
7042         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
7043     SDValue patchableNode = SDValue(MN, 0);
7044     DAG.setRoot(patchableNode);
7045     setValue(&I, patchableNode);
7046     return;
7047   }
7048   case Intrinsic::experimental_deoptimize:
7049     LowerDeoptimizeCall(&I);
7050     return;
7051   case Intrinsic::experimental_stepvector:
7052     visitStepVector(I);
7053     return;
7054   case Intrinsic::vector_reduce_fadd:
7055   case Intrinsic::vector_reduce_fmul:
7056   case Intrinsic::vector_reduce_add:
7057   case Intrinsic::vector_reduce_mul:
7058   case Intrinsic::vector_reduce_and:
7059   case Intrinsic::vector_reduce_or:
7060   case Intrinsic::vector_reduce_xor:
7061   case Intrinsic::vector_reduce_smax:
7062   case Intrinsic::vector_reduce_smin:
7063   case Intrinsic::vector_reduce_umax:
7064   case Intrinsic::vector_reduce_umin:
7065   case Intrinsic::vector_reduce_fmax:
7066   case Intrinsic::vector_reduce_fmin:
7067     visitVectorReduce(I, Intrinsic);
7068     return;
7069 
7070   case Intrinsic::icall_branch_funnel: {
7071     SmallVector<SDValue, 16> Ops;
7072     Ops.push_back(getValue(I.getArgOperand(0)));
7073 
7074     int64_t Offset;
7075     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7076         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7077     if (!Base)
7078       report_fatal_error(
7079           "llvm.icall.branch.funnel operand must be a GlobalValue");
7080     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
7081 
7082     struct BranchFunnelTarget {
7083       int64_t Offset;
7084       SDValue Target;
7085     };
7086     SmallVector<BranchFunnelTarget, 8> Targets;
7087 
7088     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
7089       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7090           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7091       if (ElemBase != Base)
7092         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7093                            "to the same GlobalValue");
7094 
7095       SDValue Val = getValue(I.getArgOperand(Op + 1));
7096       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7097       if (!GA)
7098         report_fatal_error(
7099             "llvm.icall.branch.funnel operand must be a GlobalValue");
7100       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7101                                      GA->getGlobal(), getCurSDLoc(),
7102                                      Val.getValueType(), GA->getOffset())});
7103     }
7104     llvm::sort(Targets,
7105                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7106                  return T1.Offset < T2.Offset;
7107                });
7108 
7109     for (auto &T : Targets) {
7110       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
7111       Ops.push_back(T.Target);
7112     }
7113 
7114     Ops.push_back(DAG.getRoot()); // Chain
7115     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
7116                                  getCurSDLoc(), MVT::Other, Ops),
7117               0);
7118     DAG.setRoot(N);
7119     setValue(&I, N);
7120     HasTailCall = true;
7121     return;
7122   }
7123 
7124   case Intrinsic::wasm_landingpad_index:
7125     // Information this intrinsic contained has been transferred to
7126     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7127     // delete it now.
7128     return;
7129 
7130   case Intrinsic::aarch64_settag:
7131   case Intrinsic::aarch64_settag_zero: {
7132     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7133     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7134     SDValue Val = TSI.EmitTargetCodeForSetTag(
7135         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
7136         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7137         ZeroMemory);
7138     DAG.setRoot(Val);
7139     setValue(&I, Val);
7140     return;
7141   }
7142   case Intrinsic::ptrmask: {
7143     SDValue Ptr = getValue(I.getOperand(0));
7144     SDValue Const = getValue(I.getOperand(1));
7145 
7146     EVT PtrVT = Ptr.getValueType();
7147     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
7148                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
7149     return;
7150   }
7151   case Intrinsic::get_active_lane_mask: {
7152     auto DL = getCurSDLoc();
7153     SDValue Index = getValue(I.getOperand(0));
7154     SDValue TripCount = getValue(I.getOperand(1));
7155     Type *ElementTy = I.getOperand(0)->getType();
7156     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7157     unsigned VecWidth = VT.getVectorNumElements();
7158 
7159     SmallVector<SDValue, 16> OpsTripCount;
7160     SmallVector<SDValue, 16> OpsIndex;
7161     SmallVector<SDValue, 16> OpsStepConstants;
7162     for (unsigned i = 0; i < VecWidth; i++) {
7163       OpsTripCount.push_back(TripCount);
7164       OpsIndex.push_back(Index);
7165       OpsStepConstants.push_back(
7166           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
7167     }
7168 
7169     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
7170 
7171     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
7172     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
7173     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
7174     SDValue VectorInduction = DAG.getNode(
7175        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
7176     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
7177     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
7178                                  VectorTripCount, ISD::CondCode::SETULT);
7179     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
7180                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
7181                              SetCC));
7182     return;
7183   }
7184   case Intrinsic::experimental_vector_insert: {
7185     auto DL = getCurSDLoc();
7186 
7187     SDValue Vec = getValue(I.getOperand(0));
7188     SDValue SubVec = getValue(I.getOperand(1));
7189     SDValue Index = getValue(I.getOperand(2));
7190 
7191     // The intrinsic's index type is i64, but the SDNode requires an index type
7192     // suitable for the target. Convert the index as required.
7193     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7194     if (Index.getValueType() != VectorIdxTy)
7195       Index = DAG.getVectorIdxConstant(
7196           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7197 
7198     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7199     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
7200                              Index));
7201     return;
7202   }
7203   case Intrinsic::experimental_vector_extract: {
7204     auto DL = getCurSDLoc();
7205 
7206     SDValue Vec = getValue(I.getOperand(0));
7207     SDValue Index = getValue(I.getOperand(1));
7208     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7209 
7210     // The intrinsic's index type is i64, but the SDNode requires an index type
7211     // suitable for the target. Convert the index as required.
7212     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7213     if (Index.getValueType() != VectorIdxTy)
7214       Index = DAG.getVectorIdxConstant(
7215           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7216 
7217     setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
7218     return;
7219   }
7220   case Intrinsic::experimental_vector_reverse:
7221     visitVectorReverse(I);
7222     return;
7223   case Intrinsic::experimental_vector_splice:
7224     visitVectorSplice(I);
7225     return;
7226   }
7227 }
7228 
7229 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7230     const ConstrainedFPIntrinsic &FPI) {
7231   SDLoc sdl = getCurSDLoc();
7232 
7233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7234   SmallVector<EVT, 4> ValueVTs;
7235   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7236   ValueVTs.push_back(MVT::Other); // Out chain
7237 
7238   // We do not need to serialize constrained FP intrinsics against
7239   // each other or against (nonvolatile) loads, so they can be
7240   // chained like loads.
7241   SDValue Chain = DAG.getRoot();
7242   SmallVector<SDValue, 4> Opers;
7243   Opers.push_back(Chain);
7244   if (FPI.isUnaryOp()) {
7245     Opers.push_back(getValue(FPI.getArgOperand(0)));
7246   } else if (FPI.isTernaryOp()) {
7247     Opers.push_back(getValue(FPI.getArgOperand(0)));
7248     Opers.push_back(getValue(FPI.getArgOperand(1)));
7249     Opers.push_back(getValue(FPI.getArgOperand(2)));
7250   } else {
7251     Opers.push_back(getValue(FPI.getArgOperand(0)));
7252     Opers.push_back(getValue(FPI.getArgOperand(1)));
7253   }
7254 
7255   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7256     assert(Result.getNode()->getNumValues() == 2);
7257 
7258     // Push node to the appropriate list so that future instructions can be
7259     // chained up correctly.
7260     SDValue OutChain = Result.getValue(1);
7261     switch (EB) {
7262     case fp::ExceptionBehavior::ebIgnore:
7263       // The only reason why ebIgnore nodes still need to be chained is that
7264       // they might depend on the current rounding mode, and therefore must
7265       // not be moved across instruction that may change that mode.
7266       LLVM_FALLTHROUGH;
7267     case fp::ExceptionBehavior::ebMayTrap:
7268       // These must not be moved across calls or instructions that may change
7269       // floating-point exception masks.
7270       PendingConstrainedFP.push_back(OutChain);
7271       break;
7272     case fp::ExceptionBehavior::ebStrict:
7273       // These must not be moved across calls or instructions that may change
7274       // floating-point exception masks or read floating-point exception flags.
7275       // In addition, they cannot be optimized out even if unused.
7276       PendingConstrainedFPStrict.push_back(OutChain);
7277       break;
7278     }
7279   };
7280 
7281   SDVTList VTs = DAG.getVTList(ValueVTs);
7282   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7283 
7284   SDNodeFlags Flags;
7285   if (EB == fp::ExceptionBehavior::ebIgnore)
7286     Flags.setNoFPExcept(true);
7287 
7288   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7289     Flags.copyFMF(*FPOp);
7290 
7291   unsigned Opcode;
7292   switch (FPI.getIntrinsicID()) {
7293   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7294 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7295   case Intrinsic::INTRINSIC:                                                   \
7296     Opcode = ISD::STRICT_##DAGN;                                               \
7297     break;
7298 #include "llvm/IR/ConstrainedOps.def"
7299   case Intrinsic::experimental_constrained_fmuladd: {
7300     Opcode = ISD::STRICT_FMA;
7301     // Break fmuladd into fmul and fadd.
7302     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7303         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7304                                         ValueVTs[0])) {
7305       Opers.pop_back();
7306       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7307       pushOutChain(Mul, EB);
7308       Opcode = ISD::STRICT_FADD;
7309       Opers.clear();
7310       Opers.push_back(Mul.getValue(1));
7311       Opers.push_back(Mul.getValue(0));
7312       Opers.push_back(getValue(FPI.getArgOperand(2)));
7313     }
7314     break;
7315   }
7316   }
7317 
7318   // A few strict DAG nodes carry additional operands that are not
7319   // set up by the default code above.
7320   switch (Opcode) {
7321   default: break;
7322   case ISD::STRICT_FP_ROUND:
7323     Opers.push_back(
7324         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7325     break;
7326   case ISD::STRICT_FSETCC:
7327   case ISD::STRICT_FSETCCS: {
7328     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7329     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7330     if (TM.Options.NoNaNsFPMath)
7331       Condition = getFCmpCodeWithoutNaN(Condition);
7332     Opers.push_back(DAG.getCondCode(Condition));
7333     break;
7334   }
7335   }
7336 
7337   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7338   pushOutChain(Result, EB);
7339 
7340   SDValue FPResult = Result.getValue(0);
7341   setValue(&FPI, FPResult);
7342 }
7343 
7344 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7345   Optional<unsigned> ResOPC;
7346   switch (VPIntrin.getIntrinsicID()) {
7347 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
7348 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
7349 #define END_REGISTER_VP_INTRINSIC(...) break;
7350 #include "llvm/IR/VPIntrinsics.def"
7351   }
7352 
7353   if (!ResOPC.hasValue())
7354     llvm_unreachable(
7355         "Inconsistency: no SDNode available for this VPIntrinsic!");
7356 
7357   return ResOPC.getValue();
7358 }
7359 
7360 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7361     const VPIntrinsic &VPIntrin) {
7362   SDLoc DL = getCurSDLoc();
7363   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7364 
7365   SmallVector<EVT, 4> ValueVTs;
7366   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7367   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7368   SDVTList VTs = DAG.getVTList(ValueVTs);
7369 
7370   auto EVLParamPos =
7371       VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
7372 
7373   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7374   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7375          "Unexpected target EVL type");
7376 
7377   // Request operands.
7378   SmallVector<SDValue, 7> OpValues;
7379   for (unsigned I = 0; I < VPIntrin.getNumArgOperands(); ++I) {
7380     auto Op = getValue(VPIntrin.getArgOperand(I));
7381     if (I == EVLParamPos)
7382       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7383     OpValues.push_back(Op);
7384   }
7385 
7386   SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7387   setValue(&VPIntrin, Result);
7388 }
7389 
7390 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7391                                           const BasicBlock *EHPadBB,
7392                                           MCSymbol *&BeginLabel) {
7393   MachineFunction &MF = DAG.getMachineFunction();
7394   MachineModuleInfo &MMI = MF.getMMI();
7395 
7396   // Insert a label before the invoke call to mark the try range.  This can be
7397   // used to detect deletion of the invoke via the MachineModuleInfo.
7398   BeginLabel = MMI.getContext().createTempSymbol();
7399 
7400   // For SjLj, keep track of which landing pads go with which invokes
7401   // so as to maintain the ordering of pads in the LSDA.
7402   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7403   if (CallSiteIndex) {
7404     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7405     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7406 
7407     // Now that the call site is handled, stop tracking it.
7408     MMI.setCurrentCallSite(0);
7409   }
7410 
7411   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7412 }
7413 
7414 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7415                                         const BasicBlock *EHPadBB,
7416                                         MCSymbol *BeginLabel) {
7417   assert(BeginLabel && "BeginLabel should've been set");
7418 
7419   MachineFunction &MF = DAG.getMachineFunction();
7420   MachineModuleInfo &MMI = MF.getMMI();
7421 
7422   // Insert a label at the end of the invoke call to mark the try range.  This
7423   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7424   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7425   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7426 
7427   // Inform MachineModuleInfo of range.
7428   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7429   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7430   // actually use outlined funclets and their LSDA info style.
7431   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7432     assert(II && "II should've been set");
7433     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7434     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7435   } else if (!isScopedEHPersonality(Pers)) {
7436     assert(EHPadBB);
7437     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7438   }
7439 
7440   return Chain;
7441 }
7442 
7443 std::pair<SDValue, SDValue>
7444 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7445                                     const BasicBlock *EHPadBB) {
7446   MCSymbol *BeginLabel = nullptr;
7447 
7448   if (EHPadBB) {
7449     // Both PendingLoads and PendingExports must be flushed here;
7450     // this call might not return.
7451     (void)getRoot();
7452     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7453     CLI.setChain(getRoot());
7454   }
7455 
7456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7457   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7458 
7459   assert((CLI.IsTailCall || Result.second.getNode()) &&
7460          "Non-null chain expected with non-tail call!");
7461   assert((Result.second.getNode() || !Result.first.getNode()) &&
7462          "Null value expected with tail call!");
7463 
7464   if (!Result.second.getNode()) {
7465     // As a special case, a null chain means that a tail call has been emitted
7466     // and the DAG root is already updated.
7467     HasTailCall = true;
7468 
7469     // Since there's no actual continuation from this block, nothing can be
7470     // relying on us setting vregs for them.
7471     PendingExports.clear();
7472   } else {
7473     DAG.setRoot(Result.second);
7474   }
7475 
7476   if (EHPadBB) {
7477     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7478                            BeginLabel));
7479   }
7480 
7481   return Result;
7482 }
7483 
7484 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7485                                       bool isTailCall,
7486                                       bool isMustTailCall,
7487                                       const BasicBlock *EHPadBB) {
7488   auto &DL = DAG.getDataLayout();
7489   FunctionType *FTy = CB.getFunctionType();
7490   Type *RetTy = CB.getType();
7491 
7492   TargetLowering::ArgListTy Args;
7493   Args.reserve(CB.arg_size());
7494 
7495   const Value *SwiftErrorVal = nullptr;
7496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7497 
7498   if (isTailCall) {
7499     // Avoid emitting tail calls in functions with the disable-tail-calls
7500     // attribute.
7501     auto *Caller = CB.getParent()->getParent();
7502     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7503         "true" && !isMustTailCall)
7504       isTailCall = false;
7505 
7506     // We can't tail call inside a function with a swifterror argument. Lowering
7507     // does not support this yet. It would have to move into the swifterror
7508     // register before the call.
7509     if (TLI.supportSwiftError() &&
7510         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7511       isTailCall = false;
7512   }
7513 
7514   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7515     TargetLowering::ArgListEntry Entry;
7516     const Value *V = *I;
7517 
7518     // Skip empty types
7519     if (V->getType()->isEmptyTy())
7520       continue;
7521 
7522     SDValue ArgNode = getValue(V);
7523     Entry.Node = ArgNode; Entry.Ty = V->getType();
7524 
7525     Entry.setAttributes(&CB, I - CB.arg_begin());
7526 
7527     // Use swifterror virtual register as input to the call.
7528     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7529       SwiftErrorVal = V;
7530       // We find the virtual register for the actual swifterror argument.
7531       // Instead of using the Value, we use the virtual register instead.
7532       Entry.Node =
7533           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7534                           EVT(TLI.getPointerTy(DL)));
7535     }
7536 
7537     Args.push_back(Entry);
7538 
7539     // If we have an explicit sret argument that is an Instruction, (i.e., it
7540     // might point to function-local memory), we can't meaningfully tail-call.
7541     if (Entry.IsSRet && isa<Instruction>(V))
7542       isTailCall = false;
7543   }
7544 
7545   // If call site has a cfguardtarget operand bundle, create and add an
7546   // additional ArgListEntry.
7547   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7548     TargetLowering::ArgListEntry Entry;
7549     Value *V = Bundle->Inputs[0];
7550     SDValue ArgNode = getValue(V);
7551     Entry.Node = ArgNode;
7552     Entry.Ty = V->getType();
7553     Entry.IsCFGuardTarget = true;
7554     Args.push_back(Entry);
7555   }
7556 
7557   // Check if target-independent constraints permit a tail call here.
7558   // Target-dependent constraints are checked within TLI->LowerCallTo.
7559   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7560     isTailCall = false;
7561 
7562   // Disable tail calls if there is an swifterror argument. Targets have not
7563   // been updated to support tail calls.
7564   if (TLI.supportSwiftError() && SwiftErrorVal)
7565     isTailCall = false;
7566 
7567   TargetLowering::CallLoweringInfo CLI(DAG);
7568   CLI.setDebugLoc(getCurSDLoc())
7569       .setChain(getRoot())
7570       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7571       .setTailCall(isTailCall)
7572       .setConvergent(CB.isConvergent())
7573       .setIsPreallocated(
7574           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7575   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7576 
7577   if (Result.first.getNode()) {
7578     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7579     setValue(&CB, Result.first);
7580   }
7581 
7582   // The last element of CLI.InVals has the SDValue for swifterror return.
7583   // Here we copy it to a virtual register and update SwiftErrorMap for
7584   // book-keeping.
7585   if (SwiftErrorVal && TLI.supportSwiftError()) {
7586     // Get the last element of InVals.
7587     SDValue Src = CLI.InVals.back();
7588     Register VReg =
7589         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7590     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7591     DAG.setRoot(CopyNode);
7592   }
7593 }
7594 
7595 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7596                              SelectionDAGBuilder &Builder) {
7597   // Check to see if this load can be trivially constant folded, e.g. if the
7598   // input is from a string literal.
7599   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7600     // Cast pointer to the type we really want to load.
7601     Type *LoadTy =
7602         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7603     if (LoadVT.isVector())
7604       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7605 
7606     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7607                                          PointerType::getUnqual(LoadTy));
7608 
7609     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7610             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7611       return Builder.getValue(LoadCst);
7612   }
7613 
7614   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7615   // still constant memory, the input chain can be the entry node.
7616   SDValue Root;
7617   bool ConstantMemory = false;
7618 
7619   // Do not serialize (non-volatile) loads of constant memory with anything.
7620   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7621     Root = Builder.DAG.getEntryNode();
7622     ConstantMemory = true;
7623   } else {
7624     // Do not serialize non-volatile loads against each other.
7625     Root = Builder.DAG.getRoot();
7626   }
7627 
7628   SDValue Ptr = Builder.getValue(PtrVal);
7629   SDValue LoadVal =
7630       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7631                           MachinePointerInfo(PtrVal), Align(1));
7632 
7633   if (!ConstantMemory)
7634     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7635   return LoadVal;
7636 }
7637 
7638 /// Record the value for an instruction that produces an integer result,
7639 /// converting the type where necessary.
7640 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7641                                                   SDValue Value,
7642                                                   bool IsSigned) {
7643   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7644                                                     I.getType(), true);
7645   if (IsSigned)
7646     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7647   else
7648     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7649   setValue(&I, Value);
7650 }
7651 
7652 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7653 /// true and lower it. Otherwise return false, and it will be lowered like a
7654 /// normal call.
7655 /// The caller already checked that \p I calls the appropriate LibFunc with a
7656 /// correct prototype.
7657 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7658   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7659   const Value *Size = I.getArgOperand(2);
7660   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7661   if (CSize && CSize->getZExtValue() == 0) {
7662     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7663                                                           I.getType(), true);
7664     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7665     return true;
7666   }
7667 
7668   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7669   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7670       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7671       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7672   if (Res.first.getNode()) {
7673     processIntegerCallValue(I, Res.first, true);
7674     PendingLoads.push_back(Res.second);
7675     return true;
7676   }
7677 
7678   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7679   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7680   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7681     return false;
7682 
7683   // If the target has a fast compare for the given size, it will return a
7684   // preferred load type for that size. Require that the load VT is legal and
7685   // that the target supports unaligned loads of that type. Otherwise, return
7686   // INVALID.
7687   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7688     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7689     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7690     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7691       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7692       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7693       // TODO: Check alignment of src and dest ptrs.
7694       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7695       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7696       if (!TLI.isTypeLegal(LVT) ||
7697           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7698           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7699         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7700     }
7701 
7702     return LVT;
7703   };
7704 
7705   // This turns into unaligned loads. We only do this if the target natively
7706   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7707   // we'll only produce a small number of byte loads.
7708   MVT LoadVT;
7709   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7710   switch (NumBitsToCompare) {
7711   default:
7712     return false;
7713   case 16:
7714     LoadVT = MVT::i16;
7715     break;
7716   case 32:
7717     LoadVT = MVT::i32;
7718     break;
7719   case 64:
7720   case 128:
7721   case 256:
7722     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7723     break;
7724   }
7725 
7726   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7727     return false;
7728 
7729   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7730   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7731 
7732   // Bitcast to a wide integer type if the loads are vectors.
7733   if (LoadVT.isVector()) {
7734     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7735     LoadL = DAG.getBitcast(CmpVT, LoadL);
7736     LoadR = DAG.getBitcast(CmpVT, LoadR);
7737   }
7738 
7739   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7740   processIntegerCallValue(I, Cmp, false);
7741   return true;
7742 }
7743 
7744 /// See if we can lower a memchr call into an optimized form. If so, return
7745 /// true and lower it. Otherwise return false, and it will be lowered like a
7746 /// normal call.
7747 /// The caller already checked that \p I calls the appropriate LibFunc with a
7748 /// correct prototype.
7749 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7750   const Value *Src = I.getArgOperand(0);
7751   const Value *Char = I.getArgOperand(1);
7752   const Value *Length = I.getArgOperand(2);
7753 
7754   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7755   std::pair<SDValue, SDValue> Res =
7756     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7757                                 getValue(Src), getValue(Char), getValue(Length),
7758                                 MachinePointerInfo(Src));
7759   if (Res.first.getNode()) {
7760     setValue(&I, Res.first);
7761     PendingLoads.push_back(Res.second);
7762     return true;
7763   }
7764 
7765   return false;
7766 }
7767 
7768 /// See if we can lower a mempcpy call into an optimized form. If so, return
7769 /// true and lower it. Otherwise return false, and it will be lowered like a
7770 /// normal call.
7771 /// The caller already checked that \p I calls the appropriate LibFunc with a
7772 /// correct prototype.
7773 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7774   SDValue Dst = getValue(I.getArgOperand(0));
7775   SDValue Src = getValue(I.getArgOperand(1));
7776   SDValue Size = getValue(I.getArgOperand(2));
7777 
7778   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7779   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7780   // DAG::getMemcpy needs Alignment to be defined.
7781   Align Alignment = std::min(DstAlign, SrcAlign);
7782 
7783   bool isVol = false;
7784   SDLoc sdl = getCurSDLoc();
7785 
7786   // In the mempcpy context we need to pass in a false value for isTailCall
7787   // because the return pointer needs to be adjusted by the size of
7788   // the copied memory.
7789   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7790   AAMDNodes AAInfo;
7791   I.getAAMetadata(AAInfo);
7792   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7793                              /*isTailCall=*/false,
7794                              MachinePointerInfo(I.getArgOperand(0)),
7795                              MachinePointerInfo(I.getArgOperand(1)), AAInfo);
7796   assert(MC.getNode() != nullptr &&
7797          "** memcpy should not be lowered as TailCall in mempcpy context **");
7798   DAG.setRoot(MC);
7799 
7800   // Check if Size needs to be truncated or extended.
7801   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7802 
7803   // Adjust return pointer to point just past the last dst byte.
7804   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7805                                     Dst, Size);
7806   setValue(&I, DstPlusSize);
7807   return true;
7808 }
7809 
7810 /// See if we can lower a strcpy call into an optimized form.  If so, return
7811 /// true and lower it, otherwise return false and it will be lowered like a
7812 /// normal call.
7813 /// The caller already checked that \p I calls the appropriate LibFunc with a
7814 /// correct prototype.
7815 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7816   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7817 
7818   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7819   std::pair<SDValue, SDValue> Res =
7820     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7821                                 getValue(Arg0), getValue(Arg1),
7822                                 MachinePointerInfo(Arg0),
7823                                 MachinePointerInfo(Arg1), isStpcpy);
7824   if (Res.first.getNode()) {
7825     setValue(&I, Res.first);
7826     DAG.setRoot(Res.second);
7827     return true;
7828   }
7829 
7830   return false;
7831 }
7832 
7833 /// See if we can lower a strcmp call into an optimized form.  If so, return
7834 /// true and lower it, otherwise return false and it will be lowered like a
7835 /// normal call.
7836 /// The caller already checked that \p I calls the appropriate LibFunc with a
7837 /// correct prototype.
7838 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7839   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7840 
7841   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7842   std::pair<SDValue, SDValue> Res =
7843     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7844                                 getValue(Arg0), getValue(Arg1),
7845                                 MachinePointerInfo(Arg0),
7846                                 MachinePointerInfo(Arg1));
7847   if (Res.first.getNode()) {
7848     processIntegerCallValue(I, Res.first, true);
7849     PendingLoads.push_back(Res.second);
7850     return true;
7851   }
7852 
7853   return false;
7854 }
7855 
7856 /// See if we can lower a strlen call into an optimized form.  If so, return
7857 /// true and lower it, otherwise return false and it will be lowered like a
7858 /// normal call.
7859 /// The caller already checked that \p I calls the appropriate LibFunc with a
7860 /// correct prototype.
7861 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7862   const Value *Arg0 = I.getArgOperand(0);
7863 
7864   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7865   std::pair<SDValue, SDValue> Res =
7866     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7867                                 getValue(Arg0), MachinePointerInfo(Arg0));
7868   if (Res.first.getNode()) {
7869     processIntegerCallValue(I, Res.first, false);
7870     PendingLoads.push_back(Res.second);
7871     return true;
7872   }
7873 
7874   return false;
7875 }
7876 
7877 /// See if we can lower a strnlen call into an optimized form.  If so, return
7878 /// true and lower it, otherwise return false and it will be lowered like a
7879 /// normal call.
7880 /// The caller already checked that \p I calls the appropriate LibFunc with a
7881 /// correct prototype.
7882 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7883   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7884 
7885   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7886   std::pair<SDValue, SDValue> Res =
7887     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7888                                  getValue(Arg0), getValue(Arg1),
7889                                  MachinePointerInfo(Arg0));
7890   if (Res.first.getNode()) {
7891     processIntegerCallValue(I, Res.first, false);
7892     PendingLoads.push_back(Res.second);
7893     return true;
7894   }
7895 
7896   return false;
7897 }
7898 
7899 /// See if we can lower a unary floating-point operation into an SDNode with
7900 /// the specified Opcode.  If so, return true and lower it, otherwise return
7901 /// false and it will be lowered like a normal call.
7902 /// The caller already checked that \p I calls the appropriate LibFunc with a
7903 /// correct prototype.
7904 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7905                                               unsigned Opcode) {
7906   // We already checked this call's prototype; verify it doesn't modify errno.
7907   if (!I.onlyReadsMemory())
7908     return false;
7909 
7910   SDNodeFlags Flags;
7911   Flags.copyFMF(cast<FPMathOperator>(I));
7912 
7913   SDValue Tmp = getValue(I.getArgOperand(0));
7914   setValue(&I,
7915            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7916   return true;
7917 }
7918 
7919 /// See if we can lower a binary floating-point operation into an SDNode with
7920 /// the specified Opcode. If so, return true and lower it. Otherwise return
7921 /// false, and it will be lowered like a normal call.
7922 /// The caller already checked that \p I calls the appropriate LibFunc with a
7923 /// correct prototype.
7924 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7925                                                unsigned Opcode) {
7926   // We already checked this call's prototype; verify it doesn't modify errno.
7927   if (!I.onlyReadsMemory())
7928     return false;
7929 
7930   SDNodeFlags Flags;
7931   Flags.copyFMF(cast<FPMathOperator>(I));
7932 
7933   SDValue Tmp0 = getValue(I.getArgOperand(0));
7934   SDValue Tmp1 = getValue(I.getArgOperand(1));
7935   EVT VT = Tmp0.getValueType();
7936   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
7937   return true;
7938 }
7939 
7940 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7941   // Handle inline assembly differently.
7942   if (I.isInlineAsm()) {
7943     visitInlineAsm(I);
7944     return;
7945   }
7946 
7947   if (Function *F = I.getCalledFunction()) {
7948     if (F->isDeclaration()) {
7949       // Is this an LLVM intrinsic or a target-specific intrinsic?
7950       unsigned IID = F->getIntrinsicID();
7951       if (!IID)
7952         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7953           IID = II->getIntrinsicID(F);
7954 
7955       if (IID) {
7956         visitIntrinsicCall(I, IID);
7957         return;
7958       }
7959     }
7960 
7961     // Check for well-known libc/libm calls.  If the function is internal, it
7962     // can't be a library call.  Don't do the check if marked as nobuiltin for
7963     // some reason or the call site requires strict floating point semantics.
7964     LibFunc Func;
7965     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7966         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7967         LibInfo->hasOptimizedCodeGen(Func)) {
7968       switch (Func) {
7969       default: break;
7970       case LibFunc_bcmp:
7971         if (visitMemCmpBCmpCall(I))
7972           return;
7973         break;
7974       case LibFunc_copysign:
7975       case LibFunc_copysignf:
7976       case LibFunc_copysignl:
7977         // We already checked this call's prototype; verify it doesn't modify
7978         // errno.
7979         if (I.onlyReadsMemory()) {
7980           SDValue LHS = getValue(I.getArgOperand(0));
7981           SDValue RHS = getValue(I.getArgOperand(1));
7982           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7983                                    LHS.getValueType(), LHS, RHS));
7984           return;
7985         }
7986         break;
7987       case LibFunc_fabs:
7988       case LibFunc_fabsf:
7989       case LibFunc_fabsl:
7990         if (visitUnaryFloatCall(I, ISD::FABS))
7991           return;
7992         break;
7993       case LibFunc_fmin:
7994       case LibFunc_fminf:
7995       case LibFunc_fminl:
7996         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7997           return;
7998         break;
7999       case LibFunc_fmax:
8000       case LibFunc_fmaxf:
8001       case LibFunc_fmaxl:
8002         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8003           return;
8004         break;
8005       case LibFunc_sin:
8006       case LibFunc_sinf:
8007       case LibFunc_sinl:
8008         if (visitUnaryFloatCall(I, ISD::FSIN))
8009           return;
8010         break;
8011       case LibFunc_cos:
8012       case LibFunc_cosf:
8013       case LibFunc_cosl:
8014         if (visitUnaryFloatCall(I, ISD::FCOS))
8015           return;
8016         break;
8017       case LibFunc_sqrt:
8018       case LibFunc_sqrtf:
8019       case LibFunc_sqrtl:
8020       case LibFunc_sqrt_finite:
8021       case LibFunc_sqrtf_finite:
8022       case LibFunc_sqrtl_finite:
8023         if (visitUnaryFloatCall(I, ISD::FSQRT))
8024           return;
8025         break;
8026       case LibFunc_floor:
8027       case LibFunc_floorf:
8028       case LibFunc_floorl:
8029         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8030           return;
8031         break;
8032       case LibFunc_nearbyint:
8033       case LibFunc_nearbyintf:
8034       case LibFunc_nearbyintl:
8035         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8036           return;
8037         break;
8038       case LibFunc_ceil:
8039       case LibFunc_ceilf:
8040       case LibFunc_ceill:
8041         if (visitUnaryFloatCall(I, ISD::FCEIL))
8042           return;
8043         break;
8044       case LibFunc_rint:
8045       case LibFunc_rintf:
8046       case LibFunc_rintl:
8047         if (visitUnaryFloatCall(I, ISD::FRINT))
8048           return;
8049         break;
8050       case LibFunc_round:
8051       case LibFunc_roundf:
8052       case LibFunc_roundl:
8053         if (visitUnaryFloatCall(I, ISD::FROUND))
8054           return;
8055         break;
8056       case LibFunc_trunc:
8057       case LibFunc_truncf:
8058       case LibFunc_truncl:
8059         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8060           return;
8061         break;
8062       case LibFunc_log2:
8063       case LibFunc_log2f:
8064       case LibFunc_log2l:
8065         if (visitUnaryFloatCall(I, ISD::FLOG2))
8066           return;
8067         break;
8068       case LibFunc_exp2:
8069       case LibFunc_exp2f:
8070       case LibFunc_exp2l:
8071         if (visitUnaryFloatCall(I, ISD::FEXP2))
8072           return;
8073         break;
8074       case LibFunc_memcmp:
8075         if (visitMemCmpBCmpCall(I))
8076           return;
8077         break;
8078       case LibFunc_mempcpy:
8079         if (visitMemPCpyCall(I))
8080           return;
8081         break;
8082       case LibFunc_memchr:
8083         if (visitMemChrCall(I))
8084           return;
8085         break;
8086       case LibFunc_strcpy:
8087         if (visitStrCpyCall(I, false))
8088           return;
8089         break;
8090       case LibFunc_stpcpy:
8091         if (visitStrCpyCall(I, true))
8092           return;
8093         break;
8094       case LibFunc_strcmp:
8095         if (visitStrCmpCall(I))
8096           return;
8097         break;
8098       case LibFunc_strlen:
8099         if (visitStrLenCall(I))
8100           return;
8101         break;
8102       case LibFunc_strnlen:
8103         if (visitStrNLenCall(I))
8104           return;
8105         break;
8106       }
8107     }
8108   }
8109 
8110   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8111   // have to do anything here to lower funclet bundles.
8112   // CFGuardTarget bundles are lowered in LowerCallTo.
8113   assert(!I.hasOperandBundlesOtherThan(
8114              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8115               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8116               LLVMContext::OB_clang_arc_attachedcall}) &&
8117          "Cannot lower calls with arbitrary operand bundles!");
8118 
8119   SDValue Callee = getValue(I.getCalledOperand());
8120 
8121   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8122     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8123   else
8124     // Check if we can potentially perform a tail call. More detailed checking
8125     // is be done within LowerCallTo, after more information about the call is
8126     // known.
8127     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8128 }
8129 
8130 namespace {
8131 
8132 /// AsmOperandInfo - This contains information for each constraint that we are
8133 /// lowering.
8134 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8135 public:
8136   /// CallOperand - If this is the result output operand or a clobber
8137   /// this is null, otherwise it is the incoming operand to the CallInst.
8138   /// This gets modified as the asm is processed.
8139   SDValue CallOperand;
8140 
8141   /// AssignedRegs - If this is a register or register class operand, this
8142   /// contains the set of register corresponding to the operand.
8143   RegsForValue AssignedRegs;
8144 
8145   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8146     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8147   }
8148 
8149   /// Whether or not this operand accesses memory
8150   bool hasMemory(const TargetLowering &TLI) const {
8151     // Indirect operand accesses access memory.
8152     if (isIndirect)
8153       return true;
8154 
8155     for (const auto &Code : Codes)
8156       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8157         return true;
8158 
8159     return false;
8160   }
8161 
8162   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8163   /// corresponds to.  If there is no Value* for this operand, it returns
8164   /// MVT::Other.
8165   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8166                            const DataLayout &DL) const {
8167     if (!CallOperandVal) return MVT::Other;
8168 
8169     if (isa<BasicBlock>(CallOperandVal))
8170       return TLI.getProgramPointerTy(DL);
8171 
8172     llvm::Type *OpTy = CallOperandVal->getType();
8173 
8174     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8175     // If this is an indirect operand, the operand is a pointer to the
8176     // accessed type.
8177     if (isIndirect) {
8178       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
8179       if (!PtrTy)
8180         report_fatal_error("Indirect operand for inline asm not a pointer!");
8181       OpTy = PtrTy->getElementType();
8182     }
8183 
8184     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8185     if (StructType *STy = dyn_cast<StructType>(OpTy))
8186       if (STy->getNumElements() == 1)
8187         OpTy = STy->getElementType(0);
8188 
8189     // If OpTy is not a single value, it may be a struct/union that we
8190     // can tile with integers.
8191     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8192       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8193       switch (BitSize) {
8194       default: break;
8195       case 1:
8196       case 8:
8197       case 16:
8198       case 32:
8199       case 64:
8200       case 128:
8201         OpTy = IntegerType::get(Context, BitSize);
8202         break;
8203       }
8204     }
8205 
8206     return TLI.getAsmOperandValueType(DL, OpTy, true);
8207   }
8208 };
8209 
8210 
8211 } // end anonymous namespace
8212 
8213 /// Make sure that the output operand \p OpInfo and its corresponding input
8214 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8215 /// out).
8216 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8217                                SDISelAsmOperandInfo &MatchingOpInfo,
8218                                SelectionDAG &DAG) {
8219   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8220     return;
8221 
8222   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8223   const auto &TLI = DAG.getTargetLoweringInfo();
8224 
8225   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8226       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8227                                        OpInfo.ConstraintVT);
8228   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8229       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8230                                        MatchingOpInfo.ConstraintVT);
8231   if ((OpInfo.ConstraintVT.isInteger() !=
8232        MatchingOpInfo.ConstraintVT.isInteger()) ||
8233       (MatchRC.second != InputRC.second)) {
8234     // FIXME: error out in a more elegant fashion
8235     report_fatal_error("Unsupported asm: input constraint"
8236                        " with a matching output constraint of"
8237                        " incompatible type!");
8238   }
8239   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8240 }
8241 
8242 /// Get a direct memory input to behave well as an indirect operand.
8243 /// This may introduce stores, hence the need for a \p Chain.
8244 /// \return The (possibly updated) chain.
8245 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8246                                         SDISelAsmOperandInfo &OpInfo,
8247                                         SelectionDAG &DAG) {
8248   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8249 
8250   // If we don't have an indirect input, put it in the constpool if we can,
8251   // otherwise spill it to a stack slot.
8252   // TODO: This isn't quite right. We need to handle these according to
8253   // the addressing mode that the constraint wants. Also, this may take
8254   // an additional register for the computation and we don't want that
8255   // either.
8256 
8257   // If the operand is a float, integer, or vector constant, spill to a
8258   // constant pool entry to get its address.
8259   const Value *OpVal = OpInfo.CallOperandVal;
8260   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8261       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8262     OpInfo.CallOperand = DAG.getConstantPool(
8263         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8264     return Chain;
8265   }
8266 
8267   // Otherwise, create a stack slot and emit a store to it before the asm.
8268   Type *Ty = OpVal->getType();
8269   auto &DL = DAG.getDataLayout();
8270   uint64_t TySize = DL.getTypeAllocSize(Ty);
8271   MachineFunction &MF = DAG.getMachineFunction();
8272   int SSFI = MF.getFrameInfo().CreateStackObject(
8273       TySize, DL.getPrefTypeAlign(Ty), false);
8274   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8275   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8276                             MachinePointerInfo::getFixedStack(MF, SSFI),
8277                             TLI.getMemValueType(DL, Ty));
8278   OpInfo.CallOperand = StackSlot;
8279 
8280   return Chain;
8281 }
8282 
8283 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8284 /// specified operand.  We prefer to assign virtual registers, to allow the
8285 /// register allocator to handle the assignment process.  However, if the asm
8286 /// uses features that we can't model on machineinstrs, we have SDISel do the
8287 /// allocation.  This produces generally horrible, but correct, code.
8288 ///
8289 ///   OpInfo describes the operand
8290 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8291 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8292                                  SDISelAsmOperandInfo &OpInfo,
8293                                  SDISelAsmOperandInfo &RefOpInfo) {
8294   LLVMContext &Context = *DAG.getContext();
8295   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8296 
8297   MachineFunction &MF = DAG.getMachineFunction();
8298   SmallVector<unsigned, 4> Regs;
8299   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8300 
8301   // No work to do for memory operations.
8302   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8303     return;
8304 
8305   // If this is a constraint for a single physreg, or a constraint for a
8306   // register class, find it.
8307   unsigned AssignedReg;
8308   const TargetRegisterClass *RC;
8309   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8310       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8311   // RC is unset only on failure. Return immediately.
8312   if (!RC)
8313     return;
8314 
8315   // Get the actual register value type.  This is important, because the user
8316   // may have asked for (e.g.) the AX register in i32 type.  We need to
8317   // remember that AX is actually i16 to get the right extension.
8318   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8319 
8320   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8321     // If this is an FP operand in an integer register (or visa versa), or more
8322     // generally if the operand value disagrees with the register class we plan
8323     // to stick it in, fix the operand type.
8324     //
8325     // If this is an input value, the bitcast to the new type is done now.
8326     // Bitcast for output value is done at the end of visitInlineAsm().
8327     if ((OpInfo.Type == InlineAsm::isOutput ||
8328          OpInfo.Type == InlineAsm::isInput) &&
8329         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8330       // Try to convert to the first EVT that the reg class contains.  If the
8331       // types are identical size, use a bitcast to convert (e.g. two differing
8332       // vector types).  Note: output bitcast is done at the end of
8333       // visitInlineAsm().
8334       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8335         // Exclude indirect inputs while they are unsupported because the code
8336         // to perform the load is missing and thus OpInfo.CallOperand still
8337         // refers to the input address rather than the pointed-to value.
8338         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8339           OpInfo.CallOperand =
8340               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8341         OpInfo.ConstraintVT = RegVT;
8342         // If the operand is an FP value and we want it in integer registers,
8343         // use the corresponding integer type. This turns an f64 value into
8344         // i64, which can be passed with two i32 values on a 32-bit machine.
8345       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8346         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8347         if (OpInfo.Type == InlineAsm::isInput)
8348           OpInfo.CallOperand =
8349               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8350         OpInfo.ConstraintVT = VT;
8351       }
8352     }
8353   }
8354 
8355   // No need to allocate a matching input constraint since the constraint it's
8356   // matching to has already been allocated.
8357   if (OpInfo.isMatchingInputConstraint())
8358     return;
8359 
8360   EVT ValueVT = OpInfo.ConstraintVT;
8361   if (OpInfo.ConstraintVT == MVT::Other)
8362     ValueVT = RegVT;
8363 
8364   // Initialize NumRegs.
8365   unsigned NumRegs = 1;
8366   if (OpInfo.ConstraintVT != MVT::Other)
8367     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8368 
8369   // If this is a constraint for a specific physical register, like {r17},
8370   // assign it now.
8371 
8372   // If this associated to a specific register, initialize iterator to correct
8373   // place. If virtual, make sure we have enough registers
8374 
8375   // Initialize iterator if necessary
8376   TargetRegisterClass::iterator I = RC->begin();
8377   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8378 
8379   // Do not check for single registers.
8380   if (AssignedReg) {
8381       for (; *I != AssignedReg; ++I)
8382         assert(I != RC->end() && "AssignedReg should be member of RC");
8383   }
8384 
8385   for (; NumRegs; --NumRegs, ++I) {
8386     assert(I != RC->end() && "Ran out of registers to allocate!");
8387     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8388     Regs.push_back(R);
8389   }
8390 
8391   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8392 }
8393 
8394 static unsigned
8395 findMatchingInlineAsmOperand(unsigned OperandNo,
8396                              const std::vector<SDValue> &AsmNodeOperands) {
8397   // Scan until we find the definition we already emitted of this operand.
8398   unsigned CurOp = InlineAsm::Op_FirstOperand;
8399   for (; OperandNo; --OperandNo) {
8400     // Advance to the next operand.
8401     unsigned OpFlag =
8402         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8403     assert((InlineAsm::isRegDefKind(OpFlag) ||
8404             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8405             InlineAsm::isMemKind(OpFlag)) &&
8406            "Skipped past definitions?");
8407     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8408   }
8409   return CurOp;
8410 }
8411 
8412 namespace {
8413 
8414 class ExtraFlags {
8415   unsigned Flags = 0;
8416 
8417 public:
8418   explicit ExtraFlags(const CallBase &Call) {
8419     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8420     if (IA->hasSideEffects())
8421       Flags |= InlineAsm::Extra_HasSideEffects;
8422     if (IA->isAlignStack())
8423       Flags |= InlineAsm::Extra_IsAlignStack;
8424     if (Call.isConvergent())
8425       Flags |= InlineAsm::Extra_IsConvergent;
8426     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8427   }
8428 
8429   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8430     // Ideally, we would only check against memory constraints.  However, the
8431     // meaning of an Other constraint can be target-specific and we can't easily
8432     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8433     // for Other constraints as well.
8434     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8435         OpInfo.ConstraintType == TargetLowering::C_Other) {
8436       if (OpInfo.Type == InlineAsm::isInput)
8437         Flags |= InlineAsm::Extra_MayLoad;
8438       else if (OpInfo.Type == InlineAsm::isOutput)
8439         Flags |= InlineAsm::Extra_MayStore;
8440       else if (OpInfo.Type == InlineAsm::isClobber)
8441         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8442     }
8443   }
8444 
8445   unsigned get() const { return Flags; }
8446 };
8447 
8448 } // end anonymous namespace
8449 
8450 /// visitInlineAsm - Handle a call to an InlineAsm object.
8451 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8452                                          const BasicBlock *EHPadBB) {
8453   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8454 
8455   /// ConstraintOperands - Information about all of the constraints.
8456   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8457 
8458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8459   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8460       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8461 
8462   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8463   // AsmDialect, MayLoad, MayStore).
8464   bool HasSideEffect = IA->hasSideEffects();
8465   ExtraFlags ExtraInfo(Call);
8466 
8467   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8468   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8469   unsigned NumMatchingOps = 0;
8470   for (auto &T : TargetConstraints) {
8471     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8472     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8473 
8474     // Compute the value type for each operand.
8475     if (OpInfo.Type == InlineAsm::isInput ||
8476         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8477       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8478 
8479       // Process the call argument. BasicBlocks are labels, currently appearing
8480       // only in asm's.
8481       if (isa<CallBrInst>(Call) &&
8482           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8483                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8484                         NumMatchingOps) &&
8485           (NumMatchingOps == 0 ||
8486            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8487                         NumMatchingOps))) {
8488         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8489         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8490         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8491       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8492         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8493       } else {
8494         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8495       }
8496 
8497       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8498                                            DAG.getDataLayout());
8499       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8500     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8501       // The return value of the call is this value.  As such, there is no
8502       // corresponding argument.
8503       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8504       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8505         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8506             DAG.getDataLayout(), STy->getElementType(ResNo));
8507       } else {
8508         assert(ResNo == 0 && "Asm only has one result!");
8509         OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
8510             DAG.getDataLayout(), Call.getType()).getSimpleVT();
8511       }
8512       ++ResNo;
8513     } else {
8514       OpInfo.ConstraintVT = MVT::Other;
8515     }
8516 
8517     if (OpInfo.hasMatchingInput())
8518       ++NumMatchingOps;
8519 
8520     if (!HasSideEffect)
8521       HasSideEffect = OpInfo.hasMemory(TLI);
8522 
8523     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8524     // FIXME: Could we compute this on OpInfo rather than T?
8525 
8526     // Compute the constraint code and ConstraintType to use.
8527     TLI.ComputeConstraintToUse(T, SDValue());
8528 
8529     if (T.ConstraintType == TargetLowering::C_Immediate &&
8530         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8531       // We've delayed emitting a diagnostic like the "n" constraint because
8532       // inlining could cause an integer showing up.
8533       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8534                                           "' expects an integer constant "
8535                                           "expression");
8536 
8537     ExtraInfo.update(T);
8538   }
8539 
8540   // We won't need to flush pending loads if this asm doesn't touch
8541   // memory and is nonvolatile.
8542   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8543 
8544   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8545   if (EmitEHLabels) {
8546     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8547   }
8548   bool IsCallBr = isa<CallBrInst>(Call);
8549 
8550   if (IsCallBr || EmitEHLabels) {
8551     // If this is a callbr or invoke we need to flush pending exports since
8552     // inlineasm_br and invoke are terminators.
8553     // We need to do this before nodes are glued to the inlineasm_br node.
8554     Chain = getControlRoot();
8555   }
8556 
8557   MCSymbol *BeginLabel = nullptr;
8558   if (EmitEHLabels) {
8559     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8560   }
8561 
8562   // Second pass over the constraints: compute which constraint option to use.
8563   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8564     // If this is an output operand with a matching input operand, look up the
8565     // matching input. If their types mismatch, e.g. one is an integer, the
8566     // other is floating point, or their sizes are different, flag it as an
8567     // error.
8568     if (OpInfo.hasMatchingInput()) {
8569       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8570       patchMatchingInput(OpInfo, Input, DAG);
8571     }
8572 
8573     // Compute the constraint code and ConstraintType to use.
8574     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8575 
8576     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8577         OpInfo.Type == InlineAsm::isClobber)
8578       continue;
8579 
8580     // If this is a memory input, and if the operand is not indirect, do what we
8581     // need to provide an address for the memory input.
8582     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8583         !OpInfo.isIndirect) {
8584       assert((OpInfo.isMultipleAlternative ||
8585               (OpInfo.Type == InlineAsm::isInput)) &&
8586              "Can only indirectify direct input operands!");
8587 
8588       // Memory operands really want the address of the value.
8589       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8590 
8591       // There is no longer a Value* corresponding to this operand.
8592       OpInfo.CallOperandVal = nullptr;
8593 
8594       // It is now an indirect operand.
8595       OpInfo.isIndirect = true;
8596     }
8597 
8598   }
8599 
8600   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8601   std::vector<SDValue> AsmNodeOperands;
8602   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8603   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8604       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8605 
8606   // If we have a !srcloc metadata node associated with it, we want to attach
8607   // this to the ultimately generated inline asm machineinstr.  To do this, we
8608   // pass in the third operand as this (potentially null) inline asm MDNode.
8609   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8610   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8611 
8612   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8613   // bits as operand 3.
8614   AsmNodeOperands.push_back(DAG.getTargetConstant(
8615       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8616 
8617   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8618   // this, assign virtual and physical registers for inputs and otput.
8619   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8620     // Assign Registers.
8621     SDISelAsmOperandInfo &RefOpInfo =
8622         OpInfo.isMatchingInputConstraint()
8623             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8624             : OpInfo;
8625     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8626 
8627     auto DetectWriteToReservedRegister = [&]() {
8628       const MachineFunction &MF = DAG.getMachineFunction();
8629       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8630       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8631         if (Register::isPhysicalRegister(Reg) &&
8632             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8633           const char *RegName = TRI.getName(Reg);
8634           emitInlineAsmError(Call, "write to reserved register '" +
8635                                        Twine(RegName) + "'");
8636           return true;
8637         }
8638       }
8639       return false;
8640     };
8641 
8642     switch (OpInfo.Type) {
8643     case InlineAsm::isOutput:
8644       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8645         unsigned ConstraintID =
8646             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8647         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8648                "Failed to convert memory constraint code to constraint id.");
8649 
8650         // Add information to the INLINEASM node to know about this output.
8651         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8652         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8653         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8654                                                         MVT::i32));
8655         AsmNodeOperands.push_back(OpInfo.CallOperand);
8656       } else {
8657         // Otherwise, this outputs to a register (directly for C_Register /
8658         // C_RegisterClass, and a target-defined fashion for
8659         // C_Immediate/C_Other). Find a register that we can use.
8660         if (OpInfo.AssignedRegs.Regs.empty()) {
8661           emitInlineAsmError(
8662               Call, "couldn't allocate output register for constraint '" +
8663                         Twine(OpInfo.ConstraintCode) + "'");
8664           return;
8665         }
8666 
8667         if (DetectWriteToReservedRegister())
8668           return;
8669 
8670         // Add information to the INLINEASM node to know that this register is
8671         // set.
8672         OpInfo.AssignedRegs.AddInlineAsmOperands(
8673             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8674                                   : InlineAsm::Kind_RegDef,
8675             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8676       }
8677       break;
8678 
8679     case InlineAsm::isInput: {
8680       SDValue InOperandVal = OpInfo.CallOperand;
8681 
8682       if (OpInfo.isMatchingInputConstraint()) {
8683         // If this is required to match an output register we have already set,
8684         // just use its register.
8685         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8686                                                   AsmNodeOperands);
8687         unsigned OpFlag =
8688           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8689         if (InlineAsm::isRegDefKind(OpFlag) ||
8690             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8691           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8692           if (OpInfo.isIndirect) {
8693             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8694             emitInlineAsmError(Call, "inline asm not supported yet: "
8695                                      "don't know how to handle tied "
8696                                      "indirect register inputs");
8697             return;
8698           }
8699 
8700           SmallVector<unsigned, 4> Regs;
8701           MachineFunction &MF = DAG.getMachineFunction();
8702           MachineRegisterInfo &MRI = MF.getRegInfo();
8703           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8704           RegisterSDNode *R = dyn_cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8705           Register TiedReg = R->getReg();
8706           MVT RegVT = R->getSimpleValueType(0);
8707           const TargetRegisterClass *RC = TiedReg.isVirtual() ?
8708             MRI.getRegClass(TiedReg) : TRI.getMinimalPhysRegClass(TiedReg);
8709           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8710           for (unsigned i = 0; i != NumRegs; ++i)
8711             Regs.push_back(MRI.createVirtualRegister(RC));
8712 
8713           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8714 
8715           SDLoc dl = getCurSDLoc();
8716           // Use the produced MatchedRegs object to
8717           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8718           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8719                                            true, OpInfo.getMatchedOperand(), dl,
8720                                            DAG, AsmNodeOperands);
8721           break;
8722         }
8723 
8724         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8725         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8726                "Unexpected number of operands");
8727         // Add information to the INLINEASM node to know about this input.
8728         // See InlineAsm.h isUseOperandTiedToDef.
8729         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8730         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8731                                                     OpInfo.getMatchedOperand());
8732         AsmNodeOperands.push_back(DAG.getTargetConstant(
8733             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8734         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8735         break;
8736       }
8737 
8738       // Treat indirect 'X' constraint as memory.
8739       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8740           OpInfo.isIndirect)
8741         OpInfo.ConstraintType = TargetLowering::C_Memory;
8742 
8743       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8744           OpInfo.ConstraintType == TargetLowering::C_Other) {
8745         std::vector<SDValue> Ops;
8746         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8747                                           Ops, DAG);
8748         if (Ops.empty()) {
8749           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8750             if (isa<ConstantSDNode>(InOperandVal)) {
8751               emitInlineAsmError(Call, "value out of range for constraint '" +
8752                                            Twine(OpInfo.ConstraintCode) + "'");
8753               return;
8754             }
8755 
8756           emitInlineAsmError(Call,
8757                              "invalid operand for inline asm constraint '" +
8758                                  Twine(OpInfo.ConstraintCode) + "'");
8759           return;
8760         }
8761 
8762         // Add information to the INLINEASM node to know about this input.
8763         unsigned ResOpType =
8764           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8765         AsmNodeOperands.push_back(DAG.getTargetConstant(
8766             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8767         llvm::append_range(AsmNodeOperands, Ops);
8768         break;
8769       }
8770 
8771       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8772         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8773         assert(InOperandVal.getValueType() ==
8774                    TLI.getPointerTy(DAG.getDataLayout()) &&
8775                "Memory operands expect pointer values");
8776 
8777         unsigned ConstraintID =
8778             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8779         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8780                "Failed to convert memory constraint code to constraint id.");
8781 
8782         // Add information to the INLINEASM node to know about this input.
8783         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8784         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8785         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8786                                                         getCurSDLoc(),
8787                                                         MVT::i32));
8788         AsmNodeOperands.push_back(InOperandVal);
8789         break;
8790       }
8791 
8792       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8793               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8794              "Unknown constraint type!");
8795 
8796       // TODO: Support this.
8797       if (OpInfo.isIndirect) {
8798         emitInlineAsmError(
8799             Call, "Don't know how to handle indirect register inputs yet "
8800                   "for constraint '" +
8801                       Twine(OpInfo.ConstraintCode) + "'");
8802         return;
8803       }
8804 
8805       // Copy the input into the appropriate registers.
8806       if (OpInfo.AssignedRegs.Regs.empty()) {
8807         emitInlineAsmError(Call,
8808                            "couldn't allocate input reg for constraint '" +
8809                                Twine(OpInfo.ConstraintCode) + "'");
8810         return;
8811       }
8812 
8813       if (DetectWriteToReservedRegister())
8814         return;
8815 
8816       SDLoc dl = getCurSDLoc();
8817 
8818       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8819                                         &Call);
8820 
8821       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8822                                                dl, DAG, AsmNodeOperands);
8823       break;
8824     }
8825     case InlineAsm::isClobber:
8826       // Add the clobbered value to the operand list, so that the register
8827       // allocator is aware that the physreg got clobbered.
8828       if (!OpInfo.AssignedRegs.Regs.empty())
8829         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8830                                                  false, 0, getCurSDLoc(), DAG,
8831                                                  AsmNodeOperands);
8832       break;
8833     }
8834   }
8835 
8836   // Finish up input operands.  Set the input chain and add the flag last.
8837   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8838   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8839 
8840   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8841   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8842                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8843   Flag = Chain.getValue(1);
8844 
8845   // Do additional work to generate outputs.
8846 
8847   SmallVector<EVT, 1> ResultVTs;
8848   SmallVector<SDValue, 1> ResultValues;
8849   SmallVector<SDValue, 8> OutChains;
8850 
8851   llvm::Type *CallResultType = Call.getType();
8852   ArrayRef<Type *> ResultTypes;
8853   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8854     ResultTypes = StructResult->elements();
8855   else if (!CallResultType->isVoidTy())
8856     ResultTypes = makeArrayRef(CallResultType);
8857 
8858   auto CurResultType = ResultTypes.begin();
8859   auto handleRegAssign = [&](SDValue V) {
8860     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8861     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8862     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8863     ++CurResultType;
8864     // If the type of the inline asm call site return value is different but has
8865     // same size as the type of the asm output bitcast it.  One example of this
8866     // is for vectors with different width / number of elements.  This can
8867     // happen for register classes that can contain multiple different value
8868     // types.  The preg or vreg allocated may not have the same VT as was
8869     // expected.
8870     //
8871     // This can also happen for a return value that disagrees with the register
8872     // class it is put in, eg. a double in a general-purpose register on a
8873     // 32-bit machine.
8874     if (ResultVT != V.getValueType() &&
8875         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8876       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8877     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8878              V.getValueType().isInteger()) {
8879       // If a result value was tied to an input value, the computed result
8880       // may have a wider width than the expected result.  Extract the
8881       // relevant portion.
8882       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8883     }
8884     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8885     ResultVTs.push_back(ResultVT);
8886     ResultValues.push_back(V);
8887   };
8888 
8889   // Deal with output operands.
8890   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8891     if (OpInfo.Type == InlineAsm::isOutput) {
8892       SDValue Val;
8893       // Skip trivial output operands.
8894       if (OpInfo.AssignedRegs.Regs.empty())
8895         continue;
8896 
8897       switch (OpInfo.ConstraintType) {
8898       case TargetLowering::C_Register:
8899       case TargetLowering::C_RegisterClass:
8900         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8901                                                   Chain, &Flag, &Call);
8902         break;
8903       case TargetLowering::C_Immediate:
8904       case TargetLowering::C_Other:
8905         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8906                                               OpInfo, DAG);
8907         break;
8908       case TargetLowering::C_Memory:
8909         break; // Already handled.
8910       case TargetLowering::C_Unknown:
8911         assert(false && "Unexpected unknown constraint");
8912       }
8913 
8914       // Indirect output manifest as stores. Record output chains.
8915       if (OpInfo.isIndirect) {
8916         const Value *Ptr = OpInfo.CallOperandVal;
8917         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8918         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8919                                      MachinePointerInfo(Ptr));
8920         OutChains.push_back(Store);
8921       } else {
8922         // generate CopyFromRegs to associated registers.
8923         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8924         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8925           for (const SDValue &V : Val->op_values())
8926             handleRegAssign(V);
8927         } else
8928           handleRegAssign(Val);
8929       }
8930     }
8931   }
8932 
8933   // Set results.
8934   if (!ResultValues.empty()) {
8935     assert(CurResultType == ResultTypes.end() &&
8936            "Mismatch in number of ResultTypes");
8937     assert(ResultValues.size() == ResultTypes.size() &&
8938            "Mismatch in number of output operands in asm result");
8939 
8940     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8941                             DAG.getVTList(ResultVTs), ResultValues);
8942     setValue(&Call, V);
8943   }
8944 
8945   // Collect store chains.
8946   if (!OutChains.empty())
8947     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8948 
8949   if (EmitEHLabels) {
8950     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
8951   }
8952 
8953   // Only Update Root if inline assembly has a memory effect.
8954   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
8955       EmitEHLabels)
8956     DAG.setRoot(Chain);
8957 }
8958 
8959 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8960                                              const Twine &Message) {
8961   LLVMContext &Ctx = *DAG.getContext();
8962   Ctx.emitError(&Call, Message);
8963 
8964   // Make sure we leave the DAG in a valid state
8965   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8966   SmallVector<EVT, 1> ValueVTs;
8967   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8968 
8969   if (ValueVTs.empty())
8970     return;
8971 
8972   SmallVector<SDValue, 1> Ops;
8973   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8974     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8975 
8976   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8977 }
8978 
8979 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8980   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8981                           MVT::Other, getRoot(),
8982                           getValue(I.getArgOperand(0)),
8983                           DAG.getSrcValue(I.getArgOperand(0))));
8984 }
8985 
8986 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8987   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8988   const DataLayout &DL = DAG.getDataLayout();
8989   SDValue V = DAG.getVAArg(
8990       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8991       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8992       DL.getABITypeAlign(I.getType()).value());
8993   DAG.setRoot(V.getValue(1));
8994 
8995   if (I.getType()->isPointerTy())
8996     V = DAG.getPtrExtOrTrunc(
8997         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8998   setValue(&I, V);
8999 }
9000 
9001 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9002   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9003                           MVT::Other, getRoot(),
9004                           getValue(I.getArgOperand(0)),
9005                           DAG.getSrcValue(I.getArgOperand(0))));
9006 }
9007 
9008 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9009   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9010                           MVT::Other, getRoot(),
9011                           getValue(I.getArgOperand(0)),
9012                           getValue(I.getArgOperand(1)),
9013                           DAG.getSrcValue(I.getArgOperand(0)),
9014                           DAG.getSrcValue(I.getArgOperand(1))));
9015 }
9016 
9017 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9018                                                     const Instruction &I,
9019                                                     SDValue Op) {
9020   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9021   if (!Range)
9022     return Op;
9023 
9024   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9025   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9026     return Op;
9027 
9028   APInt Lo = CR.getUnsignedMin();
9029   if (!Lo.isMinValue())
9030     return Op;
9031 
9032   APInt Hi = CR.getUnsignedMax();
9033   unsigned Bits = std::max(Hi.getActiveBits(),
9034                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9035 
9036   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9037 
9038   SDLoc SL = getCurSDLoc();
9039 
9040   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9041                              DAG.getValueType(SmallVT));
9042   unsigned NumVals = Op.getNode()->getNumValues();
9043   if (NumVals == 1)
9044     return ZExt;
9045 
9046   SmallVector<SDValue, 4> Ops;
9047 
9048   Ops.push_back(ZExt);
9049   for (unsigned I = 1; I != NumVals; ++I)
9050     Ops.push_back(Op.getValue(I));
9051 
9052   return DAG.getMergeValues(Ops, SL);
9053 }
9054 
9055 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9056 /// the call being lowered.
9057 ///
9058 /// This is a helper for lowering intrinsics that follow a target calling
9059 /// convention or require stack pointer adjustment. Only a subset of the
9060 /// intrinsic's operands need to participate in the calling convention.
9061 void SelectionDAGBuilder::populateCallLoweringInfo(
9062     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9063     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9064     bool IsPatchPoint) {
9065   TargetLowering::ArgListTy Args;
9066   Args.reserve(NumArgs);
9067 
9068   // Populate the argument list.
9069   // Attributes for args start at offset 1, after the return attribute.
9070   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9071        ArgI != ArgE; ++ArgI) {
9072     const Value *V = Call->getOperand(ArgI);
9073 
9074     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9075 
9076     TargetLowering::ArgListEntry Entry;
9077     Entry.Node = getValue(V);
9078     Entry.Ty = V->getType();
9079     Entry.setAttributes(Call, ArgI);
9080     Args.push_back(Entry);
9081   }
9082 
9083   CLI.setDebugLoc(getCurSDLoc())
9084       .setChain(getRoot())
9085       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9086       .setDiscardResult(Call->use_empty())
9087       .setIsPatchPoint(IsPatchPoint)
9088       .setIsPreallocated(
9089           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9090 }
9091 
9092 /// Add a stack map intrinsic call's live variable operands to a stackmap
9093 /// or patchpoint target node's operand list.
9094 ///
9095 /// Constants are converted to TargetConstants purely as an optimization to
9096 /// avoid constant materialization and register allocation.
9097 ///
9098 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9099 /// generate addess computation nodes, and so FinalizeISel can convert the
9100 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9101 /// address materialization and register allocation, but may also be required
9102 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9103 /// alloca in the entry block, then the runtime may assume that the alloca's
9104 /// StackMap location can be read immediately after compilation and that the
9105 /// location is valid at any point during execution (this is similar to the
9106 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9107 /// only available in a register, then the runtime would need to trap when
9108 /// execution reaches the StackMap in order to read the alloca's location.
9109 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9110                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9111                                 SelectionDAGBuilder &Builder) {
9112   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9113     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9114     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9115       Ops.push_back(
9116         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9117       Ops.push_back(
9118         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9119     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9120       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9121       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9122           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9123     } else
9124       Ops.push_back(OpVal);
9125   }
9126 }
9127 
9128 /// Lower llvm.experimental.stackmap directly to its target opcode.
9129 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9130   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9131   //                                  [live variables...])
9132 
9133   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9134 
9135   SDValue Chain, InFlag, Callee, NullPtr;
9136   SmallVector<SDValue, 32> Ops;
9137 
9138   SDLoc DL = getCurSDLoc();
9139   Callee = getValue(CI.getCalledOperand());
9140   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9141 
9142   // The stackmap intrinsic only records the live variables (the arguments
9143   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9144   // intrinsic, this won't be lowered to a function call. This means we don't
9145   // have to worry about calling conventions and target specific lowering code.
9146   // Instead we perform the call lowering right here.
9147   //
9148   // chain, flag = CALLSEQ_START(chain, 0, 0)
9149   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9150   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9151   //
9152   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9153   InFlag = Chain.getValue(1);
9154 
9155   // Add the <id> and <numBytes> constants.
9156   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9157   Ops.push_back(DAG.getTargetConstant(
9158                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9159   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9160   Ops.push_back(DAG.getTargetConstant(
9161                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9162                   MVT::i32));
9163 
9164   // Push live variables for the stack map.
9165   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9166 
9167   // We are not pushing any register mask info here on the operands list,
9168   // because the stackmap doesn't clobber anything.
9169 
9170   // Push the chain and the glue flag.
9171   Ops.push_back(Chain);
9172   Ops.push_back(InFlag);
9173 
9174   // Create the STACKMAP node.
9175   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9176   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9177   Chain = SDValue(SM, 0);
9178   InFlag = Chain.getValue(1);
9179 
9180   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9181 
9182   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9183 
9184   // Set the root to the target-lowered call chain.
9185   DAG.setRoot(Chain);
9186 
9187   // Inform the Frame Information that we have a stackmap in this function.
9188   FuncInfo.MF->getFrameInfo().setHasStackMap();
9189 }
9190 
9191 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9192 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9193                                           const BasicBlock *EHPadBB) {
9194   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9195   //                                                 i32 <numBytes>,
9196   //                                                 i8* <target>,
9197   //                                                 i32 <numArgs>,
9198   //                                                 [Args...],
9199   //                                                 [live variables...])
9200 
9201   CallingConv::ID CC = CB.getCallingConv();
9202   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9203   bool HasDef = !CB.getType()->isVoidTy();
9204   SDLoc dl = getCurSDLoc();
9205   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9206 
9207   // Handle immediate and symbolic callees.
9208   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9209     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9210                                    /*isTarget=*/true);
9211   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9212     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9213                                          SDLoc(SymbolicCallee),
9214                                          SymbolicCallee->getValueType(0));
9215 
9216   // Get the real number of arguments participating in the call <numArgs>
9217   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9218   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9219 
9220   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9221   // Intrinsics include all meta-operands up to but not including CC.
9222   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9223   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9224          "Not enough arguments provided to the patchpoint intrinsic");
9225 
9226   // For AnyRegCC the arguments are lowered later on manually.
9227   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9228   Type *ReturnTy =
9229       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9230 
9231   TargetLowering::CallLoweringInfo CLI(DAG);
9232   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9233                            ReturnTy, true);
9234   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9235 
9236   SDNode *CallEnd = Result.second.getNode();
9237   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9238     CallEnd = CallEnd->getOperand(0).getNode();
9239 
9240   /// Get a call instruction from the call sequence chain.
9241   /// Tail calls are not allowed.
9242   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9243          "Expected a callseq node.");
9244   SDNode *Call = CallEnd->getOperand(0).getNode();
9245   bool HasGlue = Call->getGluedNode();
9246 
9247   // Replace the target specific call node with the patchable intrinsic.
9248   SmallVector<SDValue, 8> Ops;
9249 
9250   // Add the <id> and <numBytes> constants.
9251   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9252   Ops.push_back(DAG.getTargetConstant(
9253                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9254   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9255   Ops.push_back(DAG.getTargetConstant(
9256                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9257                   MVT::i32));
9258 
9259   // Add the callee.
9260   Ops.push_back(Callee);
9261 
9262   // Adjust <numArgs> to account for any arguments that have been passed on the
9263   // stack instead.
9264   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9265   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9266   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9267   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9268 
9269   // Add the calling convention
9270   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9271 
9272   // Add the arguments we omitted previously. The register allocator should
9273   // place these in any free register.
9274   if (IsAnyRegCC)
9275     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9276       Ops.push_back(getValue(CB.getArgOperand(i)));
9277 
9278   // Push the arguments from the call instruction up to the register mask.
9279   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9280   Ops.append(Call->op_begin() + 2, e);
9281 
9282   // Push live variables for the stack map.
9283   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9284 
9285   // Push the register mask info.
9286   if (HasGlue)
9287     Ops.push_back(*(Call->op_end()-2));
9288   else
9289     Ops.push_back(*(Call->op_end()-1));
9290 
9291   // Push the chain (this is originally the first operand of the call, but
9292   // becomes now the last or second to last operand).
9293   Ops.push_back(*(Call->op_begin()));
9294 
9295   // Push the glue flag (last operand).
9296   if (HasGlue)
9297     Ops.push_back(*(Call->op_end()-1));
9298 
9299   SDVTList NodeTys;
9300   if (IsAnyRegCC && HasDef) {
9301     // Create the return types based on the intrinsic definition
9302     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9303     SmallVector<EVT, 3> ValueVTs;
9304     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9305     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9306 
9307     // There is always a chain and a glue type at the end
9308     ValueVTs.push_back(MVT::Other);
9309     ValueVTs.push_back(MVT::Glue);
9310     NodeTys = DAG.getVTList(ValueVTs);
9311   } else
9312     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9313 
9314   // Replace the target specific call node with a PATCHPOINT node.
9315   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9316                                          dl, NodeTys, Ops);
9317 
9318   // Update the NodeMap.
9319   if (HasDef) {
9320     if (IsAnyRegCC)
9321       setValue(&CB, SDValue(MN, 0));
9322     else
9323       setValue(&CB, Result.first);
9324   }
9325 
9326   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9327   // call sequence. Furthermore the location of the chain and glue can change
9328   // when the AnyReg calling convention is used and the intrinsic returns a
9329   // value.
9330   if (IsAnyRegCC && HasDef) {
9331     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9332     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9333     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9334   } else
9335     DAG.ReplaceAllUsesWith(Call, MN);
9336   DAG.DeleteNode(Call);
9337 
9338   // Inform the Frame Information that we have a patchpoint in this function.
9339   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9340 }
9341 
9342 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9343                                             unsigned Intrinsic) {
9344   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9345   SDValue Op1 = getValue(I.getArgOperand(0));
9346   SDValue Op2;
9347   if (I.getNumArgOperands() > 1)
9348     Op2 = getValue(I.getArgOperand(1));
9349   SDLoc dl = getCurSDLoc();
9350   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9351   SDValue Res;
9352   SDNodeFlags SDFlags;
9353   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9354     SDFlags.copyFMF(*FPMO);
9355 
9356   switch (Intrinsic) {
9357   case Intrinsic::vector_reduce_fadd:
9358     if (SDFlags.hasAllowReassociation())
9359       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9360                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9361                         SDFlags);
9362     else
9363       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9364     break;
9365   case Intrinsic::vector_reduce_fmul:
9366     if (SDFlags.hasAllowReassociation())
9367       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9368                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9369                         SDFlags);
9370     else
9371       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9372     break;
9373   case Intrinsic::vector_reduce_add:
9374     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9375     break;
9376   case Intrinsic::vector_reduce_mul:
9377     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9378     break;
9379   case Intrinsic::vector_reduce_and:
9380     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9381     break;
9382   case Intrinsic::vector_reduce_or:
9383     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9384     break;
9385   case Intrinsic::vector_reduce_xor:
9386     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9387     break;
9388   case Intrinsic::vector_reduce_smax:
9389     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9390     break;
9391   case Intrinsic::vector_reduce_smin:
9392     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9393     break;
9394   case Intrinsic::vector_reduce_umax:
9395     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9396     break;
9397   case Intrinsic::vector_reduce_umin:
9398     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9399     break;
9400   case Intrinsic::vector_reduce_fmax:
9401     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9402     break;
9403   case Intrinsic::vector_reduce_fmin:
9404     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9405     break;
9406   default:
9407     llvm_unreachable("Unhandled vector reduce intrinsic");
9408   }
9409   setValue(&I, Res);
9410 }
9411 
9412 /// Returns an AttributeList representing the attributes applied to the return
9413 /// value of the given call.
9414 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9415   SmallVector<Attribute::AttrKind, 2> Attrs;
9416   if (CLI.RetSExt)
9417     Attrs.push_back(Attribute::SExt);
9418   if (CLI.RetZExt)
9419     Attrs.push_back(Attribute::ZExt);
9420   if (CLI.IsInReg)
9421     Attrs.push_back(Attribute::InReg);
9422 
9423   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9424                             Attrs);
9425 }
9426 
9427 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9428 /// implementation, which just calls LowerCall.
9429 /// FIXME: When all targets are
9430 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9431 std::pair<SDValue, SDValue>
9432 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9433   // Handle the incoming return values from the call.
9434   CLI.Ins.clear();
9435   Type *OrigRetTy = CLI.RetTy;
9436   SmallVector<EVT, 4> RetTys;
9437   SmallVector<uint64_t, 4> Offsets;
9438   auto &DL = CLI.DAG.getDataLayout();
9439   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9440 
9441   if (CLI.IsPostTypeLegalization) {
9442     // If we are lowering a libcall after legalization, split the return type.
9443     SmallVector<EVT, 4> OldRetTys;
9444     SmallVector<uint64_t, 4> OldOffsets;
9445     RetTys.swap(OldRetTys);
9446     Offsets.swap(OldOffsets);
9447 
9448     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9449       EVT RetVT = OldRetTys[i];
9450       uint64_t Offset = OldOffsets[i];
9451       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9452       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9453       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9454       RetTys.append(NumRegs, RegisterVT);
9455       for (unsigned j = 0; j != NumRegs; ++j)
9456         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9457     }
9458   }
9459 
9460   SmallVector<ISD::OutputArg, 4> Outs;
9461   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9462 
9463   bool CanLowerReturn =
9464       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9465                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9466 
9467   SDValue DemoteStackSlot;
9468   int DemoteStackIdx = -100;
9469   if (!CanLowerReturn) {
9470     // FIXME: equivalent assert?
9471     // assert(!CS.hasInAllocaArgument() &&
9472     //        "sret demotion is incompatible with inalloca");
9473     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9474     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9475     MachineFunction &MF = CLI.DAG.getMachineFunction();
9476     DemoteStackIdx =
9477         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9478     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9479                                               DL.getAllocaAddrSpace());
9480 
9481     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9482     ArgListEntry Entry;
9483     Entry.Node = DemoteStackSlot;
9484     Entry.Ty = StackSlotPtrType;
9485     Entry.IsSExt = false;
9486     Entry.IsZExt = false;
9487     Entry.IsInReg = false;
9488     Entry.IsSRet = true;
9489     Entry.IsNest = false;
9490     Entry.IsByVal = false;
9491     Entry.IsByRef = false;
9492     Entry.IsReturned = false;
9493     Entry.IsSwiftSelf = false;
9494     Entry.IsSwiftAsync = false;
9495     Entry.IsSwiftError = false;
9496     Entry.IsCFGuardTarget = false;
9497     Entry.Alignment = Alignment;
9498     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9499     CLI.NumFixedArgs += 1;
9500     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9501 
9502     // sret demotion isn't compatible with tail-calls, since the sret argument
9503     // points into the callers stack frame.
9504     CLI.IsTailCall = false;
9505   } else {
9506     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9507         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9508     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9509       ISD::ArgFlagsTy Flags;
9510       if (NeedsRegBlock) {
9511         Flags.setInConsecutiveRegs();
9512         if (I == RetTys.size() - 1)
9513           Flags.setInConsecutiveRegsLast();
9514       }
9515       EVT VT = RetTys[I];
9516       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9517                                                      CLI.CallConv, VT);
9518       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9519                                                        CLI.CallConv, VT);
9520       for (unsigned i = 0; i != NumRegs; ++i) {
9521         ISD::InputArg MyFlags;
9522         MyFlags.Flags = Flags;
9523         MyFlags.VT = RegisterVT;
9524         MyFlags.ArgVT = VT;
9525         MyFlags.Used = CLI.IsReturnValueUsed;
9526         if (CLI.RetTy->isPointerTy()) {
9527           MyFlags.Flags.setPointer();
9528           MyFlags.Flags.setPointerAddrSpace(
9529               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9530         }
9531         if (CLI.RetSExt)
9532           MyFlags.Flags.setSExt();
9533         if (CLI.RetZExt)
9534           MyFlags.Flags.setZExt();
9535         if (CLI.IsInReg)
9536           MyFlags.Flags.setInReg();
9537         CLI.Ins.push_back(MyFlags);
9538       }
9539     }
9540   }
9541 
9542   // We push in swifterror return as the last element of CLI.Ins.
9543   ArgListTy &Args = CLI.getArgs();
9544   if (supportSwiftError()) {
9545     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9546       if (Args[i].IsSwiftError) {
9547         ISD::InputArg MyFlags;
9548         MyFlags.VT = getPointerTy(DL);
9549         MyFlags.ArgVT = EVT(getPointerTy(DL));
9550         MyFlags.Flags.setSwiftError();
9551         CLI.Ins.push_back(MyFlags);
9552       }
9553     }
9554   }
9555 
9556   // Handle all of the outgoing arguments.
9557   CLI.Outs.clear();
9558   CLI.OutVals.clear();
9559   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9560     SmallVector<EVT, 4> ValueVTs;
9561     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9562     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9563     Type *FinalType = Args[i].Ty;
9564     if (Args[i].IsByVal)
9565       FinalType = Args[i].IndirectType;
9566     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9567         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9568     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9569          ++Value) {
9570       EVT VT = ValueVTs[Value];
9571       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9572       SDValue Op = SDValue(Args[i].Node.getNode(),
9573                            Args[i].Node.getResNo() + Value);
9574       ISD::ArgFlagsTy Flags;
9575 
9576       // Certain targets (such as MIPS), may have a different ABI alignment
9577       // for a type depending on the context. Give the target a chance to
9578       // specify the alignment it wants.
9579       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9580       Flags.setOrigAlign(OriginalAlignment);
9581 
9582       if (Args[i].Ty->isPointerTy()) {
9583         Flags.setPointer();
9584         Flags.setPointerAddrSpace(
9585             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9586       }
9587       if (Args[i].IsZExt)
9588         Flags.setZExt();
9589       if (Args[i].IsSExt)
9590         Flags.setSExt();
9591       if (Args[i].IsInReg) {
9592         // If we are using vectorcall calling convention, a structure that is
9593         // passed InReg - is surely an HVA
9594         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9595             isa<StructType>(FinalType)) {
9596           // The first value of a structure is marked
9597           if (0 == Value)
9598             Flags.setHvaStart();
9599           Flags.setHva();
9600         }
9601         // Set InReg Flag
9602         Flags.setInReg();
9603       }
9604       if (Args[i].IsSRet)
9605         Flags.setSRet();
9606       if (Args[i].IsSwiftSelf)
9607         Flags.setSwiftSelf();
9608       if (Args[i].IsSwiftAsync)
9609         Flags.setSwiftAsync();
9610       if (Args[i].IsSwiftError)
9611         Flags.setSwiftError();
9612       if (Args[i].IsCFGuardTarget)
9613         Flags.setCFGuardTarget();
9614       if (Args[i].IsByVal)
9615         Flags.setByVal();
9616       if (Args[i].IsByRef)
9617         Flags.setByRef();
9618       if (Args[i].IsPreallocated) {
9619         Flags.setPreallocated();
9620         // Set the byval flag for CCAssignFn callbacks that don't know about
9621         // preallocated.  This way we can know how many bytes we should've
9622         // allocated and how many bytes a callee cleanup function will pop.  If
9623         // we port preallocated to more targets, we'll have to add custom
9624         // preallocated handling in the various CC lowering callbacks.
9625         Flags.setByVal();
9626       }
9627       if (Args[i].IsInAlloca) {
9628         Flags.setInAlloca();
9629         // Set the byval flag for CCAssignFn callbacks that don't know about
9630         // inalloca.  This way we can know how many bytes we should've allocated
9631         // and how many bytes a callee cleanup function will pop.  If we port
9632         // inalloca to more targets, we'll have to add custom inalloca handling
9633         // in the various CC lowering callbacks.
9634         Flags.setByVal();
9635       }
9636       Align MemAlign;
9637       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9638         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9639         Flags.setByValSize(FrameSize);
9640 
9641         // info is not there but there are cases it cannot get right.
9642         if (auto MA = Args[i].Alignment)
9643           MemAlign = *MA;
9644         else
9645           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9646       } else if (auto MA = Args[i].Alignment) {
9647         MemAlign = *MA;
9648       } else {
9649         MemAlign = OriginalAlignment;
9650       }
9651       Flags.setMemAlign(MemAlign);
9652       if (Args[i].IsNest)
9653         Flags.setNest();
9654       if (NeedsRegBlock)
9655         Flags.setInConsecutiveRegs();
9656 
9657       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9658                                                  CLI.CallConv, VT);
9659       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9660                                                         CLI.CallConv, VT);
9661       SmallVector<SDValue, 4> Parts(NumParts);
9662       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9663 
9664       if (Args[i].IsSExt)
9665         ExtendKind = ISD::SIGN_EXTEND;
9666       else if (Args[i].IsZExt)
9667         ExtendKind = ISD::ZERO_EXTEND;
9668 
9669       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9670       // for now.
9671       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9672           CanLowerReturn) {
9673         assert((CLI.RetTy == Args[i].Ty ||
9674                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9675                  CLI.RetTy->getPointerAddressSpace() ==
9676                      Args[i].Ty->getPointerAddressSpace())) &&
9677                RetTys.size() == NumValues && "unexpected use of 'returned'");
9678         // Before passing 'returned' to the target lowering code, ensure that
9679         // either the register MVT and the actual EVT are the same size or that
9680         // the return value and argument are extended in the same way; in these
9681         // cases it's safe to pass the argument register value unchanged as the
9682         // return register value (although it's at the target's option whether
9683         // to do so)
9684         // TODO: allow code generation to take advantage of partially preserved
9685         // registers rather than clobbering the entire register when the
9686         // parameter extension method is not compatible with the return
9687         // extension method
9688         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9689             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9690              CLI.RetZExt == Args[i].IsZExt))
9691           Flags.setReturned();
9692       }
9693 
9694       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9695                      CLI.CallConv, ExtendKind);
9696 
9697       for (unsigned j = 0; j != NumParts; ++j) {
9698         // if it isn't first piece, alignment must be 1
9699         // For scalable vectors the scalable part is currently handled
9700         // by individual targets, so we just use the known minimum size here.
9701         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9702                     i < CLI.NumFixedArgs, i,
9703                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9704         if (NumParts > 1 && j == 0)
9705           MyFlags.Flags.setSplit();
9706         else if (j != 0) {
9707           MyFlags.Flags.setOrigAlign(Align(1));
9708           if (j == NumParts - 1)
9709             MyFlags.Flags.setSplitEnd();
9710         }
9711 
9712         CLI.Outs.push_back(MyFlags);
9713         CLI.OutVals.push_back(Parts[j]);
9714       }
9715 
9716       if (NeedsRegBlock && Value == NumValues - 1)
9717         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9718     }
9719   }
9720 
9721   SmallVector<SDValue, 4> InVals;
9722   CLI.Chain = LowerCall(CLI, InVals);
9723 
9724   // Update CLI.InVals to use outside of this function.
9725   CLI.InVals = InVals;
9726 
9727   // Verify that the target's LowerCall behaved as expected.
9728   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9729          "LowerCall didn't return a valid chain!");
9730   assert((!CLI.IsTailCall || InVals.empty()) &&
9731          "LowerCall emitted a return value for a tail call!");
9732   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9733          "LowerCall didn't emit the correct number of values!");
9734 
9735   // For a tail call, the return value is merely live-out and there aren't
9736   // any nodes in the DAG representing it. Return a special value to
9737   // indicate that a tail call has been emitted and no more Instructions
9738   // should be processed in the current block.
9739   if (CLI.IsTailCall) {
9740     CLI.DAG.setRoot(CLI.Chain);
9741     return std::make_pair(SDValue(), SDValue());
9742   }
9743 
9744 #ifndef NDEBUG
9745   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9746     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9747     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9748            "LowerCall emitted a value with the wrong type!");
9749   }
9750 #endif
9751 
9752   SmallVector<SDValue, 4> ReturnValues;
9753   if (!CanLowerReturn) {
9754     // The instruction result is the result of loading from the
9755     // hidden sret parameter.
9756     SmallVector<EVT, 1> PVTs;
9757     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9758 
9759     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9760     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9761     EVT PtrVT = PVTs[0];
9762 
9763     unsigned NumValues = RetTys.size();
9764     ReturnValues.resize(NumValues);
9765     SmallVector<SDValue, 4> Chains(NumValues);
9766 
9767     // An aggregate return value cannot wrap around the address space, so
9768     // offsets to its parts don't wrap either.
9769     SDNodeFlags Flags;
9770     Flags.setNoUnsignedWrap(true);
9771 
9772     MachineFunction &MF = CLI.DAG.getMachineFunction();
9773     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9774     for (unsigned i = 0; i < NumValues; ++i) {
9775       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9776                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9777                                                         PtrVT), Flags);
9778       SDValue L = CLI.DAG.getLoad(
9779           RetTys[i], CLI.DL, CLI.Chain, Add,
9780           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9781                                             DemoteStackIdx, Offsets[i]),
9782           HiddenSRetAlign);
9783       ReturnValues[i] = L;
9784       Chains[i] = L.getValue(1);
9785     }
9786 
9787     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9788   } else {
9789     // Collect the legal value parts into potentially illegal values
9790     // that correspond to the original function's return values.
9791     Optional<ISD::NodeType> AssertOp;
9792     if (CLI.RetSExt)
9793       AssertOp = ISD::AssertSext;
9794     else if (CLI.RetZExt)
9795       AssertOp = ISD::AssertZext;
9796     unsigned CurReg = 0;
9797     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9798       EVT VT = RetTys[I];
9799       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9800                                                      CLI.CallConv, VT);
9801       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9802                                                        CLI.CallConv, VT);
9803 
9804       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9805                                               NumRegs, RegisterVT, VT, nullptr,
9806                                               CLI.CallConv, AssertOp));
9807       CurReg += NumRegs;
9808     }
9809 
9810     // For a function returning void, there is no return value. We can't create
9811     // such a node, so we just return a null return value in that case. In
9812     // that case, nothing will actually look at the value.
9813     if (ReturnValues.empty())
9814       return std::make_pair(SDValue(), CLI.Chain);
9815   }
9816 
9817   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9818                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9819   return std::make_pair(Res, CLI.Chain);
9820 }
9821 
9822 /// Places new result values for the node in Results (their number
9823 /// and types must exactly match those of the original return values of
9824 /// the node), or leaves Results empty, which indicates that the node is not
9825 /// to be custom lowered after all.
9826 void TargetLowering::LowerOperationWrapper(SDNode *N,
9827                                            SmallVectorImpl<SDValue> &Results,
9828                                            SelectionDAG &DAG) const {
9829   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9830 
9831   if (!Res.getNode())
9832     return;
9833 
9834   // If the original node has one result, take the return value from
9835   // LowerOperation as is. It might not be result number 0.
9836   if (N->getNumValues() == 1) {
9837     Results.push_back(Res);
9838     return;
9839   }
9840 
9841   // If the original node has multiple results, then the return node should
9842   // have the same number of results.
9843   assert((N->getNumValues() == Res->getNumValues()) &&
9844       "Lowering returned the wrong number of results!");
9845 
9846   // Places new result values base on N result number.
9847   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9848     Results.push_back(Res.getValue(I));
9849 }
9850 
9851 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9852   llvm_unreachable("LowerOperation not implemented for this target!");
9853 }
9854 
9855 void
9856 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9857   SDValue Op = getNonRegisterValue(V);
9858   assert((Op.getOpcode() != ISD::CopyFromReg ||
9859           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9860          "Copy from a reg to the same reg!");
9861   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9862 
9863   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9864   // If this is an InlineAsm we have to match the registers required, not the
9865   // notional registers required by the type.
9866 
9867   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9868                    None); // This is not an ABI copy.
9869   SDValue Chain = DAG.getEntryNode();
9870 
9871   ISD::NodeType ExtendType = ISD::ANY_EXTEND;
9872   auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
9873   if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
9874     ExtendType = PreferredExtendIt->second;
9875   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9876   PendingExports.push_back(Chain);
9877 }
9878 
9879 #include "llvm/CodeGen/SelectionDAGISel.h"
9880 
9881 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9882 /// entry block, return true.  This includes arguments used by switches, since
9883 /// the switch may expand into multiple basic blocks.
9884 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9885   // With FastISel active, we may be splitting blocks, so force creation
9886   // of virtual registers for all non-dead arguments.
9887   if (FastISel)
9888     return A->use_empty();
9889 
9890   const BasicBlock &Entry = A->getParent()->front();
9891   for (const User *U : A->users())
9892     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9893       return false;  // Use not in entry block.
9894 
9895   return true;
9896 }
9897 
9898 using ArgCopyElisionMapTy =
9899     DenseMap<const Argument *,
9900              std::pair<const AllocaInst *, const StoreInst *>>;
9901 
9902 /// Scan the entry block of the function in FuncInfo for arguments that look
9903 /// like copies into a local alloca. Record any copied arguments in
9904 /// ArgCopyElisionCandidates.
9905 static void
9906 findArgumentCopyElisionCandidates(const DataLayout &DL,
9907                                   FunctionLoweringInfo *FuncInfo,
9908                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9909   // Record the state of every static alloca used in the entry block. Argument
9910   // allocas are all used in the entry block, so we need approximately as many
9911   // entries as we have arguments.
9912   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9913   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9914   unsigned NumArgs = FuncInfo->Fn->arg_size();
9915   StaticAllocas.reserve(NumArgs * 2);
9916 
9917   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9918     if (!V)
9919       return nullptr;
9920     V = V->stripPointerCasts();
9921     const auto *AI = dyn_cast<AllocaInst>(V);
9922     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9923       return nullptr;
9924     auto Iter = StaticAllocas.insert({AI, Unknown});
9925     return &Iter.first->second;
9926   };
9927 
9928   // Look for stores of arguments to static allocas. Look through bitcasts and
9929   // GEPs to handle type coercions, as long as the alloca is fully initialized
9930   // by the store. Any non-store use of an alloca escapes it and any subsequent
9931   // unanalyzed store might write it.
9932   // FIXME: Handle structs initialized with multiple stores.
9933   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9934     // Look for stores, and handle non-store uses conservatively.
9935     const auto *SI = dyn_cast<StoreInst>(&I);
9936     if (!SI) {
9937       // We will look through cast uses, so ignore them completely.
9938       if (I.isCast())
9939         continue;
9940       // Ignore debug info and pseudo op intrinsics, they don't escape or store
9941       // to allocas.
9942       if (I.isDebugOrPseudoInst())
9943         continue;
9944       // This is an unknown instruction. Assume it escapes or writes to all
9945       // static alloca operands.
9946       for (const Use &U : I.operands()) {
9947         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9948           *Info = StaticAllocaInfo::Clobbered;
9949       }
9950       continue;
9951     }
9952 
9953     // If the stored value is a static alloca, mark it as escaped.
9954     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9955       *Info = StaticAllocaInfo::Clobbered;
9956 
9957     // Check if the destination is a static alloca.
9958     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9959     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9960     if (!Info)
9961       continue;
9962     const AllocaInst *AI = cast<AllocaInst>(Dst);
9963 
9964     // Skip allocas that have been initialized or clobbered.
9965     if (*Info != StaticAllocaInfo::Unknown)
9966       continue;
9967 
9968     // Check if the stored value is an argument, and that this store fully
9969     // initializes the alloca.
9970     // If the argument type has padding bits we can't directly forward a pointer
9971     // as the upper bits may contain garbage.
9972     // Don't elide copies from the same argument twice.
9973     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9974     const auto *Arg = dyn_cast<Argument>(Val);
9975     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9976         Arg->getType()->isEmptyTy() ||
9977         DL.getTypeStoreSize(Arg->getType()) !=
9978             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9979         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
9980         ArgCopyElisionCandidates.count(Arg)) {
9981       *Info = StaticAllocaInfo::Clobbered;
9982       continue;
9983     }
9984 
9985     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9986                       << '\n');
9987 
9988     // Mark this alloca and store for argument copy elision.
9989     *Info = StaticAllocaInfo::Elidable;
9990     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9991 
9992     // Stop scanning if we've seen all arguments. This will happen early in -O0
9993     // builds, which is useful, because -O0 builds have large entry blocks and
9994     // many allocas.
9995     if (ArgCopyElisionCandidates.size() == NumArgs)
9996       break;
9997   }
9998 }
9999 
10000 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10001 /// ArgVal is a load from a suitable fixed stack object.
10002 static void tryToElideArgumentCopy(
10003     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10004     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10005     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10006     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10007     SDValue ArgVal, bool &ArgHasUses) {
10008   // Check if this is a load from a fixed stack object.
10009   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10010   if (!LNode)
10011     return;
10012   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10013   if (!FINode)
10014     return;
10015 
10016   // Check that the fixed stack object is the right size and alignment.
10017   // Look at the alignment that the user wrote on the alloca instead of looking
10018   // at the stack object.
10019   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10020   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10021   const AllocaInst *AI = ArgCopyIter->second.first;
10022   int FixedIndex = FINode->getIndex();
10023   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10024   int OldIndex = AllocaIndex;
10025   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10026   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10027     LLVM_DEBUG(
10028         dbgs() << "  argument copy elision failed due to bad fixed stack "
10029                   "object size\n");
10030     return;
10031   }
10032   Align RequiredAlignment = AI->getAlign();
10033   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10034     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10035                          "greater than stack argument alignment ("
10036                       << DebugStr(RequiredAlignment) << " vs "
10037                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10038     return;
10039   }
10040 
10041   // Perform the elision. Delete the old stack object and replace its only use
10042   // in the variable info map. Mark the stack object as mutable.
10043   LLVM_DEBUG({
10044     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10045            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10046            << '\n';
10047   });
10048   MFI.RemoveStackObject(OldIndex);
10049   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10050   AllocaIndex = FixedIndex;
10051   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10052   Chains.push_back(ArgVal.getValue(1));
10053 
10054   // Avoid emitting code for the store implementing the copy.
10055   const StoreInst *SI = ArgCopyIter->second.second;
10056   ElidedArgCopyInstrs.insert(SI);
10057 
10058   // Check for uses of the argument again so that we can avoid exporting ArgVal
10059   // if it is't used by anything other than the store.
10060   for (const Value *U : Arg.users()) {
10061     if (U != SI) {
10062       ArgHasUses = true;
10063       break;
10064     }
10065   }
10066 }
10067 
10068 void SelectionDAGISel::LowerArguments(const Function &F) {
10069   SelectionDAG &DAG = SDB->DAG;
10070   SDLoc dl = SDB->getCurSDLoc();
10071   const DataLayout &DL = DAG.getDataLayout();
10072   SmallVector<ISD::InputArg, 16> Ins;
10073 
10074   // In Naked functions we aren't going to save any registers.
10075   if (F.hasFnAttribute(Attribute::Naked))
10076     return;
10077 
10078   if (!FuncInfo->CanLowerReturn) {
10079     // Put in an sret pointer parameter before all the other parameters.
10080     SmallVector<EVT, 1> ValueVTs;
10081     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10082                     F.getReturnType()->getPointerTo(
10083                         DAG.getDataLayout().getAllocaAddrSpace()),
10084                     ValueVTs);
10085 
10086     // NOTE: Assuming that a pointer will never break down to more than one VT
10087     // or one register.
10088     ISD::ArgFlagsTy Flags;
10089     Flags.setSRet();
10090     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10091     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10092                          ISD::InputArg::NoArgIndex, 0);
10093     Ins.push_back(RetArg);
10094   }
10095 
10096   // Look for stores of arguments to static allocas. Mark such arguments with a
10097   // flag to ask the target to give us the memory location of that argument if
10098   // available.
10099   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10100   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10101                                     ArgCopyElisionCandidates);
10102 
10103   // Set up the incoming argument description vector.
10104   for (const Argument &Arg : F.args()) {
10105     unsigned ArgNo = Arg.getArgNo();
10106     SmallVector<EVT, 4> ValueVTs;
10107     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10108     bool isArgValueUsed = !Arg.use_empty();
10109     unsigned PartBase = 0;
10110     Type *FinalType = Arg.getType();
10111     if (Arg.hasAttribute(Attribute::ByVal))
10112       FinalType = Arg.getParamByValType();
10113     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10114         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10115     for (unsigned Value = 0, NumValues = ValueVTs.size();
10116          Value != NumValues; ++Value) {
10117       EVT VT = ValueVTs[Value];
10118       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10119       ISD::ArgFlagsTy Flags;
10120 
10121 
10122       if (Arg.getType()->isPointerTy()) {
10123         Flags.setPointer();
10124         Flags.setPointerAddrSpace(
10125             cast<PointerType>(Arg.getType())->getAddressSpace());
10126       }
10127       if (Arg.hasAttribute(Attribute::ZExt))
10128         Flags.setZExt();
10129       if (Arg.hasAttribute(Attribute::SExt))
10130         Flags.setSExt();
10131       if (Arg.hasAttribute(Attribute::InReg)) {
10132         // If we are using vectorcall calling convention, a structure that is
10133         // passed InReg - is surely an HVA
10134         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10135             isa<StructType>(Arg.getType())) {
10136           // The first value of a structure is marked
10137           if (0 == Value)
10138             Flags.setHvaStart();
10139           Flags.setHva();
10140         }
10141         // Set InReg Flag
10142         Flags.setInReg();
10143       }
10144       if (Arg.hasAttribute(Attribute::StructRet))
10145         Flags.setSRet();
10146       if (Arg.hasAttribute(Attribute::SwiftSelf))
10147         Flags.setSwiftSelf();
10148       if (Arg.hasAttribute(Attribute::SwiftAsync))
10149         Flags.setSwiftAsync();
10150       if (Arg.hasAttribute(Attribute::SwiftError))
10151         Flags.setSwiftError();
10152       if (Arg.hasAttribute(Attribute::ByVal))
10153         Flags.setByVal();
10154       if (Arg.hasAttribute(Attribute::ByRef))
10155         Flags.setByRef();
10156       if (Arg.hasAttribute(Attribute::InAlloca)) {
10157         Flags.setInAlloca();
10158         // Set the byval flag for CCAssignFn callbacks that don't know about
10159         // inalloca.  This way we can know how many bytes we should've allocated
10160         // and how many bytes a callee cleanup function will pop.  If we port
10161         // inalloca to more targets, we'll have to add custom inalloca handling
10162         // in the various CC lowering callbacks.
10163         Flags.setByVal();
10164       }
10165       if (Arg.hasAttribute(Attribute::Preallocated)) {
10166         Flags.setPreallocated();
10167         // Set the byval flag for CCAssignFn callbacks that don't know about
10168         // preallocated.  This way we can know how many bytes we should've
10169         // allocated and how many bytes a callee cleanup function will pop.  If
10170         // we port preallocated to more targets, we'll have to add custom
10171         // preallocated handling in the various CC lowering callbacks.
10172         Flags.setByVal();
10173       }
10174 
10175       // Certain targets (such as MIPS), may have a different ABI alignment
10176       // for a type depending on the context. Give the target a chance to
10177       // specify the alignment it wants.
10178       const Align OriginalAlignment(
10179           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10180       Flags.setOrigAlign(OriginalAlignment);
10181 
10182       Align MemAlign;
10183       Type *ArgMemTy = nullptr;
10184       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10185           Flags.isByRef()) {
10186         if (!ArgMemTy)
10187           ArgMemTy = Arg.getPointeeInMemoryValueType();
10188 
10189         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10190 
10191         // For in-memory arguments, size and alignment should be passed from FE.
10192         // BE will guess if this info is not there but there are cases it cannot
10193         // get right.
10194         if (auto ParamAlign = Arg.getParamStackAlign())
10195           MemAlign = *ParamAlign;
10196         else if ((ParamAlign = Arg.getParamAlign()))
10197           MemAlign = *ParamAlign;
10198         else
10199           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10200         if (Flags.isByRef())
10201           Flags.setByRefSize(MemSize);
10202         else
10203           Flags.setByValSize(MemSize);
10204       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10205         MemAlign = *ParamAlign;
10206       } else {
10207         MemAlign = OriginalAlignment;
10208       }
10209       Flags.setMemAlign(MemAlign);
10210 
10211       if (Arg.hasAttribute(Attribute::Nest))
10212         Flags.setNest();
10213       if (NeedsRegBlock)
10214         Flags.setInConsecutiveRegs();
10215       if (ArgCopyElisionCandidates.count(&Arg))
10216         Flags.setCopyElisionCandidate();
10217       if (Arg.hasAttribute(Attribute::Returned))
10218         Flags.setReturned();
10219 
10220       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10221           *CurDAG->getContext(), F.getCallingConv(), VT);
10222       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10223           *CurDAG->getContext(), F.getCallingConv(), VT);
10224       for (unsigned i = 0; i != NumRegs; ++i) {
10225         // For scalable vectors, use the minimum size; individual targets
10226         // are responsible for handling scalable vector arguments and
10227         // return values.
10228         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10229                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10230         if (NumRegs > 1 && i == 0)
10231           MyFlags.Flags.setSplit();
10232         // if it isn't first piece, alignment must be 1
10233         else if (i > 0) {
10234           MyFlags.Flags.setOrigAlign(Align(1));
10235           if (i == NumRegs - 1)
10236             MyFlags.Flags.setSplitEnd();
10237         }
10238         Ins.push_back(MyFlags);
10239       }
10240       if (NeedsRegBlock && Value == NumValues - 1)
10241         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10242       PartBase += VT.getStoreSize().getKnownMinSize();
10243     }
10244   }
10245 
10246   // Call the target to set up the argument values.
10247   SmallVector<SDValue, 8> InVals;
10248   SDValue NewRoot = TLI->LowerFormalArguments(
10249       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10250 
10251   // Verify that the target's LowerFormalArguments behaved as expected.
10252   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10253          "LowerFormalArguments didn't return a valid chain!");
10254   assert(InVals.size() == Ins.size() &&
10255          "LowerFormalArguments didn't emit the correct number of values!");
10256   LLVM_DEBUG({
10257     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10258       assert(InVals[i].getNode() &&
10259              "LowerFormalArguments emitted a null value!");
10260       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10261              "LowerFormalArguments emitted a value with the wrong type!");
10262     }
10263   });
10264 
10265   // Update the DAG with the new chain value resulting from argument lowering.
10266   DAG.setRoot(NewRoot);
10267 
10268   // Set up the argument values.
10269   unsigned i = 0;
10270   if (!FuncInfo->CanLowerReturn) {
10271     // Create a virtual register for the sret pointer, and put in a copy
10272     // from the sret argument into it.
10273     SmallVector<EVT, 1> ValueVTs;
10274     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10275                     F.getReturnType()->getPointerTo(
10276                         DAG.getDataLayout().getAllocaAddrSpace()),
10277                     ValueVTs);
10278     MVT VT = ValueVTs[0].getSimpleVT();
10279     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10280     Optional<ISD::NodeType> AssertOp = None;
10281     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10282                                         nullptr, F.getCallingConv(), AssertOp);
10283 
10284     MachineFunction& MF = SDB->DAG.getMachineFunction();
10285     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10286     Register SRetReg =
10287         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10288     FuncInfo->DemoteRegister = SRetReg;
10289     NewRoot =
10290         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10291     DAG.setRoot(NewRoot);
10292 
10293     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10294     ++i;
10295   }
10296 
10297   SmallVector<SDValue, 4> Chains;
10298   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10299   for (const Argument &Arg : F.args()) {
10300     SmallVector<SDValue, 4> ArgValues;
10301     SmallVector<EVT, 4> ValueVTs;
10302     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10303     unsigned NumValues = ValueVTs.size();
10304     if (NumValues == 0)
10305       continue;
10306 
10307     bool ArgHasUses = !Arg.use_empty();
10308 
10309     // Elide the copying store if the target loaded this argument from a
10310     // suitable fixed stack object.
10311     if (Ins[i].Flags.isCopyElisionCandidate()) {
10312       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10313                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10314                              InVals[i], ArgHasUses);
10315     }
10316 
10317     // If this argument is unused then remember its value. It is used to generate
10318     // debugging information.
10319     bool isSwiftErrorArg =
10320         TLI->supportSwiftError() &&
10321         Arg.hasAttribute(Attribute::SwiftError);
10322     if (!ArgHasUses && !isSwiftErrorArg) {
10323       SDB->setUnusedArgValue(&Arg, InVals[i]);
10324 
10325       // Also remember any frame index for use in FastISel.
10326       if (FrameIndexSDNode *FI =
10327           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10328         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10329     }
10330 
10331     for (unsigned Val = 0; Val != NumValues; ++Val) {
10332       EVT VT = ValueVTs[Val];
10333       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10334                                                       F.getCallingConv(), VT);
10335       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10336           *CurDAG->getContext(), F.getCallingConv(), VT);
10337 
10338       // Even an apparent 'unused' swifterror argument needs to be returned. So
10339       // we do generate a copy for it that can be used on return from the
10340       // function.
10341       if (ArgHasUses || isSwiftErrorArg) {
10342         Optional<ISD::NodeType> AssertOp;
10343         if (Arg.hasAttribute(Attribute::SExt))
10344           AssertOp = ISD::AssertSext;
10345         else if (Arg.hasAttribute(Attribute::ZExt))
10346           AssertOp = ISD::AssertZext;
10347 
10348         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10349                                              PartVT, VT, nullptr,
10350                                              F.getCallingConv(), AssertOp));
10351       }
10352 
10353       i += NumParts;
10354     }
10355 
10356     // We don't need to do anything else for unused arguments.
10357     if (ArgValues.empty())
10358       continue;
10359 
10360     // Note down frame index.
10361     if (FrameIndexSDNode *FI =
10362         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10363       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10364 
10365     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10366                                      SDB->getCurSDLoc());
10367 
10368     SDB->setValue(&Arg, Res);
10369     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10370       // We want to associate the argument with the frame index, among
10371       // involved operands, that correspond to the lowest address. The
10372       // getCopyFromParts function, called earlier, is swapping the order of
10373       // the operands to BUILD_PAIR depending on endianness. The result of
10374       // that swapping is that the least significant bits of the argument will
10375       // be in the first operand of the BUILD_PAIR node, and the most
10376       // significant bits will be in the second operand.
10377       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10378       if (LoadSDNode *LNode =
10379           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10380         if (FrameIndexSDNode *FI =
10381             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10382           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10383     }
10384 
10385     // Analyses past this point are naive and don't expect an assertion.
10386     if (Res.getOpcode() == ISD::AssertZext)
10387       Res = Res.getOperand(0);
10388 
10389     // Update the SwiftErrorVRegDefMap.
10390     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10391       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10392       if (Register::isVirtualRegister(Reg))
10393         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10394                                    Reg);
10395     }
10396 
10397     // If this argument is live outside of the entry block, insert a copy from
10398     // wherever we got it to the vreg that other BB's will reference it as.
10399     if (Res.getOpcode() == ISD::CopyFromReg) {
10400       // If we can, though, try to skip creating an unnecessary vreg.
10401       // FIXME: This isn't very clean... it would be nice to make this more
10402       // general.
10403       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10404       if (Register::isVirtualRegister(Reg)) {
10405         FuncInfo->ValueMap[&Arg] = Reg;
10406         continue;
10407       }
10408     }
10409     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10410       FuncInfo->InitializeRegForValue(&Arg);
10411       SDB->CopyToExportRegsIfNeeded(&Arg);
10412     }
10413   }
10414 
10415   if (!Chains.empty()) {
10416     Chains.push_back(NewRoot);
10417     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10418   }
10419 
10420   DAG.setRoot(NewRoot);
10421 
10422   assert(i == InVals.size() && "Argument register count mismatch!");
10423 
10424   // If any argument copy elisions occurred and we have debug info, update the
10425   // stale frame indices used in the dbg.declare variable info table.
10426   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10427   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10428     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10429       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10430       if (I != ArgCopyElisionFrameIndexMap.end())
10431         VI.Slot = I->second;
10432     }
10433   }
10434 
10435   // Finally, if the target has anything special to do, allow it to do so.
10436   emitFunctionEntryCode();
10437 }
10438 
10439 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10440 /// ensure constants are generated when needed.  Remember the virtual registers
10441 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10442 /// directly add them, because expansion might result in multiple MBB's for one
10443 /// BB.  As such, the start of the BB might correspond to a different MBB than
10444 /// the end.
10445 void
10446 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10447   const Instruction *TI = LLVMBB->getTerminator();
10448 
10449   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10450 
10451   // Check PHI nodes in successors that expect a value to be available from this
10452   // block.
10453   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10454     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10455     if (!isa<PHINode>(SuccBB->begin())) continue;
10456     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10457 
10458     // If this terminator has multiple identical successors (common for
10459     // switches), only handle each succ once.
10460     if (!SuccsHandled.insert(SuccMBB).second)
10461       continue;
10462 
10463     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10464 
10465     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10466     // nodes and Machine PHI nodes, but the incoming operands have not been
10467     // emitted yet.
10468     for (const PHINode &PN : SuccBB->phis()) {
10469       // Ignore dead phi's.
10470       if (PN.use_empty())
10471         continue;
10472 
10473       // Skip empty types
10474       if (PN.getType()->isEmptyTy())
10475         continue;
10476 
10477       unsigned Reg;
10478       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10479 
10480       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10481         unsigned &RegOut = ConstantsOut[C];
10482         if (RegOut == 0) {
10483           RegOut = FuncInfo.CreateRegs(C);
10484           CopyValueToVirtualRegister(C, RegOut);
10485         }
10486         Reg = RegOut;
10487       } else {
10488         DenseMap<const Value *, Register>::iterator I =
10489           FuncInfo.ValueMap.find(PHIOp);
10490         if (I != FuncInfo.ValueMap.end())
10491           Reg = I->second;
10492         else {
10493           assert(isa<AllocaInst>(PHIOp) &&
10494                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10495                  "Didn't codegen value into a register!??");
10496           Reg = FuncInfo.CreateRegs(PHIOp);
10497           CopyValueToVirtualRegister(PHIOp, Reg);
10498         }
10499       }
10500 
10501       // Remember that this register needs to added to the machine PHI node as
10502       // the input for this MBB.
10503       SmallVector<EVT, 4> ValueVTs;
10504       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10505       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10506       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10507         EVT VT = ValueVTs[vti];
10508         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10509         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10510           FuncInfo.PHINodesToUpdate.push_back(
10511               std::make_pair(&*MBBI++, Reg + i));
10512         Reg += NumRegisters;
10513       }
10514     }
10515   }
10516 
10517   ConstantsOut.clear();
10518 }
10519 
10520 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10521 /// is 0.
10522 MachineBasicBlock *
10523 SelectionDAGBuilder::StackProtectorDescriptor::
10524 AddSuccessorMBB(const BasicBlock *BB,
10525                 MachineBasicBlock *ParentMBB,
10526                 bool IsLikely,
10527                 MachineBasicBlock *SuccMBB) {
10528   // If SuccBB has not been created yet, create it.
10529   if (!SuccMBB) {
10530     MachineFunction *MF = ParentMBB->getParent();
10531     MachineFunction::iterator BBI(ParentMBB);
10532     SuccMBB = MF->CreateMachineBasicBlock(BB);
10533     MF->insert(++BBI, SuccMBB);
10534   }
10535   // Add it as a successor of ParentMBB.
10536   ParentMBB->addSuccessor(
10537       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10538   return SuccMBB;
10539 }
10540 
10541 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10542   MachineFunction::iterator I(MBB);
10543   if (++I == FuncInfo.MF->end())
10544     return nullptr;
10545   return &*I;
10546 }
10547 
10548 /// During lowering new call nodes can be created (such as memset, etc.).
10549 /// Those will become new roots of the current DAG, but complications arise
10550 /// when they are tail calls. In such cases, the call lowering will update
10551 /// the root, but the builder still needs to know that a tail call has been
10552 /// lowered in order to avoid generating an additional return.
10553 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10554   // If the node is null, we do have a tail call.
10555   if (MaybeTC.getNode() != nullptr)
10556     DAG.setRoot(MaybeTC);
10557   else
10558     HasTailCall = true;
10559 }
10560 
10561 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10562                                         MachineBasicBlock *SwitchMBB,
10563                                         MachineBasicBlock *DefaultMBB) {
10564   MachineFunction *CurMF = FuncInfo.MF;
10565   MachineBasicBlock *NextMBB = nullptr;
10566   MachineFunction::iterator BBI(W.MBB);
10567   if (++BBI != FuncInfo.MF->end())
10568     NextMBB = &*BBI;
10569 
10570   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10571 
10572   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10573 
10574   if (Size == 2 && W.MBB == SwitchMBB) {
10575     // If any two of the cases has the same destination, and if one value
10576     // is the same as the other, but has one bit unset that the other has set,
10577     // use bit manipulation to do two compares at once.  For example:
10578     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10579     // TODO: This could be extended to merge any 2 cases in switches with 3
10580     // cases.
10581     // TODO: Handle cases where W.CaseBB != SwitchBB.
10582     CaseCluster &Small = *W.FirstCluster;
10583     CaseCluster &Big = *W.LastCluster;
10584 
10585     if (Small.Low == Small.High && Big.Low == Big.High &&
10586         Small.MBB == Big.MBB) {
10587       const APInt &SmallValue = Small.Low->getValue();
10588       const APInt &BigValue = Big.Low->getValue();
10589 
10590       // Check that there is only one bit different.
10591       APInt CommonBit = BigValue ^ SmallValue;
10592       if (CommonBit.isPowerOf2()) {
10593         SDValue CondLHS = getValue(Cond);
10594         EVT VT = CondLHS.getValueType();
10595         SDLoc DL = getCurSDLoc();
10596 
10597         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10598                                  DAG.getConstant(CommonBit, DL, VT));
10599         SDValue Cond = DAG.getSetCC(
10600             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10601             ISD::SETEQ);
10602 
10603         // Update successor info.
10604         // Both Small and Big will jump to Small.BB, so we sum up the
10605         // probabilities.
10606         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10607         if (BPI)
10608           addSuccessorWithProb(
10609               SwitchMBB, DefaultMBB,
10610               // The default destination is the first successor in IR.
10611               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10612         else
10613           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10614 
10615         // Insert the true branch.
10616         SDValue BrCond =
10617             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10618                         DAG.getBasicBlock(Small.MBB));
10619         // Insert the false branch.
10620         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10621                              DAG.getBasicBlock(DefaultMBB));
10622 
10623         DAG.setRoot(BrCond);
10624         return;
10625       }
10626     }
10627   }
10628 
10629   if (TM.getOptLevel() != CodeGenOpt::None) {
10630     // Here, we order cases by probability so the most likely case will be
10631     // checked first. However, two clusters can have the same probability in
10632     // which case their relative ordering is non-deterministic. So we use Low
10633     // as a tie-breaker as clusters are guaranteed to never overlap.
10634     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10635                [](const CaseCluster &a, const CaseCluster &b) {
10636       return a.Prob != b.Prob ?
10637              a.Prob > b.Prob :
10638              a.Low->getValue().slt(b.Low->getValue());
10639     });
10640 
10641     // Rearrange the case blocks so that the last one falls through if possible
10642     // without changing the order of probabilities.
10643     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10644       --I;
10645       if (I->Prob > W.LastCluster->Prob)
10646         break;
10647       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10648         std::swap(*I, *W.LastCluster);
10649         break;
10650       }
10651     }
10652   }
10653 
10654   // Compute total probability.
10655   BranchProbability DefaultProb = W.DefaultProb;
10656   BranchProbability UnhandledProbs = DefaultProb;
10657   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10658     UnhandledProbs += I->Prob;
10659 
10660   MachineBasicBlock *CurMBB = W.MBB;
10661   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10662     bool FallthroughUnreachable = false;
10663     MachineBasicBlock *Fallthrough;
10664     if (I == W.LastCluster) {
10665       // For the last cluster, fall through to the default destination.
10666       Fallthrough = DefaultMBB;
10667       FallthroughUnreachable = isa<UnreachableInst>(
10668           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10669     } else {
10670       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10671       CurMF->insert(BBI, Fallthrough);
10672       // Put Cond in a virtual register to make it available from the new blocks.
10673       ExportFromCurrentBlock(Cond);
10674     }
10675     UnhandledProbs -= I->Prob;
10676 
10677     switch (I->Kind) {
10678       case CC_JumpTable: {
10679         // FIXME: Optimize away range check based on pivot comparisons.
10680         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10681         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10682 
10683         // The jump block hasn't been inserted yet; insert it here.
10684         MachineBasicBlock *JumpMBB = JT->MBB;
10685         CurMF->insert(BBI, JumpMBB);
10686 
10687         auto JumpProb = I->Prob;
10688         auto FallthroughProb = UnhandledProbs;
10689 
10690         // If the default statement is a target of the jump table, we evenly
10691         // distribute the default probability to successors of CurMBB. Also
10692         // update the probability on the edge from JumpMBB to Fallthrough.
10693         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10694                                               SE = JumpMBB->succ_end();
10695              SI != SE; ++SI) {
10696           if (*SI == DefaultMBB) {
10697             JumpProb += DefaultProb / 2;
10698             FallthroughProb -= DefaultProb / 2;
10699             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10700             JumpMBB->normalizeSuccProbs();
10701             break;
10702           }
10703         }
10704 
10705         if (FallthroughUnreachable) {
10706           // Skip the range check if the fallthrough block is unreachable.
10707           JTH->OmitRangeCheck = true;
10708         }
10709 
10710         if (!JTH->OmitRangeCheck)
10711           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10712         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10713         CurMBB->normalizeSuccProbs();
10714 
10715         // The jump table header will be inserted in our current block, do the
10716         // range check, and fall through to our fallthrough block.
10717         JTH->HeaderBB = CurMBB;
10718         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10719 
10720         // If we're in the right place, emit the jump table header right now.
10721         if (CurMBB == SwitchMBB) {
10722           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10723           JTH->Emitted = true;
10724         }
10725         break;
10726       }
10727       case CC_BitTests: {
10728         // FIXME: Optimize away range check based on pivot comparisons.
10729         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10730 
10731         // The bit test blocks haven't been inserted yet; insert them here.
10732         for (BitTestCase &BTC : BTB->Cases)
10733           CurMF->insert(BBI, BTC.ThisBB);
10734 
10735         // Fill in fields of the BitTestBlock.
10736         BTB->Parent = CurMBB;
10737         BTB->Default = Fallthrough;
10738 
10739         BTB->DefaultProb = UnhandledProbs;
10740         // If the cases in bit test don't form a contiguous range, we evenly
10741         // distribute the probability on the edge to Fallthrough to two
10742         // successors of CurMBB.
10743         if (!BTB->ContiguousRange) {
10744           BTB->Prob += DefaultProb / 2;
10745           BTB->DefaultProb -= DefaultProb / 2;
10746         }
10747 
10748         if (FallthroughUnreachable) {
10749           // Skip the range check if the fallthrough block is unreachable.
10750           BTB->OmitRangeCheck = true;
10751         }
10752 
10753         // If we're in the right place, emit the bit test header right now.
10754         if (CurMBB == SwitchMBB) {
10755           visitBitTestHeader(*BTB, SwitchMBB);
10756           BTB->Emitted = true;
10757         }
10758         break;
10759       }
10760       case CC_Range: {
10761         const Value *RHS, *LHS, *MHS;
10762         ISD::CondCode CC;
10763         if (I->Low == I->High) {
10764           // Check Cond == I->Low.
10765           CC = ISD::SETEQ;
10766           LHS = Cond;
10767           RHS=I->Low;
10768           MHS = nullptr;
10769         } else {
10770           // Check I->Low <= Cond <= I->High.
10771           CC = ISD::SETLE;
10772           LHS = I->Low;
10773           MHS = Cond;
10774           RHS = I->High;
10775         }
10776 
10777         // If Fallthrough is unreachable, fold away the comparison.
10778         if (FallthroughUnreachable)
10779           CC = ISD::SETTRUE;
10780 
10781         // The false probability is the sum of all unhandled cases.
10782         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10783                      getCurSDLoc(), I->Prob, UnhandledProbs);
10784 
10785         if (CurMBB == SwitchMBB)
10786           visitSwitchCase(CB, SwitchMBB);
10787         else
10788           SL->SwitchCases.push_back(CB);
10789 
10790         break;
10791       }
10792     }
10793     CurMBB = Fallthrough;
10794   }
10795 }
10796 
10797 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10798                                               CaseClusterIt First,
10799                                               CaseClusterIt Last) {
10800   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10801     if (X.Prob != CC.Prob)
10802       return X.Prob > CC.Prob;
10803 
10804     // Ties are broken by comparing the case value.
10805     return X.Low->getValue().slt(CC.Low->getValue());
10806   });
10807 }
10808 
10809 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10810                                         const SwitchWorkListItem &W,
10811                                         Value *Cond,
10812                                         MachineBasicBlock *SwitchMBB) {
10813   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10814          "Clusters not sorted?");
10815 
10816   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10817 
10818   // Balance the tree based on branch probabilities to create a near-optimal (in
10819   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10820   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10821   CaseClusterIt LastLeft = W.FirstCluster;
10822   CaseClusterIt FirstRight = W.LastCluster;
10823   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10824   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10825 
10826   // Move LastLeft and FirstRight towards each other from opposite directions to
10827   // find a partitioning of the clusters which balances the probability on both
10828   // sides. If LeftProb and RightProb are equal, alternate which side is
10829   // taken to ensure 0-probability nodes are distributed evenly.
10830   unsigned I = 0;
10831   while (LastLeft + 1 < FirstRight) {
10832     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10833       LeftProb += (++LastLeft)->Prob;
10834     else
10835       RightProb += (--FirstRight)->Prob;
10836     I++;
10837   }
10838 
10839   while (true) {
10840     // Our binary search tree differs from a typical BST in that ours can have up
10841     // to three values in each leaf. The pivot selection above doesn't take that
10842     // into account, which means the tree might require more nodes and be less
10843     // efficient. We compensate for this here.
10844 
10845     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10846     unsigned NumRight = W.LastCluster - FirstRight + 1;
10847 
10848     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10849       // If one side has less than 3 clusters, and the other has more than 3,
10850       // consider taking a cluster from the other side.
10851 
10852       if (NumLeft < NumRight) {
10853         // Consider moving the first cluster on the right to the left side.
10854         CaseCluster &CC = *FirstRight;
10855         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10856         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10857         if (LeftSideRank <= RightSideRank) {
10858           // Moving the cluster to the left does not demote it.
10859           ++LastLeft;
10860           ++FirstRight;
10861           continue;
10862         }
10863       } else {
10864         assert(NumRight < NumLeft);
10865         // Consider moving the last element on the left to the right side.
10866         CaseCluster &CC = *LastLeft;
10867         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10868         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10869         if (RightSideRank <= LeftSideRank) {
10870           // Moving the cluster to the right does not demot it.
10871           --LastLeft;
10872           --FirstRight;
10873           continue;
10874         }
10875       }
10876     }
10877     break;
10878   }
10879 
10880   assert(LastLeft + 1 == FirstRight);
10881   assert(LastLeft >= W.FirstCluster);
10882   assert(FirstRight <= W.LastCluster);
10883 
10884   // Use the first element on the right as pivot since we will make less-than
10885   // comparisons against it.
10886   CaseClusterIt PivotCluster = FirstRight;
10887   assert(PivotCluster > W.FirstCluster);
10888   assert(PivotCluster <= W.LastCluster);
10889 
10890   CaseClusterIt FirstLeft = W.FirstCluster;
10891   CaseClusterIt LastRight = W.LastCluster;
10892 
10893   const ConstantInt *Pivot = PivotCluster->Low;
10894 
10895   // New blocks will be inserted immediately after the current one.
10896   MachineFunction::iterator BBI(W.MBB);
10897   ++BBI;
10898 
10899   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10900   // we can branch to its destination directly if it's squeezed exactly in
10901   // between the known lower bound and Pivot - 1.
10902   MachineBasicBlock *LeftMBB;
10903   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10904       FirstLeft->Low == W.GE &&
10905       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10906     LeftMBB = FirstLeft->MBB;
10907   } else {
10908     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10909     FuncInfo.MF->insert(BBI, LeftMBB);
10910     WorkList.push_back(
10911         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10912     // Put Cond in a virtual register to make it available from the new blocks.
10913     ExportFromCurrentBlock(Cond);
10914   }
10915 
10916   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10917   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10918   // directly if RHS.High equals the current upper bound.
10919   MachineBasicBlock *RightMBB;
10920   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10921       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10922     RightMBB = FirstRight->MBB;
10923   } else {
10924     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10925     FuncInfo.MF->insert(BBI, RightMBB);
10926     WorkList.push_back(
10927         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10928     // Put Cond in a virtual register to make it available from the new blocks.
10929     ExportFromCurrentBlock(Cond);
10930   }
10931 
10932   // Create the CaseBlock record that will be used to lower the branch.
10933   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10934                getCurSDLoc(), LeftProb, RightProb);
10935 
10936   if (W.MBB == SwitchMBB)
10937     visitSwitchCase(CB, SwitchMBB);
10938   else
10939     SL->SwitchCases.push_back(CB);
10940 }
10941 
10942 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10943 // from the swith statement.
10944 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10945                                             BranchProbability PeeledCaseProb) {
10946   if (PeeledCaseProb == BranchProbability::getOne())
10947     return BranchProbability::getZero();
10948   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10949 
10950   uint32_t Numerator = CaseProb.getNumerator();
10951   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10952   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10953 }
10954 
10955 // Try to peel the top probability case if it exceeds the threshold.
10956 // Return current MachineBasicBlock for the switch statement if the peeling
10957 // does not occur.
10958 // If the peeling is performed, return the newly created MachineBasicBlock
10959 // for the peeled switch statement. Also update Clusters to remove the peeled
10960 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10961 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10962     const SwitchInst &SI, CaseClusterVector &Clusters,
10963     BranchProbability &PeeledCaseProb) {
10964   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10965   // Don't perform if there is only one cluster or optimizing for size.
10966   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10967       TM.getOptLevel() == CodeGenOpt::None ||
10968       SwitchMBB->getParent()->getFunction().hasMinSize())
10969     return SwitchMBB;
10970 
10971   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10972   unsigned PeeledCaseIndex = 0;
10973   bool SwitchPeeled = false;
10974   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10975     CaseCluster &CC = Clusters[Index];
10976     if (CC.Prob < TopCaseProb)
10977       continue;
10978     TopCaseProb = CC.Prob;
10979     PeeledCaseIndex = Index;
10980     SwitchPeeled = true;
10981   }
10982   if (!SwitchPeeled)
10983     return SwitchMBB;
10984 
10985   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10986                     << TopCaseProb << "\n");
10987 
10988   // Record the MBB for the peeled switch statement.
10989   MachineFunction::iterator BBI(SwitchMBB);
10990   ++BBI;
10991   MachineBasicBlock *PeeledSwitchMBB =
10992       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10993   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10994 
10995   ExportFromCurrentBlock(SI.getCondition());
10996   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10997   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10998                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10999   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11000 
11001   Clusters.erase(PeeledCaseIt);
11002   for (CaseCluster &CC : Clusters) {
11003     LLVM_DEBUG(
11004         dbgs() << "Scale the probablity for one cluster, before scaling: "
11005                << CC.Prob << "\n");
11006     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11007     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11008   }
11009   PeeledCaseProb = TopCaseProb;
11010   return PeeledSwitchMBB;
11011 }
11012 
11013 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11014   // Extract cases from the switch.
11015   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11016   CaseClusterVector Clusters;
11017   Clusters.reserve(SI.getNumCases());
11018   for (auto I : SI.cases()) {
11019     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11020     const ConstantInt *CaseVal = I.getCaseValue();
11021     BranchProbability Prob =
11022         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11023             : BranchProbability(1, SI.getNumCases() + 1);
11024     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11025   }
11026 
11027   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11028 
11029   // Cluster adjacent cases with the same destination. We do this at all
11030   // optimization levels because it's cheap to do and will make codegen faster
11031   // if there are many clusters.
11032   sortAndRangeify(Clusters);
11033 
11034   // The branch probablity of the peeled case.
11035   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11036   MachineBasicBlock *PeeledSwitchMBB =
11037       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11038 
11039   // If there is only the default destination, jump there directly.
11040   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11041   if (Clusters.empty()) {
11042     assert(PeeledSwitchMBB == SwitchMBB);
11043     SwitchMBB->addSuccessor(DefaultMBB);
11044     if (DefaultMBB != NextBlock(SwitchMBB)) {
11045       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11046                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11047     }
11048     return;
11049   }
11050 
11051   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11052   SL->findBitTestClusters(Clusters, &SI);
11053 
11054   LLVM_DEBUG({
11055     dbgs() << "Case clusters: ";
11056     for (const CaseCluster &C : Clusters) {
11057       if (C.Kind == CC_JumpTable)
11058         dbgs() << "JT:";
11059       if (C.Kind == CC_BitTests)
11060         dbgs() << "BT:";
11061 
11062       C.Low->getValue().print(dbgs(), true);
11063       if (C.Low != C.High) {
11064         dbgs() << '-';
11065         C.High->getValue().print(dbgs(), true);
11066       }
11067       dbgs() << ' ';
11068     }
11069     dbgs() << '\n';
11070   });
11071 
11072   assert(!Clusters.empty());
11073   SwitchWorkList WorkList;
11074   CaseClusterIt First = Clusters.begin();
11075   CaseClusterIt Last = Clusters.end() - 1;
11076   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11077   // Scale the branchprobability for DefaultMBB if the peel occurs and
11078   // DefaultMBB is not replaced.
11079   if (PeeledCaseProb != BranchProbability::getZero() &&
11080       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11081     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11082   WorkList.push_back(
11083       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11084 
11085   while (!WorkList.empty()) {
11086     SwitchWorkListItem W = WorkList.pop_back_val();
11087     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11088 
11089     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11090         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11091       // For optimized builds, lower large range as a balanced binary tree.
11092       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11093       continue;
11094     }
11095 
11096     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11097   }
11098 }
11099 
11100 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11101   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11102   auto DL = getCurSDLoc();
11103   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11104   setValue(&I, DAG.getStepVector(DL, ResultVT));
11105 }
11106 
11107 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11108   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11109   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11110 
11111   SDLoc DL = getCurSDLoc();
11112   SDValue V = getValue(I.getOperand(0));
11113   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11114 
11115   if (VT.isScalableVector()) {
11116     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11117     return;
11118   }
11119 
11120   // Use VECTOR_SHUFFLE for the fixed-length vector
11121   // to maintain existing behavior.
11122   SmallVector<int, 8> Mask;
11123   unsigned NumElts = VT.getVectorMinNumElements();
11124   for (unsigned i = 0; i != NumElts; ++i)
11125     Mask.push_back(NumElts - 1 - i);
11126 
11127   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11128 }
11129 
11130 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11131   SmallVector<EVT, 4> ValueVTs;
11132   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11133                   ValueVTs);
11134   unsigned NumValues = ValueVTs.size();
11135   if (NumValues == 0) return;
11136 
11137   SmallVector<SDValue, 4> Values(NumValues);
11138   SDValue Op = getValue(I.getOperand(0));
11139 
11140   for (unsigned i = 0; i != NumValues; ++i)
11141     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11142                             SDValue(Op.getNode(), Op.getResNo() + i));
11143 
11144   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11145                            DAG.getVTList(ValueVTs), Values));
11146 }
11147 
11148 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11150   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11151 
11152   SDLoc DL = getCurSDLoc();
11153   SDValue V1 = getValue(I.getOperand(0));
11154   SDValue V2 = getValue(I.getOperand(1));
11155   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11156 
11157   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11158   if (VT.isScalableVector()) {
11159     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11160     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11161                              DAG.getConstant(Imm, DL, IdxVT)));
11162     return;
11163   }
11164 
11165   unsigned NumElts = VT.getVectorNumElements();
11166 
11167   if ((-Imm > NumElts) || (Imm >= NumElts)) {
11168     // Result is undefined if immediate is out-of-bounds.
11169     setValue(&I, DAG.getUNDEF(VT));
11170     return;
11171   }
11172 
11173   uint64_t Idx = (NumElts + Imm) % NumElts;
11174 
11175   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11176   SmallVector<int, 8> Mask;
11177   for (unsigned i = 0; i < NumElts; ++i)
11178     Mask.push_back(Idx + i);
11179   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11180 }
11181