xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 4c4093e6e39fe6601f9c95a95a6bc242ef648cd5)
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<Value *, 4> AdditionalValues;
1285     DIExpression *SalvagedExpr =
1286         salvageDebugInfoImpl(VAsInst, Expr, StackValue, 0, AdditionalValues);
1287 
1288     // If we cannot salvage any further, and haven't yet found a suitable debug
1289     // expression, bail out.
1290     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1291     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1292     // here for variadic dbg_values, remove that condition.
1293     if (!SalvagedExpr || !AdditionalValues.empty())
1294       break;
1295 
1296     // New value and expr now represent this debuginfo.
1297     V = VAsInst.getOperand(0);
1298     Expr = SalvagedExpr;
1299 
1300     // Some kind of simplification occurred: check whether the operand of the
1301     // salvaged debug expression can be encoded in this DAG.
1302     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1303                          /*IsVariadic=*/false)) {
1304       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1305                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1306       return;
1307     }
1308   }
1309 
1310   // This was the final opportunity to salvage this debug information, and it
1311   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1312   // any earlier variable location.
1313   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1314   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1315   DAG.AddDbgValue(SDV, false);
1316 
1317   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1318                     << "\n");
1319   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1320                     << "\n");
1321 }
1322 
1323 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1324                                            DILocalVariable *Var,
1325                                            DIExpression *Expr, DebugLoc dl,
1326                                            DebugLoc InstDL, unsigned Order,
1327                                            bool IsVariadic) {
1328   if (Values.empty())
1329     return true;
1330   SmallVector<SDDbgOperand> LocationOps;
1331   SmallVector<SDNode *> Dependencies;
1332   for (const Value *V : Values) {
1333     // Constant value.
1334     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1335         isa<ConstantPointerNull>(V)) {
1336       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1337       continue;
1338     }
1339 
1340     // If the Value is a frame index, we can create a FrameIndex debug value
1341     // without relying on the DAG at all.
1342     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1343       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1344       if (SI != FuncInfo.StaticAllocaMap.end()) {
1345         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1346         continue;
1347       }
1348     }
1349 
1350     // Do not use getValue() in here; we don't want to generate code at
1351     // this point if it hasn't been done yet.
1352     SDValue N = NodeMap[V];
1353     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1354       N = UnusedArgNodeMap[V];
1355     if (N.getNode()) {
1356       // Only emit func arg dbg value for non-variadic dbg.values for now.
1357       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1358         return true;
1359       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1360         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1361         // describe stack slot locations.
1362         //
1363         // Consider "int x = 0; int *px = &x;". There are two kinds of
1364         // interesting debug values here after optimization:
1365         //
1366         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1367         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1368         //
1369         // Both describe the direct values of their associated variables.
1370         Dependencies.push_back(N.getNode());
1371         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1372         continue;
1373       }
1374       LocationOps.emplace_back(
1375           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1376       continue;
1377     }
1378 
1379     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1380     // Special rules apply for the first dbg.values of parameter variables in a
1381     // function. Identify them by the fact they reference Argument Values, that
1382     // they're parameters, and they are parameters of the current function. We
1383     // need to let them dangle until they get an SDNode.
1384     bool IsParamOfFunc =
1385         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1386     if (IsParamOfFunc)
1387       return false;
1388 
1389     // The value is not used in this block yet (or it would have an SDNode).
1390     // We still want the value to appear for the user if possible -- if it has
1391     // an associated VReg, we can refer to that instead.
1392     auto VMI = FuncInfo.ValueMap.find(V);
1393     if (VMI != FuncInfo.ValueMap.end()) {
1394       unsigned Reg = VMI->second;
1395       // If this is a PHI node, it may be split up into several MI PHI nodes
1396       // (in FunctionLoweringInfo::set).
1397       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1398                        V->getType(), None);
1399       if (RFV.occupiesMultipleRegs()) {
1400         // FIXME: We could potentially support variadic dbg_values here.
1401         if (IsVariadic)
1402           return false;
1403         unsigned Offset = 0;
1404         unsigned BitsToDescribe = 0;
1405         if (auto VarSize = Var->getSizeInBits())
1406           BitsToDescribe = *VarSize;
1407         if (auto Fragment = Expr->getFragmentInfo())
1408           BitsToDescribe = Fragment->SizeInBits;
1409         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1410           // Bail out if all bits are described already.
1411           if (Offset >= BitsToDescribe)
1412             break;
1413           // TODO: handle scalable vectors.
1414           unsigned RegisterSize = RegAndSize.second;
1415           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1416                                       ? BitsToDescribe - Offset
1417                                       : RegisterSize;
1418           auto FragmentExpr = DIExpression::createFragmentExpression(
1419               Expr, Offset, FragmentSize);
1420           if (!FragmentExpr)
1421             continue;
1422           SDDbgValue *SDV = DAG.getVRegDbgValue(
1423               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1424           DAG.AddDbgValue(SDV, false);
1425           Offset += RegisterSize;
1426         }
1427         return true;
1428       }
1429       // We can use simple vreg locations for variadic dbg_values as well.
1430       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1431       continue;
1432     }
1433     // We failed to create a SDDbgOperand for V.
1434     return false;
1435   }
1436 
1437   // We have created a SDDbgOperand for each Value in Values.
1438   // Should use Order instead of SDNodeOrder?
1439   assert(!LocationOps.empty());
1440   SDDbgValue *SDV =
1441       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1442                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1443   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1444   return true;
1445 }
1446 
1447 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1448   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1449   for (auto &Pair : DanglingDebugInfoMap)
1450     for (auto &DDI : Pair.second)
1451       salvageUnresolvedDbgValue(DDI);
1452   clearDanglingDebugInfo();
1453 }
1454 
1455 /// getCopyFromRegs - If there was virtual register allocated for the value V
1456 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1457 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1458   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1459   SDValue Result;
1460 
1461   if (It != FuncInfo.ValueMap.end()) {
1462     Register InReg = It->second;
1463 
1464     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1465                      DAG.getDataLayout(), InReg, Ty,
1466                      None); // This is not an ABI copy.
1467     SDValue Chain = DAG.getEntryNode();
1468     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1469                                  V);
1470     resolveDanglingDebugInfo(V, Result);
1471   }
1472 
1473   return Result;
1474 }
1475 
1476 /// getValue - Return an SDValue for the given Value.
1477 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1478   // If we already have an SDValue for this value, use it. It's important
1479   // to do this first, so that we don't create a CopyFromReg if we already
1480   // have a regular SDValue.
1481   SDValue &N = NodeMap[V];
1482   if (N.getNode()) return N;
1483 
1484   // If there's a virtual register allocated and initialized for this
1485   // value, use it.
1486   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1487     return copyFromReg;
1488 
1489   // Otherwise create a new SDValue and remember it.
1490   SDValue Val = getValueImpl(V);
1491   NodeMap[V] = Val;
1492   resolveDanglingDebugInfo(V, Val);
1493   return Val;
1494 }
1495 
1496 /// getNonRegisterValue - Return an SDValue for the given Value, but
1497 /// don't look in FuncInfo.ValueMap for a virtual register.
1498 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1499   // If we already have an SDValue for this value, use it.
1500   SDValue &N = NodeMap[V];
1501   if (N.getNode()) {
1502     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1503       // Remove the debug location from the node as the node is about to be used
1504       // in a location which may differ from the original debug location.  This
1505       // is relevant to Constant and ConstantFP nodes because they can appear
1506       // as constant expressions inside PHI nodes.
1507       N->setDebugLoc(DebugLoc());
1508     }
1509     return N;
1510   }
1511 
1512   // Otherwise create a new SDValue and remember it.
1513   SDValue Val = getValueImpl(V);
1514   NodeMap[V] = Val;
1515   resolveDanglingDebugInfo(V, Val);
1516   return Val;
1517 }
1518 
1519 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1520 /// Create an SDValue for the given value.
1521 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1522   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1523 
1524   if (const Constant *C = dyn_cast<Constant>(V)) {
1525     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1526 
1527     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1528       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1529 
1530     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1531       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1532 
1533     if (isa<ConstantPointerNull>(C)) {
1534       unsigned AS = V->getType()->getPointerAddressSpace();
1535       return DAG.getConstant(0, getCurSDLoc(),
1536                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1537     }
1538 
1539     if (match(C, m_VScale(DAG.getDataLayout())))
1540       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1541 
1542     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1543       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1544 
1545     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1546       return DAG.getUNDEF(VT);
1547 
1548     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1549       visit(CE->getOpcode(), *CE);
1550       SDValue N1 = NodeMap[V];
1551       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1552       return N1;
1553     }
1554 
1555     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1556       SmallVector<SDValue, 4> Constants;
1557       for (const Use &U : C->operands()) {
1558         SDNode *Val = getValue(U).getNode();
1559         // If the operand is an empty aggregate, there are no values.
1560         if (!Val) continue;
1561         // Add each leaf value from the operand to the Constants list
1562         // to form a flattened list of all the values.
1563         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1564           Constants.push_back(SDValue(Val, i));
1565       }
1566 
1567       return DAG.getMergeValues(Constants, getCurSDLoc());
1568     }
1569 
1570     if (const ConstantDataSequential *CDS =
1571           dyn_cast<ConstantDataSequential>(C)) {
1572       SmallVector<SDValue, 4> Ops;
1573       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1574         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1575         // Add each leaf value from the operand to the Constants list
1576         // to form a flattened list of all the values.
1577         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1578           Ops.push_back(SDValue(Val, i));
1579       }
1580 
1581       if (isa<ArrayType>(CDS->getType()))
1582         return DAG.getMergeValues(Ops, getCurSDLoc());
1583       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1584     }
1585 
1586     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1587       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1588              "Unknown struct or array constant!");
1589 
1590       SmallVector<EVT, 4> ValueVTs;
1591       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1592       unsigned NumElts = ValueVTs.size();
1593       if (NumElts == 0)
1594         return SDValue(); // empty struct
1595       SmallVector<SDValue, 4> Constants(NumElts);
1596       for (unsigned i = 0; i != NumElts; ++i) {
1597         EVT EltVT = ValueVTs[i];
1598         if (isa<UndefValue>(C))
1599           Constants[i] = DAG.getUNDEF(EltVT);
1600         else if (EltVT.isFloatingPoint())
1601           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1602         else
1603           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1604       }
1605 
1606       return DAG.getMergeValues(Constants, getCurSDLoc());
1607     }
1608 
1609     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1610       return DAG.getBlockAddress(BA, VT);
1611 
1612     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1613       return getValue(Equiv->getGlobalValue());
1614 
1615     VectorType *VecTy = cast<VectorType>(V->getType());
1616 
1617     // Now that we know the number and type of the elements, get that number of
1618     // elements into the Ops array based on what kind of constant it is.
1619     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1620       SmallVector<SDValue, 16> Ops;
1621       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1622       for (unsigned i = 0; i != NumElements; ++i)
1623         Ops.push_back(getValue(CV->getOperand(i)));
1624 
1625       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1626     } else if (isa<ConstantAggregateZero>(C)) {
1627       EVT EltVT =
1628           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1629 
1630       SDValue Op;
1631       if (EltVT.isFloatingPoint())
1632         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1633       else
1634         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1635 
1636       if (isa<ScalableVectorType>(VecTy))
1637         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1638       else {
1639         SmallVector<SDValue, 16> Ops;
1640         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1641         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1642       }
1643     }
1644     llvm_unreachable("Unknown vector constant");
1645   }
1646 
1647   // If this is a static alloca, generate it as the frameindex instead of
1648   // computation.
1649   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1650     DenseMap<const AllocaInst*, int>::iterator SI =
1651       FuncInfo.StaticAllocaMap.find(AI);
1652     if (SI != FuncInfo.StaticAllocaMap.end())
1653       return DAG.getFrameIndex(SI->second,
1654                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1655   }
1656 
1657   // If this is an instruction which fast-isel has deferred, select it now.
1658   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1659     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1660 
1661     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1662                      Inst->getType(), None);
1663     SDValue Chain = DAG.getEntryNode();
1664     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1665   }
1666 
1667   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1668     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1669   }
1670   llvm_unreachable("Can't get register for value!");
1671 }
1672 
1673 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1674   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1675   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1676   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1677   bool IsSEH = isAsynchronousEHPersonality(Pers);
1678   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1679   if (!IsSEH)
1680     CatchPadMBB->setIsEHScopeEntry();
1681   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1682   if (IsMSVCCXX || IsCoreCLR)
1683     CatchPadMBB->setIsEHFuncletEntry();
1684 }
1685 
1686 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1687   // Update machine-CFG edge.
1688   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1689   FuncInfo.MBB->addSuccessor(TargetMBB);
1690   TargetMBB->setIsEHCatchretTarget(true);
1691   DAG.getMachineFunction().setHasEHCatchret(true);
1692 
1693   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1694   bool IsSEH = isAsynchronousEHPersonality(Pers);
1695   if (IsSEH) {
1696     // If this is not a fall-through branch or optimizations are switched off,
1697     // emit the branch.
1698     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1699         TM.getOptLevel() == CodeGenOpt::None)
1700       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1701                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1702     return;
1703   }
1704 
1705   // Figure out the funclet membership for the catchret's successor.
1706   // This will be used by the FuncletLayout pass to determine how to order the
1707   // BB's.
1708   // A 'catchret' returns to the outer scope's color.
1709   Value *ParentPad = I.getCatchSwitchParentPad();
1710   const BasicBlock *SuccessorColor;
1711   if (isa<ConstantTokenNone>(ParentPad))
1712     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1713   else
1714     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1715   assert(SuccessorColor && "No parent funclet for catchret!");
1716   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1717   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1718 
1719   // Create the terminator node.
1720   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1721                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1722                             DAG.getBasicBlock(SuccessorColorMBB));
1723   DAG.setRoot(Ret);
1724 }
1725 
1726 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1727   // Don't emit any special code for the cleanuppad instruction. It just marks
1728   // the start of an EH scope/funclet.
1729   FuncInfo.MBB->setIsEHScopeEntry();
1730   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1731   if (Pers != EHPersonality::Wasm_CXX) {
1732     FuncInfo.MBB->setIsEHFuncletEntry();
1733     FuncInfo.MBB->setIsCleanupFuncletEntry();
1734   }
1735 }
1736 
1737 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1738 // not match, it is OK to add only the first unwind destination catchpad to the
1739 // successors, because there will be at least one invoke instruction within the
1740 // catch scope that points to the next unwind destination, if one exists, so
1741 // CFGSort cannot mess up with BB sorting order.
1742 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1743 // call within them, and catchpads only consisting of 'catch (...)' have a
1744 // '__cxa_end_catch' call within them, both of which generate invokes in case
1745 // the next unwind destination exists, i.e., the next unwind destination is not
1746 // the caller.)
1747 //
1748 // Having at most one EH pad successor is also simpler and helps later
1749 // transformations.
1750 //
1751 // For example,
1752 // current:
1753 //   invoke void @foo to ... unwind label %catch.dispatch
1754 // catch.dispatch:
1755 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1756 // catch.start:
1757 //   ...
1758 //   ... in this BB or some other child BB dominated by this BB there will be an
1759 //   invoke that points to 'next' BB as an unwind destination
1760 //
1761 // next: ; We don't need to add this to 'current' BB's successor
1762 //   ...
1763 static void findWasmUnwindDestinations(
1764     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1765     BranchProbability Prob,
1766     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1767         &UnwindDests) {
1768   while (EHPadBB) {
1769     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1770     if (isa<CleanupPadInst>(Pad)) {
1771       // Stop on cleanup pads.
1772       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1773       UnwindDests.back().first->setIsEHScopeEntry();
1774       break;
1775     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1776       // Add the catchpad handlers to the possible destinations. We don't
1777       // continue to the unwind destination of the catchswitch for wasm.
1778       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1779         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1780         UnwindDests.back().first->setIsEHScopeEntry();
1781       }
1782       break;
1783     } else {
1784       continue;
1785     }
1786   }
1787 }
1788 
1789 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1790 /// many places it could ultimately go. In the IR, we have a single unwind
1791 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1792 /// This function skips over imaginary basic blocks that hold catchswitch
1793 /// instructions, and finds all the "real" machine
1794 /// basic block destinations. As those destinations may not be successors of
1795 /// EHPadBB, here we also calculate the edge probability to those destinations.
1796 /// The passed-in Prob is the edge probability to EHPadBB.
1797 static void findUnwindDestinations(
1798     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1799     BranchProbability Prob,
1800     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1801         &UnwindDests) {
1802   EHPersonality Personality =
1803     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1804   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1805   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1806   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1807   bool IsSEH = isAsynchronousEHPersonality(Personality);
1808 
1809   if (IsWasmCXX) {
1810     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1811     assert(UnwindDests.size() <= 1 &&
1812            "There should be at most one unwind destination for wasm");
1813     return;
1814   }
1815 
1816   while (EHPadBB) {
1817     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1818     BasicBlock *NewEHPadBB = nullptr;
1819     if (isa<LandingPadInst>(Pad)) {
1820       // Stop on landingpads. They are not funclets.
1821       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1822       break;
1823     } else if (isa<CleanupPadInst>(Pad)) {
1824       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1825       // personalities.
1826       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1827       UnwindDests.back().first->setIsEHScopeEntry();
1828       UnwindDests.back().first->setIsEHFuncletEntry();
1829       break;
1830     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1831       // Add the catchpad handlers to the possible destinations.
1832       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1833         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1834         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1835         if (IsMSVCCXX || IsCoreCLR)
1836           UnwindDests.back().first->setIsEHFuncletEntry();
1837         if (!IsSEH)
1838           UnwindDests.back().first->setIsEHScopeEntry();
1839       }
1840       NewEHPadBB = CatchSwitch->getUnwindDest();
1841     } else {
1842       continue;
1843     }
1844 
1845     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1846     if (BPI && NewEHPadBB)
1847       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1848     EHPadBB = NewEHPadBB;
1849   }
1850 }
1851 
1852 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1853   // Update successor info.
1854   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1855   auto UnwindDest = I.getUnwindDest();
1856   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1857   BranchProbability UnwindDestProb =
1858       (BPI && UnwindDest)
1859           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1860           : BranchProbability::getZero();
1861   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1862   for (auto &UnwindDest : UnwindDests) {
1863     UnwindDest.first->setIsEHPad();
1864     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1865   }
1866   FuncInfo.MBB->normalizeSuccProbs();
1867 
1868   // Create the terminator node.
1869   SDValue Ret =
1870       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1871   DAG.setRoot(Ret);
1872 }
1873 
1874 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1875   report_fatal_error("visitCatchSwitch not yet implemented!");
1876 }
1877 
1878 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1880   auto &DL = DAG.getDataLayout();
1881   SDValue Chain = getControlRoot();
1882   SmallVector<ISD::OutputArg, 8> Outs;
1883   SmallVector<SDValue, 8> OutVals;
1884 
1885   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1886   // lower
1887   //
1888   //   %val = call <ty> @llvm.experimental.deoptimize()
1889   //   ret <ty> %val
1890   //
1891   // differently.
1892   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1893     LowerDeoptimizingReturn();
1894     return;
1895   }
1896 
1897   if (!FuncInfo.CanLowerReturn) {
1898     unsigned DemoteReg = FuncInfo.DemoteRegister;
1899     const Function *F = I.getParent()->getParent();
1900 
1901     // Emit a store of the return value through the virtual register.
1902     // Leave Outs empty so that LowerReturn won't try to load return
1903     // registers the usual way.
1904     SmallVector<EVT, 1> PtrValueVTs;
1905     ComputeValueVTs(TLI, DL,
1906                     F->getReturnType()->getPointerTo(
1907                         DAG.getDataLayout().getAllocaAddrSpace()),
1908                     PtrValueVTs);
1909 
1910     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1911                                         DemoteReg, PtrValueVTs[0]);
1912     SDValue RetOp = getValue(I.getOperand(0));
1913 
1914     SmallVector<EVT, 4> ValueVTs, MemVTs;
1915     SmallVector<uint64_t, 4> Offsets;
1916     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1917                     &Offsets);
1918     unsigned NumValues = ValueVTs.size();
1919 
1920     SmallVector<SDValue, 4> Chains(NumValues);
1921     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1922     for (unsigned i = 0; i != NumValues; ++i) {
1923       // An aggregate return value cannot wrap around the address space, so
1924       // offsets to its parts don't wrap either.
1925       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1926                                            TypeSize::Fixed(Offsets[i]));
1927 
1928       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1929       if (MemVTs[i] != ValueVTs[i])
1930         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1931       Chains[i] = DAG.getStore(
1932           Chain, getCurSDLoc(), Val,
1933           // FIXME: better loc info would be nice.
1934           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1935           commonAlignment(BaseAlign, Offsets[i]));
1936     }
1937 
1938     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1939                         MVT::Other, Chains);
1940   } else if (I.getNumOperands() != 0) {
1941     SmallVector<EVT, 4> ValueVTs;
1942     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1943     unsigned NumValues = ValueVTs.size();
1944     if (NumValues) {
1945       SDValue RetOp = getValue(I.getOperand(0));
1946 
1947       const Function *F = I.getParent()->getParent();
1948 
1949       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1950           I.getOperand(0)->getType(), F->getCallingConv(),
1951           /*IsVarArg*/ false, DL);
1952 
1953       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1954       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1955                                           Attribute::SExt))
1956         ExtendKind = ISD::SIGN_EXTEND;
1957       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1958                                                Attribute::ZExt))
1959         ExtendKind = ISD::ZERO_EXTEND;
1960 
1961       LLVMContext &Context = F->getContext();
1962       bool RetInReg = F->getAttributes().hasAttribute(
1963           AttributeList::ReturnIndex, Attribute::InReg);
1964 
1965       for (unsigned j = 0; j != NumValues; ++j) {
1966         EVT VT = ValueVTs[j];
1967 
1968         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1969           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1970 
1971         CallingConv::ID CC = F->getCallingConv();
1972 
1973         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1974         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1975         SmallVector<SDValue, 4> Parts(NumParts);
1976         getCopyToParts(DAG, getCurSDLoc(),
1977                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1978                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1979 
1980         // 'inreg' on function refers to return value
1981         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1982         if (RetInReg)
1983           Flags.setInReg();
1984 
1985         if (I.getOperand(0)->getType()->isPointerTy()) {
1986           Flags.setPointer();
1987           Flags.setPointerAddrSpace(
1988               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1989         }
1990 
1991         if (NeedsRegBlock) {
1992           Flags.setInConsecutiveRegs();
1993           if (j == NumValues - 1)
1994             Flags.setInConsecutiveRegsLast();
1995         }
1996 
1997         // Propagate extension type if any
1998         if (ExtendKind == ISD::SIGN_EXTEND)
1999           Flags.setSExt();
2000         else if (ExtendKind == ISD::ZERO_EXTEND)
2001           Flags.setZExt();
2002 
2003         for (unsigned i = 0; i < NumParts; ++i) {
2004           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
2005                                         VT, /*isfixed=*/true, 0, 0));
2006           OutVals.push_back(Parts[i]);
2007         }
2008       }
2009     }
2010   }
2011 
2012   // Push in swifterror virtual register as the last element of Outs. This makes
2013   // sure swifterror virtual register will be returned in the swifterror
2014   // physical register.
2015   const Function *F = I.getParent()->getParent();
2016   if (TLI.supportSwiftError() &&
2017       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2018     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2019     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2020     Flags.setSwiftError();
2021     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
2022                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
2023                                   true /*isfixed*/, 1 /*origidx*/,
2024                                   0 /*partOffs*/));
2025     // Create SDNode for the swifterror virtual register.
2026     OutVals.push_back(
2027         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2028                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2029                         EVT(TLI.getPointerTy(DL))));
2030   }
2031 
2032   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2033   CallingConv::ID CallConv =
2034     DAG.getMachineFunction().getFunction().getCallingConv();
2035   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2036       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2037 
2038   // Verify that the target's LowerReturn behaved as expected.
2039   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2040          "LowerReturn didn't return a valid chain!");
2041 
2042   // Update the DAG with the new chain value resulting from return lowering.
2043   DAG.setRoot(Chain);
2044 }
2045 
2046 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2047 /// created for it, emit nodes to copy the value into the virtual
2048 /// registers.
2049 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2050   // Skip empty types
2051   if (V->getType()->isEmptyTy())
2052     return;
2053 
2054   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2055   if (VMI != FuncInfo.ValueMap.end()) {
2056     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2057     CopyValueToVirtualRegister(V, VMI->second);
2058   }
2059 }
2060 
2061 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2062 /// the current basic block, add it to ValueMap now so that we'll get a
2063 /// CopyTo/FromReg.
2064 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2065   // No need to export constants.
2066   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2067 
2068   // Already exported?
2069   if (FuncInfo.isExportedInst(V)) return;
2070 
2071   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2072   CopyValueToVirtualRegister(V, Reg);
2073 }
2074 
2075 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2076                                                      const BasicBlock *FromBB) {
2077   // The operands of the setcc have to be in this block.  We don't know
2078   // how to export them from some other block.
2079   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2080     // Can export from current BB.
2081     if (VI->getParent() == FromBB)
2082       return true;
2083 
2084     // Is already exported, noop.
2085     return FuncInfo.isExportedInst(V);
2086   }
2087 
2088   // If this is an argument, we can export it if the BB is the entry block or
2089   // if it is already exported.
2090   if (isa<Argument>(V)) {
2091     if (FromBB->isEntryBlock())
2092       return true;
2093 
2094     // Otherwise, can only export this if it is already exported.
2095     return FuncInfo.isExportedInst(V);
2096   }
2097 
2098   // Otherwise, constants can always be exported.
2099   return true;
2100 }
2101 
2102 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2103 BranchProbability
2104 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2105                                         const MachineBasicBlock *Dst) const {
2106   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2107   const BasicBlock *SrcBB = Src->getBasicBlock();
2108   const BasicBlock *DstBB = Dst->getBasicBlock();
2109   if (!BPI) {
2110     // If BPI is not available, set the default probability as 1 / N, where N is
2111     // the number of successors.
2112     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2113     return BranchProbability(1, SuccSize);
2114   }
2115   return BPI->getEdgeProbability(SrcBB, DstBB);
2116 }
2117 
2118 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2119                                                MachineBasicBlock *Dst,
2120                                                BranchProbability Prob) {
2121   if (!FuncInfo.BPI)
2122     Src->addSuccessorWithoutProb(Dst);
2123   else {
2124     if (Prob.isUnknown())
2125       Prob = getEdgeProbability(Src, Dst);
2126     Src->addSuccessor(Dst, Prob);
2127   }
2128 }
2129 
2130 static bool InBlock(const Value *V, const BasicBlock *BB) {
2131   if (const Instruction *I = dyn_cast<Instruction>(V))
2132     return I->getParent() == BB;
2133   return true;
2134 }
2135 
2136 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2137 /// This function emits a branch and is used at the leaves of an OR or an
2138 /// AND operator tree.
2139 void
2140 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2141                                                   MachineBasicBlock *TBB,
2142                                                   MachineBasicBlock *FBB,
2143                                                   MachineBasicBlock *CurBB,
2144                                                   MachineBasicBlock *SwitchBB,
2145                                                   BranchProbability TProb,
2146                                                   BranchProbability FProb,
2147                                                   bool InvertCond) {
2148   const BasicBlock *BB = CurBB->getBasicBlock();
2149 
2150   // If the leaf of the tree is a comparison, merge the condition into
2151   // the caseblock.
2152   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2153     // The operands of the cmp have to be in this block.  We don't know
2154     // how to export them from some other block.  If this is the first block
2155     // of the sequence, no exporting is needed.
2156     if (CurBB == SwitchBB ||
2157         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2158          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2159       ISD::CondCode Condition;
2160       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2161         ICmpInst::Predicate Pred =
2162             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2163         Condition = getICmpCondCode(Pred);
2164       } else {
2165         const FCmpInst *FC = cast<FCmpInst>(Cond);
2166         FCmpInst::Predicate Pred =
2167             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2168         Condition = getFCmpCondCode(Pred);
2169         if (TM.Options.NoNaNsFPMath)
2170           Condition = getFCmpCodeWithoutNaN(Condition);
2171       }
2172 
2173       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2174                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2175       SL->SwitchCases.push_back(CB);
2176       return;
2177     }
2178   }
2179 
2180   // Create a CaseBlock record representing this branch.
2181   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2182   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2183                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2184   SL->SwitchCases.push_back(CB);
2185 }
2186 
2187 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2188                                                MachineBasicBlock *TBB,
2189                                                MachineBasicBlock *FBB,
2190                                                MachineBasicBlock *CurBB,
2191                                                MachineBasicBlock *SwitchBB,
2192                                                Instruction::BinaryOps Opc,
2193                                                BranchProbability TProb,
2194                                                BranchProbability FProb,
2195                                                bool InvertCond) {
2196   // Skip over not part of the tree and remember to invert op and operands at
2197   // next level.
2198   Value *NotCond;
2199   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2200       InBlock(NotCond, CurBB->getBasicBlock())) {
2201     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2202                          !InvertCond);
2203     return;
2204   }
2205 
2206   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2207   const Value *BOpOp0, *BOpOp1;
2208   // Compute the effective opcode for Cond, taking into account whether it needs
2209   // to be inverted, e.g.
2210   //   and (not (or A, B)), C
2211   // gets lowered as
2212   //   and (and (not A, not B), C)
2213   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2214   if (BOp) {
2215     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2216                ? Instruction::And
2217                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2218                       ? Instruction::Or
2219                       : (Instruction::BinaryOps)0);
2220     if (InvertCond) {
2221       if (BOpc == Instruction::And)
2222         BOpc = Instruction::Or;
2223       else if (BOpc == Instruction::Or)
2224         BOpc = Instruction::And;
2225     }
2226   }
2227 
2228   // If this node is not part of the or/and tree, emit it as a branch.
2229   // Note that all nodes in the tree should have same opcode.
2230   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2231   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2232       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2233       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2234     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2235                                  TProb, FProb, InvertCond);
2236     return;
2237   }
2238 
2239   //  Create TmpBB after CurBB.
2240   MachineFunction::iterator BBI(CurBB);
2241   MachineFunction &MF = DAG.getMachineFunction();
2242   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2243   CurBB->getParent()->insert(++BBI, TmpBB);
2244 
2245   if (Opc == Instruction::Or) {
2246     // Codegen X | Y as:
2247     // BB1:
2248     //   jmp_if_X TBB
2249     //   jmp TmpBB
2250     // TmpBB:
2251     //   jmp_if_Y TBB
2252     //   jmp FBB
2253     //
2254 
2255     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2256     // The requirement is that
2257     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2258     //     = TrueProb for original BB.
2259     // Assuming the original probabilities are A and B, one choice is to set
2260     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2261     // A/(1+B) and 2B/(1+B). This choice assumes that
2262     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2263     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2264     // TmpBB, but the math is more complicated.
2265 
2266     auto NewTrueProb = TProb / 2;
2267     auto NewFalseProb = TProb / 2 + FProb;
2268     // Emit the LHS condition.
2269     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2270                          NewFalseProb, InvertCond);
2271 
2272     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2273     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2274     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2275     // Emit the RHS condition into TmpBB.
2276     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2277                          Probs[1], InvertCond);
2278   } else {
2279     assert(Opc == Instruction::And && "Unknown merge op!");
2280     // Codegen X & Y as:
2281     // BB1:
2282     //   jmp_if_X TmpBB
2283     //   jmp FBB
2284     // TmpBB:
2285     //   jmp_if_Y TBB
2286     //   jmp FBB
2287     //
2288     //  This requires creation of TmpBB after CurBB.
2289 
2290     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2291     // The requirement is that
2292     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2293     //     = FalseProb for original BB.
2294     // Assuming the original probabilities are A and B, one choice is to set
2295     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2296     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2297     // TrueProb for BB1 * FalseProb for TmpBB.
2298 
2299     auto NewTrueProb = TProb + FProb / 2;
2300     auto NewFalseProb = FProb / 2;
2301     // Emit the LHS condition.
2302     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2303                          NewFalseProb, InvertCond);
2304 
2305     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2306     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2307     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2308     // Emit the RHS condition into TmpBB.
2309     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2310                          Probs[1], InvertCond);
2311   }
2312 }
2313 
2314 /// If the set of cases should be emitted as a series of branches, return true.
2315 /// If we should emit this as a bunch of and/or'd together conditions, return
2316 /// false.
2317 bool
2318 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2319   if (Cases.size() != 2) return true;
2320 
2321   // If this is two comparisons of the same values or'd or and'd together, they
2322   // will get folded into a single comparison, so don't emit two blocks.
2323   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2324        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2325       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2326        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2327     return false;
2328   }
2329 
2330   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2331   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2332   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2333       Cases[0].CC == Cases[1].CC &&
2334       isa<Constant>(Cases[0].CmpRHS) &&
2335       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2336     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2337       return false;
2338     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2339       return false;
2340   }
2341 
2342   return true;
2343 }
2344 
2345 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2346   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2347 
2348   // Update machine-CFG edges.
2349   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2350 
2351   if (I.isUnconditional()) {
2352     // Update machine-CFG edges.
2353     BrMBB->addSuccessor(Succ0MBB);
2354 
2355     // If this is not a fall-through branch or optimizations are switched off,
2356     // emit the branch.
2357     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2358       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2359                               MVT::Other, getControlRoot(),
2360                               DAG.getBasicBlock(Succ0MBB)));
2361 
2362     return;
2363   }
2364 
2365   // If this condition is one of the special cases we handle, do special stuff
2366   // now.
2367   const Value *CondVal = I.getCondition();
2368   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2369 
2370   // If this is a series of conditions that are or'd or and'd together, emit
2371   // this as a sequence of branches instead of setcc's with and/or operations.
2372   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2373   // unpredictable branches, and vector extracts because those jumps are likely
2374   // expensive for any target), this should improve performance.
2375   // For example, instead of something like:
2376   //     cmp A, B
2377   //     C = seteq
2378   //     cmp D, E
2379   //     F = setle
2380   //     or C, F
2381   //     jnz foo
2382   // Emit:
2383   //     cmp A, B
2384   //     je foo
2385   //     cmp D, E
2386   //     jle foo
2387   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2388   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2389       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2390     Value *Vec;
2391     const Value *BOp0, *BOp1;
2392     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2393     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2394       Opcode = Instruction::And;
2395     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2396       Opcode = Instruction::Or;
2397 
2398     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2399                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2400       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2401                            getEdgeProbability(BrMBB, Succ0MBB),
2402                            getEdgeProbability(BrMBB, Succ1MBB),
2403                            /*InvertCond=*/false);
2404       // If the compares in later blocks need to use values not currently
2405       // exported from this block, export them now.  This block should always
2406       // be the first entry.
2407       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2408 
2409       // Allow some cases to be rejected.
2410       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2411         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2412           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2413           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2414         }
2415 
2416         // Emit the branch for this block.
2417         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2418         SL->SwitchCases.erase(SL->SwitchCases.begin());
2419         return;
2420       }
2421 
2422       // Okay, we decided not to do this, remove any inserted MBB's and clear
2423       // SwitchCases.
2424       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2425         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2426 
2427       SL->SwitchCases.clear();
2428     }
2429   }
2430 
2431   // Create a CaseBlock record representing this branch.
2432   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2433                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2434 
2435   // Use visitSwitchCase to actually insert the fast branch sequence for this
2436   // cond branch.
2437   visitSwitchCase(CB, BrMBB);
2438 }
2439 
2440 /// visitSwitchCase - Emits the necessary code to represent a single node in
2441 /// the binary search tree resulting from lowering a switch instruction.
2442 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2443                                           MachineBasicBlock *SwitchBB) {
2444   SDValue Cond;
2445   SDValue CondLHS = getValue(CB.CmpLHS);
2446   SDLoc dl = CB.DL;
2447 
2448   if (CB.CC == ISD::SETTRUE) {
2449     // Branch or fall through to TrueBB.
2450     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2451     SwitchBB->normalizeSuccProbs();
2452     if (CB.TrueBB != NextBlock(SwitchBB)) {
2453       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2454                               DAG.getBasicBlock(CB.TrueBB)));
2455     }
2456     return;
2457   }
2458 
2459   auto &TLI = DAG.getTargetLoweringInfo();
2460   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2461 
2462   // Build the setcc now.
2463   if (!CB.CmpMHS) {
2464     // Fold "(X == true)" to X and "(X == false)" to !X to
2465     // handle common cases produced by branch lowering.
2466     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2467         CB.CC == ISD::SETEQ)
2468       Cond = CondLHS;
2469     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2470              CB.CC == ISD::SETEQ) {
2471       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2472       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2473     } else {
2474       SDValue CondRHS = getValue(CB.CmpRHS);
2475 
2476       // If a pointer's DAG type is larger than its memory type then the DAG
2477       // values are zero-extended. This breaks signed comparisons so truncate
2478       // back to the underlying type before doing the compare.
2479       if (CondLHS.getValueType() != MemVT) {
2480         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2481         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2482       }
2483       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2484     }
2485   } else {
2486     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2487 
2488     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2489     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2490 
2491     SDValue CmpOp = getValue(CB.CmpMHS);
2492     EVT VT = CmpOp.getValueType();
2493 
2494     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2495       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2496                           ISD::SETLE);
2497     } else {
2498       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2499                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2500       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2501                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2502     }
2503   }
2504 
2505   // Update successor info
2506   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2507   // TrueBB and FalseBB are always different unless the incoming IR is
2508   // degenerate. This only happens when running llc on weird IR.
2509   if (CB.TrueBB != CB.FalseBB)
2510     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2511   SwitchBB->normalizeSuccProbs();
2512 
2513   // If the lhs block is the next block, invert the condition so that we can
2514   // fall through to the lhs instead of the rhs block.
2515   if (CB.TrueBB == NextBlock(SwitchBB)) {
2516     std::swap(CB.TrueBB, CB.FalseBB);
2517     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2518     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2519   }
2520 
2521   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2522                                MVT::Other, getControlRoot(), Cond,
2523                                DAG.getBasicBlock(CB.TrueBB));
2524 
2525   // Insert the false branch. Do this even if it's a fall through branch,
2526   // this makes it easier to do DAG optimizations which require inverting
2527   // the branch condition.
2528   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2529                        DAG.getBasicBlock(CB.FalseBB));
2530 
2531   DAG.setRoot(BrCond);
2532 }
2533 
2534 /// visitJumpTable - Emit JumpTable node in the current MBB
2535 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2536   // Emit the code for the jump table
2537   assert(JT.Reg != -1U && "Should lower JT Header first!");
2538   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2539   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2540                                      JT.Reg, PTy);
2541   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2542   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2543                                     MVT::Other, Index.getValue(1),
2544                                     Table, Index);
2545   DAG.setRoot(BrJumpTable);
2546 }
2547 
2548 /// visitJumpTableHeader - This function emits necessary code to produce index
2549 /// in the JumpTable from switch case.
2550 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2551                                                JumpTableHeader &JTH,
2552                                                MachineBasicBlock *SwitchBB) {
2553   SDLoc dl = getCurSDLoc();
2554 
2555   // Subtract the lowest switch case value from the value being switched on.
2556   SDValue SwitchOp = getValue(JTH.SValue);
2557   EVT VT = SwitchOp.getValueType();
2558   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2559                             DAG.getConstant(JTH.First, dl, VT));
2560 
2561   // The SDNode we just created, which holds the value being switched on minus
2562   // the smallest case value, needs to be copied to a virtual register so it
2563   // can be used as an index into the jump table in a subsequent basic block.
2564   // This value may be smaller or larger than the target's pointer type, and
2565   // therefore require extension or truncating.
2566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2567   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2568 
2569   unsigned JumpTableReg =
2570       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2571   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2572                                     JumpTableReg, SwitchOp);
2573   JT.Reg = JumpTableReg;
2574 
2575   if (!JTH.OmitRangeCheck) {
2576     // Emit the range check for the jump table, and branch to the default block
2577     // for the switch statement if the value being switched on exceeds the
2578     // largest case in the switch.
2579     SDValue CMP = DAG.getSetCC(
2580         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2581                                    Sub.getValueType()),
2582         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2583 
2584     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2585                                  MVT::Other, CopyTo, CMP,
2586                                  DAG.getBasicBlock(JT.Default));
2587 
2588     // Avoid emitting unnecessary branches to the next block.
2589     if (JT.MBB != NextBlock(SwitchBB))
2590       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2591                            DAG.getBasicBlock(JT.MBB));
2592 
2593     DAG.setRoot(BrCond);
2594   } else {
2595     // Avoid emitting unnecessary branches to the next block.
2596     if (JT.MBB != NextBlock(SwitchBB))
2597       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2598                               DAG.getBasicBlock(JT.MBB)));
2599     else
2600       DAG.setRoot(CopyTo);
2601   }
2602 }
2603 
2604 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2605 /// variable if there exists one.
2606 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2607                                  SDValue &Chain) {
2608   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2609   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2610   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2611   MachineFunction &MF = DAG.getMachineFunction();
2612   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2613   MachineSDNode *Node =
2614       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2615   if (Global) {
2616     MachinePointerInfo MPInfo(Global);
2617     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2618                  MachineMemOperand::MODereferenceable;
2619     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2620         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2621     DAG.setNodeMemRefs(Node, {MemRef});
2622   }
2623   if (PtrTy != PtrMemTy)
2624     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2625   return SDValue(Node, 0);
2626 }
2627 
2628 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2629 /// tail spliced into a stack protector check success bb.
2630 ///
2631 /// For a high level explanation of how this fits into the stack protector
2632 /// generation see the comment on the declaration of class
2633 /// StackProtectorDescriptor.
2634 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2635                                                   MachineBasicBlock *ParentBB) {
2636 
2637   // First create the loads to the guard/stack slot for the comparison.
2638   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2639   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2640   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2641 
2642   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2643   int FI = MFI.getStackProtectorIndex();
2644 
2645   SDValue Guard;
2646   SDLoc dl = getCurSDLoc();
2647   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2648   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2649   Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2650 
2651   // Generate code to load the content of the guard slot.
2652   SDValue GuardVal = DAG.getLoad(
2653       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2654       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2655       MachineMemOperand::MOVolatile);
2656 
2657   if (TLI.useStackGuardXorFP())
2658     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2659 
2660   // Retrieve guard check function, nullptr if instrumentation is inlined.
2661   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2662     // The target provides a guard check function to validate the guard value.
2663     // Generate a call to that function with the content of the guard slot as
2664     // argument.
2665     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2666     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2667 
2668     TargetLowering::ArgListTy Args;
2669     TargetLowering::ArgListEntry Entry;
2670     Entry.Node = GuardVal;
2671     Entry.Ty = FnTy->getParamType(0);
2672     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2673       Entry.IsInReg = true;
2674     Args.push_back(Entry);
2675 
2676     TargetLowering::CallLoweringInfo CLI(DAG);
2677     CLI.setDebugLoc(getCurSDLoc())
2678         .setChain(DAG.getEntryNode())
2679         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2680                    getValue(GuardCheckFn), std::move(Args));
2681 
2682     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2683     DAG.setRoot(Result.second);
2684     return;
2685   }
2686 
2687   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2688   // Otherwise, emit a volatile load to retrieve the stack guard value.
2689   SDValue Chain = DAG.getEntryNode();
2690   if (TLI.useLoadStackGuardNode()) {
2691     Guard = getLoadStackGuard(DAG, dl, Chain);
2692   } else {
2693     const Value *IRGuard = TLI.getSDagStackGuard(M);
2694     SDValue GuardPtr = getValue(IRGuard);
2695 
2696     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2697                         MachinePointerInfo(IRGuard, 0), Align,
2698                         MachineMemOperand::MOVolatile);
2699   }
2700 
2701   // Perform the comparison via a getsetcc.
2702   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2703                                                         *DAG.getContext(),
2704                                                         Guard.getValueType()),
2705                              Guard, GuardVal, ISD::SETNE);
2706 
2707   // If the guard/stackslot do not equal, branch to failure MBB.
2708   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2709                                MVT::Other, GuardVal.getOperand(0),
2710                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2711   // Otherwise branch to success MBB.
2712   SDValue Br = DAG.getNode(ISD::BR, dl,
2713                            MVT::Other, BrCond,
2714                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2715 
2716   DAG.setRoot(Br);
2717 }
2718 
2719 /// Codegen the failure basic block for a stack protector check.
2720 ///
2721 /// A failure stack protector machine basic block consists simply of a call to
2722 /// __stack_chk_fail().
2723 ///
2724 /// For a high level explanation of how this fits into the stack protector
2725 /// generation see the comment on the declaration of class
2726 /// StackProtectorDescriptor.
2727 void
2728 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2729   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2730   TargetLowering::MakeLibCallOptions CallOptions;
2731   CallOptions.setDiscardResult(true);
2732   SDValue Chain =
2733       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2734                       None, CallOptions, getCurSDLoc()).second;
2735   // On PS4, the "return address" must still be within the calling function,
2736   // even if it's at the very end, so emit an explicit TRAP here.
2737   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2738   if (TM.getTargetTriple().isPS4CPU())
2739     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2740   // WebAssembly needs an unreachable instruction after a non-returning call,
2741   // because the function return type can be different from __stack_chk_fail's
2742   // return type (void).
2743   if (TM.getTargetTriple().isWasm())
2744     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2745 
2746   DAG.setRoot(Chain);
2747 }
2748 
2749 /// visitBitTestHeader - This function emits necessary code to produce value
2750 /// suitable for "bit tests"
2751 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2752                                              MachineBasicBlock *SwitchBB) {
2753   SDLoc dl = getCurSDLoc();
2754 
2755   // Subtract the minimum value.
2756   SDValue SwitchOp = getValue(B.SValue);
2757   EVT VT = SwitchOp.getValueType();
2758   SDValue RangeSub =
2759       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2760 
2761   // Determine the type of the test operands.
2762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2763   bool UsePtrType = false;
2764   if (!TLI.isTypeLegal(VT)) {
2765     UsePtrType = true;
2766   } else {
2767     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2768       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2769         // Switch table case range are encoded into series of masks.
2770         // Just use pointer type, it's guaranteed to fit.
2771         UsePtrType = true;
2772         break;
2773       }
2774   }
2775   SDValue Sub = RangeSub;
2776   if (UsePtrType) {
2777     VT = TLI.getPointerTy(DAG.getDataLayout());
2778     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2779   }
2780 
2781   B.RegVT = VT.getSimpleVT();
2782   B.Reg = FuncInfo.CreateReg(B.RegVT);
2783   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2784 
2785   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2786 
2787   if (!B.OmitRangeCheck)
2788     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2789   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2790   SwitchBB->normalizeSuccProbs();
2791 
2792   SDValue Root = CopyTo;
2793   if (!B.OmitRangeCheck) {
2794     // Conditional branch to the default block.
2795     SDValue RangeCmp = DAG.getSetCC(dl,
2796         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2797                                RangeSub.getValueType()),
2798         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2799         ISD::SETUGT);
2800 
2801     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2802                        DAG.getBasicBlock(B.Default));
2803   }
2804 
2805   // Avoid emitting unnecessary branches to the next block.
2806   if (MBB != NextBlock(SwitchBB))
2807     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2808 
2809   DAG.setRoot(Root);
2810 }
2811 
2812 /// visitBitTestCase - this function produces one "bit test"
2813 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2814                                            MachineBasicBlock* NextMBB,
2815                                            BranchProbability BranchProbToNext,
2816                                            unsigned Reg,
2817                                            BitTestCase &B,
2818                                            MachineBasicBlock *SwitchBB) {
2819   SDLoc dl = getCurSDLoc();
2820   MVT VT = BB.RegVT;
2821   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2822   SDValue Cmp;
2823   unsigned PopCount = countPopulation(B.Mask);
2824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2825   if (PopCount == 1) {
2826     // Testing for a single bit; just compare the shift count with what it
2827     // would need to be to shift a 1 bit in that position.
2828     Cmp = DAG.getSetCC(
2829         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2830         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2831         ISD::SETEQ);
2832   } else if (PopCount == BB.Range) {
2833     // There is only one zero bit in the range, test for it directly.
2834     Cmp = DAG.getSetCC(
2835         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2836         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2837         ISD::SETNE);
2838   } else {
2839     // Make desired shift
2840     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2841                                     DAG.getConstant(1, dl, VT), ShiftOp);
2842 
2843     // Emit bit tests and jumps
2844     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2845                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2846     Cmp = DAG.getSetCC(
2847         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2848         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2849   }
2850 
2851   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2852   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2853   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2854   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2855   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2856   // one as they are relative probabilities (and thus work more like weights),
2857   // and hence we need to normalize them to let the sum of them become one.
2858   SwitchBB->normalizeSuccProbs();
2859 
2860   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2861                               MVT::Other, getControlRoot(),
2862                               Cmp, DAG.getBasicBlock(B.TargetBB));
2863 
2864   // Avoid emitting unnecessary branches to the next block.
2865   if (NextMBB != NextBlock(SwitchBB))
2866     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2867                         DAG.getBasicBlock(NextMBB));
2868 
2869   DAG.setRoot(BrAnd);
2870 }
2871 
2872 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2873   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2874 
2875   // Retrieve successors. Look through artificial IR level blocks like
2876   // catchswitch for successors.
2877   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2878   const BasicBlock *EHPadBB = I.getSuccessor(1);
2879 
2880   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2881   // have to do anything here to lower funclet bundles.
2882   assert(!I.hasOperandBundlesOtherThan(
2883              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2884               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2885               LLVMContext::OB_cfguardtarget,
2886               LLVMContext::OB_clang_arc_attachedcall}) &&
2887          "Cannot lower invokes with arbitrary operand bundles yet!");
2888 
2889   const Value *Callee(I.getCalledOperand());
2890   const Function *Fn = dyn_cast<Function>(Callee);
2891   if (isa<InlineAsm>(Callee))
2892     visitInlineAsm(I, EHPadBB);
2893   else if (Fn && Fn->isIntrinsic()) {
2894     switch (Fn->getIntrinsicID()) {
2895     default:
2896       llvm_unreachable("Cannot invoke this intrinsic");
2897     case Intrinsic::donothing:
2898       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2899     case Intrinsic::seh_try_begin:
2900     case Intrinsic::seh_scope_begin:
2901     case Intrinsic::seh_try_end:
2902     case Intrinsic::seh_scope_end:
2903       break;
2904     case Intrinsic::experimental_patchpoint_void:
2905     case Intrinsic::experimental_patchpoint_i64:
2906       visitPatchpoint(I, EHPadBB);
2907       break;
2908     case Intrinsic::experimental_gc_statepoint:
2909       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2910       break;
2911     case Intrinsic::wasm_rethrow: {
2912       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2913       // special because it can be invoked, so we manually lower it to a DAG
2914       // node here.
2915       SmallVector<SDValue, 8> Ops;
2916       Ops.push_back(getRoot()); // inchain
2917       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2918       Ops.push_back(
2919           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2920                                 TLI.getPointerTy(DAG.getDataLayout())));
2921       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2922       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2923       break;
2924     }
2925     }
2926   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2927     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2928     // Eventually we will support lowering the @llvm.experimental.deoptimize
2929     // intrinsic, and right now there are no plans to support other intrinsics
2930     // with deopt state.
2931     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2932   } else {
2933     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2934   }
2935 
2936   // If the value of the invoke is used outside of its defining block, make it
2937   // available as a virtual register.
2938   // We already took care of the exported value for the statepoint instruction
2939   // during call to the LowerStatepoint.
2940   if (!isa<GCStatepointInst>(I)) {
2941     CopyToExportRegsIfNeeded(&I);
2942   }
2943 
2944   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2945   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2946   BranchProbability EHPadBBProb =
2947       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2948           : BranchProbability::getZero();
2949   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2950 
2951   // Update successor info.
2952   addSuccessorWithProb(InvokeMBB, Return);
2953   for (auto &UnwindDest : UnwindDests) {
2954     UnwindDest.first->setIsEHPad();
2955     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2956   }
2957   InvokeMBB->normalizeSuccProbs();
2958 
2959   // Drop into normal successor.
2960   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2961                           DAG.getBasicBlock(Return)));
2962 }
2963 
2964 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2965   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2966 
2967   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2968   // have to do anything here to lower funclet bundles.
2969   assert(!I.hasOperandBundlesOtherThan(
2970              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2971          "Cannot lower callbrs with arbitrary operand bundles yet!");
2972 
2973   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2974   visitInlineAsm(I);
2975   CopyToExportRegsIfNeeded(&I);
2976 
2977   // Retrieve successors.
2978   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2979 
2980   // Update successor info.
2981   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2982   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2983     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2984     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2985     Target->setIsInlineAsmBrIndirectTarget();
2986   }
2987   CallBrMBB->normalizeSuccProbs();
2988 
2989   // Drop into default successor.
2990   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2991                           MVT::Other, getControlRoot(),
2992                           DAG.getBasicBlock(Return)));
2993 }
2994 
2995 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2996   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2997 }
2998 
2999 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3000   assert(FuncInfo.MBB->isEHPad() &&
3001          "Call to landingpad not in landing pad!");
3002 
3003   // If there aren't registers to copy the values into (e.g., during SjLj
3004   // exceptions), then don't bother to create these DAG nodes.
3005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3006   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3007   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3008       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3009     return;
3010 
3011   // If landingpad's return type is token type, we don't create DAG nodes
3012   // for its exception pointer and selector value. The extraction of exception
3013   // pointer or selector value from token type landingpads is not currently
3014   // supported.
3015   if (LP.getType()->isTokenTy())
3016     return;
3017 
3018   SmallVector<EVT, 2> ValueVTs;
3019   SDLoc dl = getCurSDLoc();
3020   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3021   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3022 
3023   // Get the two live-in registers as SDValues. The physregs have already been
3024   // copied into virtual registers.
3025   SDValue Ops[2];
3026   if (FuncInfo.ExceptionPointerVirtReg) {
3027     Ops[0] = DAG.getZExtOrTrunc(
3028         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3029                            FuncInfo.ExceptionPointerVirtReg,
3030                            TLI.getPointerTy(DAG.getDataLayout())),
3031         dl, ValueVTs[0]);
3032   } else {
3033     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3034   }
3035   Ops[1] = DAG.getZExtOrTrunc(
3036       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3037                          FuncInfo.ExceptionSelectorVirtReg,
3038                          TLI.getPointerTy(DAG.getDataLayout())),
3039       dl, ValueVTs[1]);
3040 
3041   // Merge into one.
3042   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3043                             DAG.getVTList(ValueVTs), Ops);
3044   setValue(&LP, Res);
3045 }
3046 
3047 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3048                                            MachineBasicBlock *Last) {
3049   // Update JTCases.
3050   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
3051     if (SL->JTCases[i].first.HeaderBB == First)
3052       SL->JTCases[i].first.HeaderBB = Last;
3053 
3054   // Update BitTestCases.
3055   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
3056     if (SL->BitTestCases[i].Parent == First)
3057       SL->BitTestCases[i].Parent = Last;
3058 }
3059 
3060 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3061   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3062 
3063   // Update machine-CFG edges with unique successors.
3064   SmallSet<BasicBlock*, 32> Done;
3065   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3066     BasicBlock *BB = I.getSuccessor(i);
3067     bool Inserted = Done.insert(BB).second;
3068     if (!Inserted)
3069         continue;
3070 
3071     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3072     addSuccessorWithProb(IndirectBrMBB, Succ);
3073   }
3074   IndirectBrMBB->normalizeSuccProbs();
3075 
3076   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3077                           MVT::Other, getControlRoot(),
3078                           getValue(I.getAddress())));
3079 }
3080 
3081 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3082   if (!DAG.getTarget().Options.TrapUnreachable)
3083     return;
3084 
3085   // We may be able to ignore unreachable behind a noreturn call.
3086   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3087     const BasicBlock &BB = *I.getParent();
3088     if (&I != &BB.front()) {
3089       BasicBlock::const_iterator PredI =
3090         std::prev(BasicBlock::const_iterator(&I));
3091       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3092         if (Call->doesNotReturn())
3093           return;
3094       }
3095     }
3096   }
3097 
3098   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3099 }
3100 
3101 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3102   SDNodeFlags Flags;
3103 
3104   SDValue Op = getValue(I.getOperand(0));
3105   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3106                                     Op, Flags);
3107   setValue(&I, UnNodeValue);
3108 }
3109 
3110 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3111   SDNodeFlags Flags;
3112   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3113     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3114     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3115   }
3116   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3117     Flags.setExact(ExactOp->isExact());
3118   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3119     Flags.copyFMF(*FPOp);
3120 
3121   SDValue Op1 = getValue(I.getOperand(0));
3122   SDValue Op2 = getValue(I.getOperand(1));
3123   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3124                                      Op1, Op2, Flags);
3125   setValue(&I, BinNodeValue);
3126 }
3127 
3128 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3129   SDValue Op1 = getValue(I.getOperand(0));
3130   SDValue Op2 = getValue(I.getOperand(1));
3131 
3132   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3133       Op1.getValueType(), DAG.getDataLayout());
3134 
3135   // Coerce the shift amount to the right type if we can.
3136   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3137     unsigned ShiftSize = ShiftTy.getSizeInBits();
3138     unsigned Op2Size = Op2.getValueSizeInBits();
3139     SDLoc DL = getCurSDLoc();
3140 
3141     // If the operand is smaller than the shift count type, promote it.
3142     if (ShiftSize > Op2Size)
3143       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3144 
3145     // If the operand is larger than the shift count type but the shift
3146     // count type has enough bits to represent any shift value, truncate
3147     // it now. This is a common case and it exposes the truncate to
3148     // optimization early.
3149     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3150       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3151     // Otherwise we'll need to temporarily settle for some other convenient
3152     // type.  Type legalization will make adjustments once the shiftee is split.
3153     else
3154       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3155   }
3156 
3157   bool nuw = false;
3158   bool nsw = false;
3159   bool exact = false;
3160 
3161   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3162 
3163     if (const OverflowingBinaryOperator *OFBinOp =
3164             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3165       nuw = OFBinOp->hasNoUnsignedWrap();
3166       nsw = OFBinOp->hasNoSignedWrap();
3167     }
3168     if (const PossiblyExactOperator *ExactOp =
3169             dyn_cast<const PossiblyExactOperator>(&I))
3170       exact = ExactOp->isExact();
3171   }
3172   SDNodeFlags Flags;
3173   Flags.setExact(exact);
3174   Flags.setNoSignedWrap(nsw);
3175   Flags.setNoUnsignedWrap(nuw);
3176   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3177                             Flags);
3178   setValue(&I, Res);
3179 }
3180 
3181 void SelectionDAGBuilder::visitSDiv(const User &I) {
3182   SDValue Op1 = getValue(I.getOperand(0));
3183   SDValue Op2 = getValue(I.getOperand(1));
3184 
3185   SDNodeFlags Flags;
3186   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3187                  cast<PossiblyExactOperator>(&I)->isExact());
3188   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3189                            Op2, Flags));
3190 }
3191 
3192 void SelectionDAGBuilder::visitICmp(const User &I) {
3193   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3194   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3195     predicate = IC->getPredicate();
3196   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3197     predicate = ICmpInst::Predicate(IC->getPredicate());
3198   SDValue Op1 = getValue(I.getOperand(0));
3199   SDValue Op2 = getValue(I.getOperand(1));
3200   ISD::CondCode Opcode = getICmpCondCode(predicate);
3201 
3202   auto &TLI = DAG.getTargetLoweringInfo();
3203   EVT MemVT =
3204       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3205 
3206   // If a pointer's DAG type is larger than its memory type then the DAG values
3207   // are zero-extended. This breaks signed comparisons so truncate back to the
3208   // underlying type before doing the compare.
3209   if (Op1.getValueType() != MemVT) {
3210     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3211     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3212   }
3213 
3214   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3215                                                         I.getType());
3216   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3217 }
3218 
3219 void SelectionDAGBuilder::visitFCmp(const User &I) {
3220   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3221   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3222     predicate = FC->getPredicate();
3223   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3224     predicate = FCmpInst::Predicate(FC->getPredicate());
3225   SDValue Op1 = getValue(I.getOperand(0));
3226   SDValue Op2 = getValue(I.getOperand(1));
3227 
3228   ISD::CondCode Condition = getFCmpCondCode(predicate);
3229   auto *FPMO = cast<FPMathOperator>(&I);
3230   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3231     Condition = getFCmpCodeWithoutNaN(Condition);
3232 
3233   SDNodeFlags Flags;
3234   Flags.copyFMF(*FPMO);
3235   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3236 
3237   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3238                                                         I.getType());
3239   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3240 }
3241 
3242 // Check if the condition of the select has one use or two users that are both
3243 // selects with the same condition.
3244 static bool hasOnlySelectUsers(const Value *Cond) {
3245   return llvm::all_of(Cond->users(), [](const Value *V) {
3246     return isa<SelectInst>(V);
3247   });
3248 }
3249 
3250 void SelectionDAGBuilder::visitSelect(const User &I) {
3251   SmallVector<EVT, 4> ValueVTs;
3252   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3253                   ValueVTs);
3254   unsigned NumValues = ValueVTs.size();
3255   if (NumValues == 0) return;
3256 
3257   SmallVector<SDValue, 4> Values(NumValues);
3258   SDValue Cond     = getValue(I.getOperand(0));
3259   SDValue LHSVal   = getValue(I.getOperand(1));
3260   SDValue RHSVal   = getValue(I.getOperand(2));
3261   SmallVector<SDValue, 1> BaseOps(1, Cond);
3262   ISD::NodeType OpCode =
3263       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3264 
3265   bool IsUnaryAbs = false;
3266   bool Negate = false;
3267 
3268   SDNodeFlags Flags;
3269   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3270     Flags.copyFMF(*FPOp);
3271 
3272   // Min/max matching is only viable if all output VTs are the same.
3273   if (is_splat(ValueVTs)) {
3274     EVT VT = ValueVTs[0];
3275     LLVMContext &Ctx = *DAG.getContext();
3276     auto &TLI = DAG.getTargetLoweringInfo();
3277 
3278     // We care about the legality of the operation after it has been type
3279     // legalized.
3280     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3281       VT = TLI.getTypeToTransformTo(Ctx, VT);
3282 
3283     // If the vselect is legal, assume we want to leave this as a vector setcc +
3284     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3285     // min/max is legal on the scalar type.
3286     bool UseScalarMinMax = VT.isVector() &&
3287       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3288 
3289     Value *LHS, *RHS;
3290     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3291     ISD::NodeType Opc = ISD::DELETED_NODE;
3292     switch (SPR.Flavor) {
3293     case SPF_UMAX:    Opc = ISD::UMAX; break;
3294     case SPF_UMIN:    Opc = ISD::UMIN; break;
3295     case SPF_SMAX:    Opc = ISD::SMAX; break;
3296     case SPF_SMIN:    Opc = ISD::SMIN; break;
3297     case SPF_FMINNUM:
3298       switch (SPR.NaNBehavior) {
3299       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3300       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3301       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3302       case SPNB_RETURNS_ANY: {
3303         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3304           Opc = ISD::FMINNUM;
3305         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3306           Opc = ISD::FMINIMUM;
3307         else if (UseScalarMinMax)
3308           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3309             ISD::FMINNUM : ISD::FMINIMUM;
3310         break;
3311       }
3312       }
3313       break;
3314     case SPF_FMAXNUM:
3315       switch (SPR.NaNBehavior) {
3316       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3317       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3318       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3319       case SPNB_RETURNS_ANY:
3320 
3321         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3322           Opc = ISD::FMAXNUM;
3323         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3324           Opc = ISD::FMAXIMUM;
3325         else if (UseScalarMinMax)
3326           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3327             ISD::FMAXNUM : ISD::FMAXIMUM;
3328         break;
3329       }
3330       break;
3331     case SPF_NABS:
3332       Negate = true;
3333       LLVM_FALLTHROUGH;
3334     case SPF_ABS:
3335       IsUnaryAbs = true;
3336       Opc = ISD::ABS;
3337       break;
3338     default: break;
3339     }
3340 
3341     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3342         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3343          (UseScalarMinMax &&
3344           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3345         // If the underlying comparison instruction is used by any other
3346         // instruction, the consumed instructions won't be destroyed, so it is
3347         // not profitable to convert to a min/max.
3348         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3349       OpCode = Opc;
3350       LHSVal = getValue(LHS);
3351       RHSVal = getValue(RHS);
3352       BaseOps.clear();
3353     }
3354 
3355     if (IsUnaryAbs) {
3356       OpCode = Opc;
3357       LHSVal = getValue(LHS);
3358       BaseOps.clear();
3359     }
3360   }
3361 
3362   if (IsUnaryAbs) {
3363     for (unsigned i = 0; i != NumValues; ++i) {
3364       SDLoc dl = getCurSDLoc();
3365       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3366       Values[i] =
3367           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3368       if (Negate)
3369         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3370                                 Values[i]);
3371     }
3372   } else {
3373     for (unsigned i = 0; i != NumValues; ++i) {
3374       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3375       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3376       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3377       Values[i] = DAG.getNode(
3378           OpCode, getCurSDLoc(),
3379           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3380     }
3381   }
3382 
3383   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3384                            DAG.getVTList(ValueVTs), Values));
3385 }
3386 
3387 void SelectionDAGBuilder::visitTrunc(const User &I) {
3388   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3389   SDValue N = getValue(I.getOperand(0));
3390   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3391                                                         I.getType());
3392   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3393 }
3394 
3395 void SelectionDAGBuilder::visitZExt(const User &I) {
3396   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3397   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3398   SDValue N = getValue(I.getOperand(0));
3399   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3400                                                         I.getType());
3401   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3402 }
3403 
3404 void SelectionDAGBuilder::visitSExt(const User &I) {
3405   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3406   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3407   SDValue N = getValue(I.getOperand(0));
3408   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3409                                                         I.getType());
3410   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3411 }
3412 
3413 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3414   // FPTrunc is never a no-op cast, no need to check
3415   SDValue N = getValue(I.getOperand(0));
3416   SDLoc dl = getCurSDLoc();
3417   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3418   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3419   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3420                            DAG.getTargetConstant(
3421                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3422 }
3423 
3424 void SelectionDAGBuilder::visitFPExt(const User &I) {
3425   // FPExt is never a no-op cast, no need to check
3426   SDValue N = getValue(I.getOperand(0));
3427   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3428                                                         I.getType());
3429   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3430 }
3431 
3432 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3433   // FPToUI is never a no-op cast, no need to check
3434   SDValue N = getValue(I.getOperand(0));
3435   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3436                                                         I.getType());
3437   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3438 }
3439 
3440 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3441   // FPToSI is never a no-op cast, no need to check
3442   SDValue N = getValue(I.getOperand(0));
3443   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3444                                                         I.getType());
3445   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3446 }
3447 
3448 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3449   // UIToFP is never a no-op cast, no need to check
3450   SDValue N = getValue(I.getOperand(0));
3451   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3452                                                         I.getType());
3453   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3454 }
3455 
3456 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3457   // SIToFP is never a no-op cast, no need to check
3458   SDValue N = getValue(I.getOperand(0));
3459   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3460                                                         I.getType());
3461   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3462 }
3463 
3464 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3465   // What to do depends on the size of the integer and the size of the pointer.
3466   // We can either truncate, zero extend, or no-op, accordingly.
3467   SDValue N = getValue(I.getOperand(0));
3468   auto &TLI = DAG.getTargetLoweringInfo();
3469   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3470                                                         I.getType());
3471   EVT PtrMemVT =
3472       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3473   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3474   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3475   setValue(&I, N);
3476 }
3477 
3478 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3479   // What to do depends on the size of the integer and the size of the pointer.
3480   // We can either truncate, zero extend, or no-op, accordingly.
3481   SDValue N = getValue(I.getOperand(0));
3482   auto &TLI = DAG.getTargetLoweringInfo();
3483   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3484   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3485   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3486   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3487   setValue(&I, N);
3488 }
3489 
3490 void SelectionDAGBuilder::visitBitCast(const User &I) {
3491   SDValue N = getValue(I.getOperand(0));
3492   SDLoc dl = getCurSDLoc();
3493   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3494                                                         I.getType());
3495 
3496   // BitCast assures us that source and destination are the same size so this is
3497   // either a BITCAST or a no-op.
3498   if (DestVT != N.getValueType())
3499     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3500                              DestVT, N)); // convert types.
3501   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3502   // might fold any kind of constant expression to an integer constant and that
3503   // is not what we are looking for. Only recognize a bitcast of a genuine
3504   // constant integer as an opaque constant.
3505   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3506     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3507                                  /*isOpaque*/true));
3508   else
3509     setValue(&I, N);            // noop cast.
3510 }
3511 
3512 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3514   const Value *SV = I.getOperand(0);
3515   SDValue N = getValue(SV);
3516   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3517 
3518   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3519   unsigned DestAS = I.getType()->getPointerAddressSpace();
3520 
3521   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3522     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3523 
3524   setValue(&I, N);
3525 }
3526 
3527 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3529   SDValue InVec = getValue(I.getOperand(0));
3530   SDValue InVal = getValue(I.getOperand(1));
3531   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3532                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3533   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3534                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3535                            InVec, InVal, InIdx));
3536 }
3537 
3538 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3540   SDValue InVec = getValue(I.getOperand(0));
3541   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3542                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3543   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3544                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3545                            InVec, InIdx));
3546 }
3547 
3548 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3549   SDValue Src1 = getValue(I.getOperand(0));
3550   SDValue Src2 = getValue(I.getOperand(1));
3551   ArrayRef<int> Mask;
3552   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3553     Mask = SVI->getShuffleMask();
3554   else
3555     Mask = cast<ConstantExpr>(I).getShuffleMask();
3556   SDLoc DL = getCurSDLoc();
3557   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3558   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3559   EVT SrcVT = Src1.getValueType();
3560 
3561   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3562       VT.isScalableVector()) {
3563     // Canonical splat form of first element of first input vector.
3564     SDValue FirstElt =
3565         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3566                     DAG.getVectorIdxConstant(0, DL));
3567     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3568     return;
3569   }
3570 
3571   // For now, we only handle splats for scalable vectors.
3572   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3573   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3574   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3575 
3576   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3577   unsigned MaskNumElts = Mask.size();
3578 
3579   if (SrcNumElts == MaskNumElts) {
3580     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3581     return;
3582   }
3583 
3584   // Normalize the shuffle vector since mask and vector length don't match.
3585   if (SrcNumElts < MaskNumElts) {
3586     // Mask is longer than the source vectors. We can use concatenate vector to
3587     // make the mask and vectors lengths match.
3588 
3589     if (MaskNumElts % SrcNumElts == 0) {
3590       // Mask length is a multiple of the source vector length.
3591       // Check if the shuffle is some kind of concatenation of the input
3592       // vectors.
3593       unsigned NumConcat = MaskNumElts / SrcNumElts;
3594       bool IsConcat = true;
3595       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3596       for (unsigned i = 0; i != MaskNumElts; ++i) {
3597         int Idx = Mask[i];
3598         if (Idx < 0)
3599           continue;
3600         // Ensure the indices in each SrcVT sized piece are sequential and that
3601         // the same source is used for the whole piece.
3602         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3603             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3604              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3605           IsConcat = false;
3606           break;
3607         }
3608         // Remember which source this index came from.
3609         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3610       }
3611 
3612       // The shuffle is concatenating multiple vectors together. Just emit
3613       // a CONCAT_VECTORS operation.
3614       if (IsConcat) {
3615         SmallVector<SDValue, 8> ConcatOps;
3616         for (auto Src : ConcatSrcs) {
3617           if (Src < 0)
3618             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3619           else if (Src == 0)
3620             ConcatOps.push_back(Src1);
3621           else
3622             ConcatOps.push_back(Src2);
3623         }
3624         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3625         return;
3626       }
3627     }
3628 
3629     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3630     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3631     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3632                                     PaddedMaskNumElts);
3633 
3634     // Pad both vectors with undefs to make them the same length as the mask.
3635     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3636 
3637     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3638     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3639     MOps1[0] = Src1;
3640     MOps2[0] = Src2;
3641 
3642     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3643     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3644 
3645     // Readjust mask for new input vector length.
3646     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3647     for (unsigned i = 0; i != MaskNumElts; ++i) {
3648       int Idx = Mask[i];
3649       if (Idx >= (int)SrcNumElts)
3650         Idx -= SrcNumElts - PaddedMaskNumElts;
3651       MappedOps[i] = Idx;
3652     }
3653 
3654     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3655 
3656     // If the concatenated vector was padded, extract a subvector with the
3657     // correct number of elements.
3658     if (MaskNumElts != PaddedMaskNumElts)
3659       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3660                            DAG.getVectorIdxConstant(0, DL));
3661 
3662     setValue(&I, Result);
3663     return;
3664   }
3665 
3666   if (SrcNumElts > MaskNumElts) {
3667     // Analyze the access pattern of the vector to see if we can extract
3668     // two subvectors and do the shuffle.
3669     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3670     bool CanExtract = true;
3671     for (int Idx : Mask) {
3672       unsigned Input = 0;
3673       if (Idx < 0)
3674         continue;
3675 
3676       if (Idx >= (int)SrcNumElts) {
3677         Input = 1;
3678         Idx -= SrcNumElts;
3679       }
3680 
3681       // If all the indices come from the same MaskNumElts sized portion of
3682       // the sources we can use extract. Also make sure the extract wouldn't
3683       // extract past the end of the source.
3684       int NewStartIdx = alignDown(Idx, MaskNumElts);
3685       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3686           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3687         CanExtract = false;
3688       // Make sure we always update StartIdx as we use it to track if all
3689       // elements are undef.
3690       StartIdx[Input] = NewStartIdx;
3691     }
3692 
3693     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3694       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3695       return;
3696     }
3697     if (CanExtract) {
3698       // Extract appropriate subvector and generate a vector shuffle
3699       for (unsigned Input = 0; Input < 2; ++Input) {
3700         SDValue &Src = Input == 0 ? Src1 : Src2;
3701         if (StartIdx[Input] < 0)
3702           Src = DAG.getUNDEF(VT);
3703         else {
3704           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3705                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3706         }
3707       }
3708 
3709       // Calculate new mask.
3710       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3711       for (int &Idx : MappedOps) {
3712         if (Idx >= (int)SrcNumElts)
3713           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3714         else if (Idx >= 0)
3715           Idx -= StartIdx[0];
3716       }
3717 
3718       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3719       return;
3720     }
3721   }
3722 
3723   // We can't use either concat vectors or extract subvectors so fall back to
3724   // replacing the shuffle with extract and build vector.
3725   // to insert and build vector.
3726   EVT EltVT = VT.getVectorElementType();
3727   SmallVector<SDValue,8> Ops;
3728   for (int Idx : Mask) {
3729     SDValue Res;
3730 
3731     if (Idx < 0) {
3732       Res = DAG.getUNDEF(EltVT);
3733     } else {
3734       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3735       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3736 
3737       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3738                         DAG.getVectorIdxConstant(Idx, DL));
3739     }
3740 
3741     Ops.push_back(Res);
3742   }
3743 
3744   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3745 }
3746 
3747 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3748   ArrayRef<unsigned> Indices;
3749   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3750     Indices = IV->getIndices();
3751   else
3752     Indices = cast<ConstantExpr>(&I)->getIndices();
3753 
3754   const Value *Op0 = I.getOperand(0);
3755   const Value *Op1 = I.getOperand(1);
3756   Type *AggTy = I.getType();
3757   Type *ValTy = Op1->getType();
3758   bool IntoUndef = isa<UndefValue>(Op0);
3759   bool FromUndef = isa<UndefValue>(Op1);
3760 
3761   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3762 
3763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3764   SmallVector<EVT, 4> AggValueVTs;
3765   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3766   SmallVector<EVT, 4> ValValueVTs;
3767   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3768 
3769   unsigned NumAggValues = AggValueVTs.size();
3770   unsigned NumValValues = ValValueVTs.size();
3771   SmallVector<SDValue, 4> Values(NumAggValues);
3772 
3773   // Ignore an insertvalue that produces an empty object
3774   if (!NumAggValues) {
3775     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3776     return;
3777   }
3778 
3779   SDValue Agg = getValue(Op0);
3780   unsigned i = 0;
3781   // Copy the beginning value(s) from the original aggregate.
3782   for (; i != LinearIndex; ++i)
3783     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3784                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3785   // Copy values from the inserted value(s).
3786   if (NumValValues) {
3787     SDValue Val = getValue(Op1);
3788     for (; i != LinearIndex + NumValValues; ++i)
3789       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3790                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3791   }
3792   // Copy remaining value(s) from the original aggregate.
3793   for (; i != NumAggValues; ++i)
3794     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3795                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3796 
3797   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3798                            DAG.getVTList(AggValueVTs), Values));
3799 }
3800 
3801 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3802   ArrayRef<unsigned> Indices;
3803   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3804     Indices = EV->getIndices();
3805   else
3806     Indices = cast<ConstantExpr>(&I)->getIndices();
3807 
3808   const Value *Op0 = I.getOperand(0);
3809   Type *AggTy = Op0->getType();
3810   Type *ValTy = I.getType();
3811   bool OutOfUndef = isa<UndefValue>(Op0);
3812 
3813   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3814 
3815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3816   SmallVector<EVT, 4> ValValueVTs;
3817   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3818 
3819   unsigned NumValValues = ValValueVTs.size();
3820 
3821   // Ignore a extractvalue that produces an empty object
3822   if (!NumValValues) {
3823     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3824     return;
3825   }
3826 
3827   SmallVector<SDValue, 4> Values(NumValValues);
3828 
3829   SDValue Agg = getValue(Op0);
3830   // Copy out the selected value(s).
3831   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3832     Values[i - LinearIndex] =
3833       OutOfUndef ?
3834         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3835         SDValue(Agg.getNode(), Agg.getResNo() + i);
3836 
3837   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3838                            DAG.getVTList(ValValueVTs), Values));
3839 }
3840 
3841 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3842   Value *Op0 = I.getOperand(0);
3843   // Note that the pointer operand may be a vector of pointers. Take the scalar
3844   // element which holds a pointer.
3845   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3846   SDValue N = getValue(Op0);
3847   SDLoc dl = getCurSDLoc();
3848   auto &TLI = DAG.getTargetLoweringInfo();
3849 
3850   // Normalize Vector GEP - all scalar operands should be converted to the
3851   // splat vector.
3852   bool IsVectorGEP = I.getType()->isVectorTy();
3853   ElementCount VectorElementCount =
3854       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3855                   : ElementCount::getFixed(0);
3856 
3857   if (IsVectorGEP && !N.getValueType().isVector()) {
3858     LLVMContext &Context = *DAG.getContext();
3859     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3860     if (VectorElementCount.isScalable())
3861       N = DAG.getSplatVector(VT, dl, N);
3862     else
3863       N = DAG.getSplatBuildVector(VT, dl, N);
3864   }
3865 
3866   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3867        GTI != E; ++GTI) {
3868     const Value *Idx = GTI.getOperand();
3869     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3870       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3871       if (Field) {
3872         // N = N + Offset
3873         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3874 
3875         // In an inbounds GEP with an offset that is nonnegative even when
3876         // interpreted as signed, assume there is no unsigned overflow.
3877         SDNodeFlags Flags;
3878         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3879           Flags.setNoUnsignedWrap(true);
3880 
3881         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3882                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3883       }
3884     } else {
3885       // IdxSize is the width of the arithmetic according to IR semantics.
3886       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3887       // (and fix up the result later).
3888       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3889       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3890       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3891       // We intentionally mask away the high bits here; ElementSize may not
3892       // fit in IdxTy.
3893       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3894       bool ElementScalable = ElementSize.isScalable();
3895 
3896       // If this is a scalar constant or a splat vector of constants,
3897       // handle it quickly.
3898       const auto *C = dyn_cast<Constant>(Idx);
3899       if (C && isa<VectorType>(C->getType()))
3900         C = C->getSplatValue();
3901 
3902       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3903       if (CI && CI->isZero())
3904         continue;
3905       if (CI && !ElementScalable) {
3906         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3907         LLVMContext &Context = *DAG.getContext();
3908         SDValue OffsVal;
3909         if (IsVectorGEP)
3910           OffsVal = DAG.getConstant(
3911               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3912         else
3913           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3914 
3915         // In an inbounds GEP with an offset that is nonnegative even when
3916         // interpreted as signed, assume there is no unsigned overflow.
3917         SDNodeFlags Flags;
3918         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3919           Flags.setNoUnsignedWrap(true);
3920 
3921         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3922 
3923         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3924         continue;
3925       }
3926 
3927       // N = N + Idx * ElementMul;
3928       SDValue IdxN = getValue(Idx);
3929 
3930       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3931         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3932                                   VectorElementCount);
3933         if (VectorElementCount.isScalable())
3934           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3935         else
3936           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3937       }
3938 
3939       // If the index is smaller or larger than intptr_t, truncate or extend
3940       // it.
3941       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3942 
3943       if (ElementScalable) {
3944         EVT VScaleTy = N.getValueType().getScalarType();
3945         SDValue VScale = DAG.getNode(
3946             ISD::VSCALE, dl, VScaleTy,
3947             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3948         if (IsVectorGEP)
3949           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3950         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3951       } else {
3952         // If this is a multiply by a power of two, turn it into a shl
3953         // immediately.  This is a very common case.
3954         if (ElementMul != 1) {
3955           if (ElementMul.isPowerOf2()) {
3956             unsigned Amt = ElementMul.logBase2();
3957             IdxN = DAG.getNode(ISD::SHL, dl,
3958                                N.getValueType(), IdxN,
3959                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3960           } else {
3961             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3962                                             IdxN.getValueType());
3963             IdxN = DAG.getNode(ISD::MUL, dl,
3964                                N.getValueType(), IdxN, Scale);
3965           }
3966         }
3967       }
3968 
3969       N = DAG.getNode(ISD::ADD, dl,
3970                       N.getValueType(), N, IdxN);
3971     }
3972   }
3973 
3974   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3975   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3976   if (IsVectorGEP) {
3977     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3978     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3979   }
3980 
3981   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3982     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3983 
3984   setValue(&I, N);
3985 }
3986 
3987 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3988   // If this is a fixed sized alloca in the entry block of the function,
3989   // allocate it statically on the stack.
3990   if (FuncInfo.StaticAllocaMap.count(&I))
3991     return;   // getValue will auto-populate this.
3992 
3993   SDLoc dl = getCurSDLoc();
3994   Type *Ty = I.getAllocatedType();
3995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3996   auto &DL = DAG.getDataLayout();
3997   uint64_t TySize = DL.getTypeAllocSize(Ty);
3998   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3999 
4000   SDValue AllocSize = getValue(I.getArraySize());
4001 
4002   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4003   if (AllocSize.getValueType() != IntPtr)
4004     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4005 
4006   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4007                           AllocSize,
4008                           DAG.getConstant(TySize, dl, IntPtr));
4009 
4010   // Handle alignment.  If the requested alignment is less than or equal to
4011   // the stack alignment, ignore it.  If the size is greater than or equal to
4012   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4013   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4014   if (*Alignment <= StackAlign)
4015     Alignment = None;
4016 
4017   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4018   // Round the size of the allocation up to the stack alignment size
4019   // by add SA-1 to the size. This doesn't overflow because we're computing
4020   // an address inside an alloca.
4021   SDNodeFlags Flags;
4022   Flags.setNoUnsignedWrap(true);
4023   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4024                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4025 
4026   // Mask out the low bits for alignment purposes.
4027   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4028                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4029 
4030   SDValue Ops[] = {
4031       getRoot(), AllocSize,
4032       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4033   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4034   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4035   setValue(&I, DSA);
4036   DAG.setRoot(DSA.getValue(1));
4037 
4038   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4039 }
4040 
4041 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4042   if (I.isAtomic())
4043     return visitAtomicLoad(I);
4044 
4045   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4046   const Value *SV = I.getOperand(0);
4047   if (TLI.supportSwiftError()) {
4048     // Swifterror values can come from either a function parameter with
4049     // swifterror attribute or an alloca with swifterror attribute.
4050     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4051       if (Arg->hasSwiftErrorAttr())
4052         return visitLoadFromSwiftError(I);
4053     }
4054 
4055     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4056       if (Alloca->isSwiftError())
4057         return visitLoadFromSwiftError(I);
4058     }
4059   }
4060 
4061   SDValue Ptr = getValue(SV);
4062 
4063   Type *Ty = I.getType();
4064   Align Alignment = I.getAlign();
4065 
4066   AAMDNodes AAInfo;
4067   I.getAAMetadata(AAInfo);
4068   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4069 
4070   SmallVector<EVT, 4> ValueVTs, MemVTs;
4071   SmallVector<uint64_t, 4> Offsets;
4072   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4073   unsigned NumValues = ValueVTs.size();
4074   if (NumValues == 0)
4075     return;
4076 
4077   bool isVolatile = I.isVolatile();
4078 
4079   SDValue Root;
4080   bool ConstantMemory = false;
4081   if (isVolatile)
4082     // Serialize volatile loads with other side effects.
4083     Root = getRoot();
4084   else if (NumValues > MaxParallelChains)
4085     Root = getMemoryRoot();
4086   else if (AA &&
4087            AA->pointsToConstantMemory(MemoryLocation(
4088                SV,
4089                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4090                AAInfo))) {
4091     // Do not serialize (non-volatile) loads of constant memory with anything.
4092     Root = DAG.getEntryNode();
4093     ConstantMemory = true;
4094   } else {
4095     // Do not serialize non-volatile loads against each other.
4096     Root = DAG.getRoot();
4097   }
4098 
4099   SDLoc dl = getCurSDLoc();
4100 
4101   if (isVolatile)
4102     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4103 
4104   // An aggregate load cannot wrap around the address space, so offsets to its
4105   // parts don't wrap either.
4106   SDNodeFlags Flags;
4107   Flags.setNoUnsignedWrap(true);
4108 
4109   SmallVector<SDValue, 4> Values(NumValues);
4110   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4111   EVT PtrVT = Ptr.getValueType();
4112 
4113   MachineMemOperand::Flags MMOFlags
4114     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4115 
4116   unsigned ChainI = 0;
4117   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4118     // Serializing loads here may result in excessive register pressure, and
4119     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4120     // could recover a bit by hoisting nodes upward in the chain by recognizing
4121     // they are side-effect free or do not alias. The optimizer should really
4122     // avoid this case by converting large object/array copies to llvm.memcpy
4123     // (MaxParallelChains should always remain as failsafe).
4124     if (ChainI == MaxParallelChains) {
4125       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4126       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4127                                   makeArrayRef(Chains.data(), ChainI));
4128       Root = Chain;
4129       ChainI = 0;
4130     }
4131     SDValue A = DAG.getNode(ISD::ADD, dl,
4132                             PtrVT, Ptr,
4133                             DAG.getConstant(Offsets[i], dl, PtrVT),
4134                             Flags);
4135 
4136     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4137                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4138                             MMOFlags, AAInfo, Ranges);
4139     Chains[ChainI] = L.getValue(1);
4140 
4141     if (MemVTs[i] != ValueVTs[i])
4142       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4143 
4144     Values[i] = L;
4145   }
4146 
4147   if (!ConstantMemory) {
4148     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4149                                 makeArrayRef(Chains.data(), ChainI));
4150     if (isVolatile)
4151       DAG.setRoot(Chain);
4152     else
4153       PendingLoads.push_back(Chain);
4154   }
4155 
4156   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4157                            DAG.getVTList(ValueVTs), Values));
4158 }
4159 
4160 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4161   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4162          "call visitStoreToSwiftError when backend supports swifterror");
4163 
4164   SmallVector<EVT, 4> ValueVTs;
4165   SmallVector<uint64_t, 4> Offsets;
4166   const Value *SrcV = I.getOperand(0);
4167   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4168                   SrcV->getType(), ValueVTs, &Offsets);
4169   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4170          "expect a single EVT for swifterror");
4171 
4172   SDValue Src = getValue(SrcV);
4173   // Create a virtual register, then update the virtual register.
4174   Register VReg =
4175       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4176   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4177   // Chain can be getRoot or getControlRoot.
4178   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4179                                       SDValue(Src.getNode(), Src.getResNo()));
4180   DAG.setRoot(CopyNode);
4181 }
4182 
4183 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4184   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4185          "call visitLoadFromSwiftError when backend supports swifterror");
4186 
4187   assert(!I.isVolatile() &&
4188          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4189          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4190          "Support volatile, non temporal, invariant for load_from_swift_error");
4191 
4192   const Value *SV = I.getOperand(0);
4193   Type *Ty = I.getType();
4194   AAMDNodes AAInfo;
4195   I.getAAMetadata(AAInfo);
4196   assert(
4197       (!AA ||
4198        !AA->pointsToConstantMemory(MemoryLocation(
4199            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4200            AAInfo))) &&
4201       "load_from_swift_error should not be constant memory");
4202 
4203   SmallVector<EVT, 4> ValueVTs;
4204   SmallVector<uint64_t, 4> Offsets;
4205   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4206                   ValueVTs, &Offsets);
4207   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4208          "expect a single EVT for swifterror");
4209 
4210   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4211   SDValue L = DAG.getCopyFromReg(
4212       getRoot(), getCurSDLoc(),
4213       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4214 
4215   setValue(&I, L);
4216 }
4217 
4218 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4219   if (I.isAtomic())
4220     return visitAtomicStore(I);
4221 
4222   const Value *SrcV = I.getOperand(0);
4223   const Value *PtrV = I.getOperand(1);
4224 
4225   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4226   if (TLI.supportSwiftError()) {
4227     // Swifterror values can come from either a function parameter with
4228     // swifterror attribute or an alloca with swifterror attribute.
4229     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4230       if (Arg->hasSwiftErrorAttr())
4231         return visitStoreToSwiftError(I);
4232     }
4233 
4234     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4235       if (Alloca->isSwiftError())
4236         return visitStoreToSwiftError(I);
4237     }
4238   }
4239 
4240   SmallVector<EVT, 4> ValueVTs, MemVTs;
4241   SmallVector<uint64_t, 4> Offsets;
4242   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4243                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4244   unsigned NumValues = ValueVTs.size();
4245   if (NumValues == 0)
4246     return;
4247 
4248   // Get the lowered operands. Note that we do this after
4249   // checking if NumResults is zero, because with zero results
4250   // the operands won't have values in the map.
4251   SDValue Src = getValue(SrcV);
4252   SDValue Ptr = getValue(PtrV);
4253 
4254   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4255   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4256   SDLoc dl = getCurSDLoc();
4257   Align Alignment = I.getAlign();
4258   AAMDNodes AAInfo;
4259   I.getAAMetadata(AAInfo);
4260 
4261   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4262 
4263   // An aggregate load cannot wrap around the address space, so offsets to its
4264   // parts don't wrap either.
4265   SDNodeFlags Flags;
4266   Flags.setNoUnsignedWrap(true);
4267 
4268   unsigned ChainI = 0;
4269   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4270     // See visitLoad comments.
4271     if (ChainI == MaxParallelChains) {
4272       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4273                                   makeArrayRef(Chains.data(), ChainI));
4274       Root = Chain;
4275       ChainI = 0;
4276     }
4277     SDValue Add =
4278         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4279     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4280     if (MemVTs[i] != ValueVTs[i])
4281       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4282     SDValue St =
4283         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4284                      Alignment, MMOFlags, AAInfo);
4285     Chains[ChainI] = St;
4286   }
4287 
4288   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4289                                   makeArrayRef(Chains.data(), ChainI));
4290   DAG.setRoot(StoreNode);
4291 }
4292 
4293 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4294                                            bool IsCompressing) {
4295   SDLoc sdl = getCurSDLoc();
4296 
4297   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4298                                MaybeAlign &Alignment) {
4299     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4300     Src0 = I.getArgOperand(0);
4301     Ptr = I.getArgOperand(1);
4302     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4303     Mask = I.getArgOperand(3);
4304   };
4305   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4306                                     MaybeAlign &Alignment) {
4307     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4308     Src0 = I.getArgOperand(0);
4309     Ptr = I.getArgOperand(1);
4310     Mask = I.getArgOperand(2);
4311     Alignment = None;
4312   };
4313 
4314   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4315   MaybeAlign Alignment;
4316   if (IsCompressing)
4317     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4318   else
4319     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4320 
4321   SDValue Ptr = getValue(PtrOperand);
4322   SDValue Src0 = getValue(Src0Operand);
4323   SDValue Mask = getValue(MaskOperand);
4324   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4325 
4326   EVT VT = Src0.getValueType();
4327   if (!Alignment)
4328     Alignment = DAG.getEVTAlign(VT);
4329 
4330   AAMDNodes AAInfo;
4331   I.getAAMetadata(AAInfo);
4332 
4333   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4334       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4335       // TODO: Make MachineMemOperands aware of scalable
4336       // vectors.
4337       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4338   SDValue StoreNode =
4339       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4340                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4341   DAG.setRoot(StoreNode);
4342   setValue(&I, StoreNode);
4343 }
4344 
4345 // Get a uniform base for the Gather/Scatter intrinsic.
4346 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4347 // We try to represent it as a base pointer + vector of indices.
4348 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4349 // The first operand of the GEP may be a single pointer or a vector of pointers
4350 // Example:
4351 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4352 //  or
4353 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4354 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4355 //
4356 // When the first GEP operand is a single pointer - it is the uniform base we
4357 // are looking for. If first operand of the GEP is a splat vector - we
4358 // extract the splat value and use it as a uniform base.
4359 // In all other cases the function returns 'false'.
4360 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4361                            ISD::MemIndexType &IndexType, SDValue &Scale,
4362                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4363   SelectionDAG& DAG = SDB->DAG;
4364   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4365   const DataLayout &DL = DAG.getDataLayout();
4366 
4367   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4368 
4369   // Handle splat constant pointer.
4370   if (auto *C = dyn_cast<Constant>(Ptr)) {
4371     C = C->getSplatValue();
4372     if (!C)
4373       return false;
4374 
4375     Base = SDB->getValue(C);
4376 
4377     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4378     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4379     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4380     IndexType = ISD::SIGNED_SCALED;
4381     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4382     return true;
4383   }
4384 
4385   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4386   if (!GEP || GEP->getParent() != CurBB)
4387     return false;
4388 
4389   if (GEP->getNumOperands() != 2)
4390     return false;
4391 
4392   const Value *BasePtr = GEP->getPointerOperand();
4393   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4394 
4395   // Make sure the base is scalar and the index is a vector.
4396   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4397     return false;
4398 
4399   Base = SDB->getValue(BasePtr);
4400   Index = SDB->getValue(IndexVal);
4401   IndexType = ISD::SIGNED_SCALED;
4402   Scale = DAG.getTargetConstant(
4403               DL.getTypeAllocSize(GEP->getResultElementType()),
4404               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4405   return true;
4406 }
4407 
4408 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4409   SDLoc sdl = getCurSDLoc();
4410 
4411   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4412   const Value *Ptr = I.getArgOperand(1);
4413   SDValue Src0 = getValue(I.getArgOperand(0));
4414   SDValue Mask = getValue(I.getArgOperand(3));
4415   EVT VT = Src0.getValueType();
4416   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4417                         ->getMaybeAlignValue()
4418                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4419   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4420 
4421   AAMDNodes AAInfo;
4422   I.getAAMetadata(AAInfo);
4423 
4424   SDValue Base;
4425   SDValue Index;
4426   ISD::MemIndexType IndexType;
4427   SDValue Scale;
4428   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4429                                     I.getParent());
4430 
4431   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4432   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4433       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4434       // TODO: Make MachineMemOperands aware of scalable
4435       // vectors.
4436       MemoryLocation::UnknownSize, Alignment, AAInfo);
4437   if (!UniformBase) {
4438     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4439     Index = getValue(Ptr);
4440     IndexType = ISD::SIGNED_UNSCALED;
4441     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4442   }
4443 
4444   EVT IdxVT = Index.getValueType();
4445   EVT EltTy = IdxVT.getVectorElementType();
4446   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4447     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4448     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4449   }
4450 
4451   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4452   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4453                                          Ops, MMO, IndexType, false);
4454   DAG.setRoot(Scatter);
4455   setValue(&I, Scatter);
4456 }
4457 
4458 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4459   SDLoc sdl = getCurSDLoc();
4460 
4461   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4462                               MaybeAlign &Alignment) {
4463     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4464     Ptr = I.getArgOperand(0);
4465     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4466     Mask = I.getArgOperand(2);
4467     Src0 = I.getArgOperand(3);
4468   };
4469   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4470                                  MaybeAlign &Alignment) {
4471     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4472     Ptr = I.getArgOperand(0);
4473     Alignment = None;
4474     Mask = I.getArgOperand(1);
4475     Src0 = I.getArgOperand(2);
4476   };
4477 
4478   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4479   MaybeAlign Alignment;
4480   if (IsExpanding)
4481     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4482   else
4483     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4484 
4485   SDValue Ptr = getValue(PtrOperand);
4486   SDValue Src0 = getValue(Src0Operand);
4487   SDValue Mask = getValue(MaskOperand);
4488   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4489 
4490   EVT VT = Src0.getValueType();
4491   if (!Alignment)
4492     Alignment = DAG.getEVTAlign(VT);
4493 
4494   AAMDNodes AAInfo;
4495   I.getAAMetadata(AAInfo);
4496   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4497 
4498   // Do not serialize masked loads of constant memory with anything.
4499   MemoryLocation ML;
4500   if (VT.isScalableVector())
4501     ML = MemoryLocation::getAfter(PtrOperand);
4502   else
4503     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4504                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4505                            AAInfo);
4506   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4507 
4508   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4509 
4510   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4511       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4512       // TODO: Make MachineMemOperands aware of scalable
4513       // vectors.
4514       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4515 
4516   SDValue Load =
4517       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4518                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4519   if (AddToChain)
4520     PendingLoads.push_back(Load.getValue(1));
4521   setValue(&I, Load);
4522 }
4523 
4524 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4525   SDLoc sdl = getCurSDLoc();
4526 
4527   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4528   const Value *Ptr = I.getArgOperand(0);
4529   SDValue Src0 = getValue(I.getArgOperand(3));
4530   SDValue Mask = getValue(I.getArgOperand(2));
4531 
4532   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4533   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4534   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4535                         ->getMaybeAlignValue()
4536                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4537 
4538   AAMDNodes AAInfo;
4539   I.getAAMetadata(AAInfo);
4540   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4541 
4542   SDValue Root = DAG.getRoot();
4543   SDValue Base;
4544   SDValue Index;
4545   ISD::MemIndexType IndexType;
4546   SDValue Scale;
4547   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4548                                     I.getParent());
4549   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4550   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4551       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4552       // TODO: Make MachineMemOperands aware of scalable
4553       // vectors.
4554       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4555 
4556   if (!UniformBase) {
4557     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4558     Index = getValue(Ptr);
4559     IndexType = ISD::SIGNED_UNSCALED;
4560     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4561   }
4562 
4563   EVT IdxVT = Index.getValueType();
4564   EVT EltTy = IdxVT.getVectorElementType();
4565   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4566     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4567     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4568   }
4569 
4570   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4571   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4572                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4573 
4574   PendingLoads.push_back(Gather.getValue(1));
4575   setValue(&I, Gather);
4576 }
4577 
4578 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4579   SDLoc dl = getCurSDLoc();
4580   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4581   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4582   SyncScope::ID SSID = I.getSyncScopeID();
4583 
4584   SDValue InChain = getRoot();
4585 
4586   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4587   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4588 
4589   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4590   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4591 
4592   MachineFunction &MF = DAG.getMachineFunction();
4593   MachineMemOperand *MMO = MF.getMachineMemOperand(
4594       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4595       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4596       FailureOrdering);
4597 
4598   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4599                                    dl, MemVT, VTs, InChain,
4600                                    getValue(I.getPointerOperand()),
4601                                    getValue(I.getCompareOperand()),
4602                                    getValue(I.getNewValOperand()), MMO);
4603 
4604   SDValue OutChain = L.getValue(2);
4605 
4606   setValue(&I, L);
4607   DAG.setRoot(OutChain);
4608 }
4609 
4610 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4611   SDLoc dl = getCurSDLoc();
4612   ISD::NodeType NT;
4613   switch (I.getOperation()) {
4614   default: llvm_unreachable("Unknown atomicrmw operation");
4615   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4616   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4617   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4618   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4619   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4620   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4621   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4622   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4623   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4624   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4625   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4626   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4627   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4628   }
4629   AtomicOrdering Ordering = I.getOrdering();
4630   SyncScope::ID SSID = I.getSyncScopeID();
4631 
4632   SDValue InChain = getRoot();
4633 
4634   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4636   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4637 
4638   MachineFunction &MF = DAG.getMachineFunction();
4639   MachineMemOperand *MMO = MF.getMachineMemOperand(
4640       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4641       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4642 
4643   SDValue L =
4644     DAG.getAtomic(NT, dl, MemVT, InChain,
4645                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4646                   MMO);
4647 
4648   SDValue OutChain = L.getValue(1);
4649 
4650   setValue(&I, L);
4651   DAG.setRoot(OutChain);
4652 }
4653 
4654 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4655   SDLoc dl = getCurSDLoc();
4656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4657   SDValue Ops[3];
4658   Ops[0] = getRoot();
4659   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4660                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4661   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4662                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4663   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4664 }
4665 
4666 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4667   SDLoc dl = getCurSDLoc();
4668   AtomicOrdering Order = I.getOrdering();
4669   SyncScope::ID SSID = I.getSyncScopeID();
4670 
4671   SDValue InChain = getRoot();
4672 
4673   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4674   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4675   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4676 
4677   if (!TLI.supportsUnalignedAtomics() &&
4678       I.getAlignment() < MemVT.getSizeInBits() / 8)
4679     report_fatal_error("Cannot generate unaligned atomic load");
4680 
4681   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4682 
4683   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4684       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4685       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4686 
4687   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4688 
4689   SDValue Ptr = getValue(I.getPointerOperand());
4690 
4691   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4692     // TODO: Once this is better exercised by tests, it should be merged with
4693     // the normal path for loads to prevent future divergence.
4694     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4695     if (MemVT != VT)
4696       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4697 
4698     setValue(&I, L);
4699     SDValue OutChain = L.getValue(1);
4700     if (!I.isUnordered())
4701       DAG.setRoot(OutChain);
4702     else
4703       PendingLoads.push_back(OutChain);
4704     return;
4705   }
4706 
4707   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4708                             Ptr, MMO);
4709 
4710   SDValue OutChain = L.getValue(1);
4711   if (MemVT != VT)
4712     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4713 
4714   setValue(&I, L);
4715   DAG.setRoot(OutChain);
4716 }
4717 
4718 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4719   SDLoc dl = getCurSDLoc();
4720 
4721   AtomicOrdering Ordering = I.getOrdering();
4722   SyncScope::ID SSID = I.getSyncScopeID();
4723 
4724   SDValue InChain = getRoot();
4725 
4726   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4727   EVT MemVT =
4728       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4729 
4730   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4731     report_fatal_error("Cannot generate unaligned atomic store");
4732 
4733   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4734 
4735   MachineFunction &MF = DAG.getMachineFunction();
4736   MachineMemOperand *MMO = MF.getMachineMemOperand(
4737       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4738       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4739 
4740   SDValue Val = getValue(I.getValueOperand());
4741   if (Val.getValueType() != MemVT)
4742     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4743   SDValue Ptr = getValue(I.getPointerOperand());
4744 
4745   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4746     // TODO: Once this is better exercised by tests, it should be merged with
4747     // the normal path for stores to prevent future divergence.
4748     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4749     DAG.setRoot(S);
4750     return;
4751   }
4752   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4753                                    Ptr, Val, MMO);
4754 
4755 
4756   DAG.setRoot(OutChain);
4757 }
4758 
4759 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4760 /// node.
4761 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4762                                                unsigned Intrinsic) {
4763   // Ignore the callsite's attributes. A specific call site may be marked with
4764   // readnone, but the lowering code will expect the chain based on the
4765   // definition.
4766   const Function *F = I.getCalledFunction();
4767   bool HasChain = !F->doesNotAccessMemory();
4768   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4769 
4770   // Build the operand list.
4771   SmallVector<SDValue, 8> Ops;
4772   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4773     if (OnlyLoad) {
4774       // We don't need to serialize loads against other loads.
4775       Ops.push_back(DAG.getRoot());
4776     } else {
4777       Ops.push_back(getRoot());
4778     }
4779   }
4780 
4781   // Info is set by getTgtMemInstrinsic
4782   TargetLowering::IntrinsicInfo Info;
4783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4784   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4785                                                DAG.getMachineFunction(),
4786                                                Intrinsic);
4787 
4788   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4789   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4790       Info.opc == ISD::INTRINSIC_W_CHAIN)
4791     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4792                                         TLI.getPointerTy(DAG.getDataLayout())));
4793 
4794   // Add all operands of the call to the operand list.
4795   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4796     const Value *Arg = I.getArgOperand(i);
4797     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4798       Ops.push_back(getValue(Arg));
4799       continue;
4800     }
4801 
4802     // Use TargetConstant instead of a regular constant for immarg.
4803     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4804     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4805       assert(CI->getBitWidth() <= 64 &&
4806              "large intrinsic immediates not handled");
4807       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4808     } else {
4809       Ops.push_back(
4810           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4811     }
4812   }
4813 
4814   SmallVector<EVT, 4> ValueVTs;
4815   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4816 
4817   if (HasChain)
4818     ValueVTs.push_back(MVT::Other);
4819 
4820   SDVTList VTs = DAG.getVTList(ValueVTs);
4821 
4822   // Propagate fast-math-flags from IR to node(s).
4823   SDNodeFlags Flags;
4824   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4825     Flags.copyFMF(*FPMO);
4826   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4827 
4828   // Create the node.
4829   SDValue Result;
4830   if (IsTgtIntrinsic) {
4831     // This is target intrinsic that touches memory
4832     AAMDNodes AAInfo;
4833     I.getAAMetadata(AAInfo);
4834     Result =
4835         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4836                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4837                                 Info.align, Info.flags, Info.size, AAInfo);
4838   } else if (!HasChain) {
4839     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4840   } else if (!I.getType()->isVoidTy()) {
4841     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4842   } else {
4843     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4844   }
4845 
4846   if (HasChain) {
4847     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4848     if (OnlyLoad)
4849       PendingLoads.push_back(Chain);
4850     else
4851       DAG.setRoot(Chain);
4852   }
4853 
4854   if (!I.getType()->isVoidTy()) {
4855     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4856       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4857       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4858     } else
4859       Result = lowerRangeToAssertZExt(DAG, I, Result);
4860 
4861     MaybeAlign Alignment = I.getRetAlign();
4862     if (!Alignment)
4863       Alignment = F->getAttributes().getRetAlignment();
4864     // Insert `assertalign` node if there's an alignment.
4865     if (InsertAssertAlign && Alignment) {
4866       Result =
4867           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4868     }
4869 
4870     setValue(&I, Result);
4871   }
4872 }
4873 
4874 /// GetSignificand - Get the significand and build it into a floating-point
4875 /// number with exponent of 1:
4876 ///
4877 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4878 ///
4879 /// where Op is the hexadecimal representation of floating point value.
4880 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4881   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4882                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4883   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4884                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4885   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4886 }
4887 
4888 /// GetExponent - Get the exponent:
4889 ///
4890 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4891 ///
4892 /// where Op is the hexadecimal representation of floating point value.
4893 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4894                            const TargetLowering &TLI, const SDLoc &dl) {
4895   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4896                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4897   SDValue t1 = DAG.getNode(
4898       ISD::SRL, dl, MVT::i32, t0,
4899       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4900   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4901                            DAG.getConstant(127, dl, MVT::i32));
4902   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4903 }
4904 
4905 /// getF32Constant - Get 32-bit floating point constant.
4906 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4907                               const SDLoc &dl) {
4908   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4909                            MVT::f32);
4910 }
4911 
4912 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4913                                        SelectionDAG &DAG) {
4914   // TODO: What fast-math-flags should be set on the floating-point nodes?
4915 
4916   //   IntegerPartOfX = ((int32_t)(t0);
4917   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4918 
4919   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4920   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4921   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4922 
4923   //   IntegerPartOfX <<= 23;
4924   IntegerPartOfX = DAG.getNode(
4925       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4926       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4927                                   DAG.getDataLayout())));
4928 
4929   SDValue TwoToFractionalPartOfX;
4930   if (LimitFloatPrecision <= 6) {
4931     // For floating-point precision of 6:
4932     //
4933     //   TwoToFractionalPartOfX =
4934     //     0.997535578f +
4935     //       (0.735607626f + 0.252464424f * x) * x;
4936     //
4937     // error 0.0144103317, which is 6 bits
4938     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4939                              getF32Constant(DAG, 0x3e814304, dl));
4940     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4941                              getF32Constant(DAG, 0x3f3c50c8, dl));
4942     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4943     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4944                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4945   } else if (LimitFloatPrecision <= 12) {
4946     // For floating-point precision of 12:
4947     //
4948     //   TwoToFractionalPartOfX =
4949     //     0.999892986f +
4950     //       (0.696457318f +
4951     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4952     //
4953     // error 0.000107046256, which is 13 to 14 bits
4954     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4955                              getF32Constant(DAG, 0x3da235e3, dl));
4956     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4957                              getF32Constant(DAG, 0x3e65b8f3, dl));
4958     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4959     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4960                              getF32Constant(DAG, 0x3f324b07, dl));
4961     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4962     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4963                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4964   } else { // LimitFloatPrecision <= 18
4965     // For floating-point precision of 18:
4966     //
4967     //   TwoToFractionalPartOfX =
4968     //     0.999999982f +
4969     //       (0.693148872f +
4970     //         (0.240227044f +
4971     //           (0.554906021e-1f +
4972     //             (0.961591928e-2f +
4973     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4974     // error 2.47208000*10^(-7), which is better than 18 bits
4975     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4976                              getF32Constant(DAG, 0x3924b03e, dl));
4977     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4978                              getF32Constant(DAG, 0x3ab24b87, dl));
4979     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4980     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4981                              getF32Constant(DAG, 0x3c1d8c17, dl));
4982     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4983     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4984                              getF32Constant(DAG, 0x3d634a1d, dl));
4985     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4986     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4987                              getF32Constant(DAG, 0x3e75fe14, dl));
4988     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4989     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4990                               getF32Constant(DAG, 0x3f317234, dl));
4991     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4992     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4993                                          getF32Constant(DAG, 0x3f800000, dl));
4994   }
4995 
4996   // Add the exponent into the result in integer domain.
4997   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4998   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4999                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5000 }
5001 
5002 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5003 /// limited-precision mode.
5004 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5005                          const TargetLowering &TLI, SDNodeFlags Flags) {
5006   if (Op.getValueType() == MVT::f32 &&
5007       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5008 
5009     // Put the exponent in the right bit position for later addition to the
5010     // final result:
5011     //
5012     // t0 = Op * log2(e)
5013 
5014     // TODO: What fast-math-flags should be set here?
5015     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5016                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5017     return getLimitedPrecisionExp2(t0, dl, DAG);
5018   }
5019 
5020   // No special expansion.
5021   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5022 }
5023 
5024 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5025 /// limited-precision mode.
5026 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5027                          const TargetLowering &TLI, SDNodeFlags Flags) {
5028   // TODO: What fast-math-flags should be set on the floating-point nodes?
5029 
5030   if (Op.getValueType() == MVT::f32 &&
5031       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5032     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5033 
5034     // Scale the exponent by log(2).
5035     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5036     SDValue LogOfExponent =
5037         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5038                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5039 
5040     // Get the significand and build it into a floating-point number with
5041     // exponent of 1.
5042     SDValue X = GetSignificand(DAG, Op1, dl);
5043 
5044     SDValue LogOfMantissa;
5045     if (LimitFloatPrecision <= 6) {
5046       // For floating-point precision of 6:
5047       //
5048       //   LogofMantissa =
5049       //     -1.1609546f +
5050       //       (1.4034025f - 0.23903021f * x) * x;
5051       //
5052       // error 0.0034276066, which is better than 8 bits
5053       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5054                                getF32Constant(DAG, 0xbe74c456, dl));
5055       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5056                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5057       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5058       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5059                                   getF32Constant(DAG, 0x3f949a29, dl));
5060     } else if (LimitFloatPrecision <= 12) {
5061       // For floating-point precision of 12:
5062       //
5063       //   LogOfMantissa =
5064       //     -1.7417939f +
5065       //       (2.8212026f +
5066       //         (-1.4699568f +
5067       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5068       //
5069       // error 0.000061011436, which is 14 bits
5070       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5071                                getF32Constant(DAG, 0xbd67b6d6, dl));
5072       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5073                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5074       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5075       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5076                                getF32Constant(DAG, 0x3fbc278b, dl));
5077       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5078       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5079                                getF32Constant(DAG, 0x40348e95, dl));
5080       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5081       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5082                                   getF32Constant(DAG, 0x3fdef31a, dl));
5083     } else { // LimitFloatPrecision <= 18
5084       // For floating-point precision of 18:
5085       //
5086       //   LogOfMantissa =
5087       //     -2.1072184f +
5088       //       (4.2372794f +
5089       //         (-3.7029485f +
5090       //           (2.2781945f +
5091       //             (-0.87823314f +
5092       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5093       //
5094       // error 0.0000023660568, which is better than 18 bits
5095       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5096                                getF32Constant(DAG, 0xbc91e5ac, dl));
5097       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5098                                getF32Constant(DAG, 0x3e4350aa, dl));
5099       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5100       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5101                                getF32Constant(DAG, 0x3f60d3e3, dl));
5102       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5103       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5104                                getF32Constant(DAG, 0x4011cdf0, dl));
5105       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5106       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5107                                getF32Constant(DAG, 0x406cfd1c, dl));
5108       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5109       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5110                                getF32Constant(DAG, 0x408797cb, dl));
5111       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5112       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5113                                   getF32Constant(DAG, 0x4006dcab, dl));
5114     }
5115 
5116     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5117   }
5118 
5119   // No special expansion.
5120   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5121 }
5122 
5123 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5124 /// limited-precision mode.
5125 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5126                           const TargetLowering &TLI, SDNodeFlags Flags) {
5127   // TODO: What fast-math-flags should be set on the floating-point nodes?
5128 
5129   if (Op.getValueType() == MVT::f32 &&
5130       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5131     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5132 
5133     // Get the exponent.
5134     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5135 
5136     // Get the significand and build it into a floating-point number with
5137     // exponent of 1.
5138     SDValue X = GetSignificand(DAG, Op1, dl);
5139 
5140     // Different possible minimax approximations of significand in
5141     // floating-point for various degrees of accuracy over [1,2].
5142     SDValue Log2ofMantissa;
5143     if (LimitFloatPrecision <= 6) {
5144       // For floating-point precision of 6:
5145       //
5146       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5147       //
5148       // error 0.0049451742, which is more than 7 bits
5149       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5150                                getF32Constant(DAG, 0xbeb08fe0, dl));
5151       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5152                                getF32Constant(DAG, 0x40019463, dl));
5153       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5154       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5155                                    getF32Constant(DAG, 0x3fd6633d, dl));
5156     } else if (LimitFloatPrecision <= 12) {
5157       // For floating-point precision of 12:
5158       //
5159       //   Log2ofMantissa =
5160       //     -2.51285454f +
5161       //       (4.07009056f +
5162       //         (-2.12067489f +
5163       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5164       //
5165       // error 0.0000876136000, which is better than 13 bits
5166       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5167                                getF32Constant(DAG, 0xbda7262e, dl));
5168       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5169                                getF32Constant(DAG, 0x3f25280b, dl));
5170       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5171       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5172                                getF32Constant(DAG, 0x4007b923, dl));
5173       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5174       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5175                                getF32Constant(DAG, 0x40823e2f, dl));
5176       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5177       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5178                                    getF32Constant(DAG, 0x4020d29c, dl));
5179     } else { // LimitFloatPrecision <= 18
5180       // For floating-point precision of 18:
5181       //
5182       //   Log2ofMantissa =
5183       //     -3.0400495f +
5184       //       (6.1129976f +
5185       //         (-5.3420409f +
5186       //           (3.2865683f +
5187       //             (-1.2669343f +
5188       //               (0.27515199f -
5189       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5190       //
5191       // error 0.0000018516, which is better than 18 bits
5192       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5193                                getF32Constant(DAG, 0xbcd2769e, dl));
5194       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5195                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5196       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5197       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5198                                getF32Constant(DAG, 0x3fa22ae7, dl));
5199       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5200       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5201                                getF32Constant(DAG, 0x40525723, dl));
5202       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5203       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5204                                getF32Constant(DAG, 0x40aaf200, dl));
5205       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5206       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5207                                getF32Constant(DAG, 0x40c39dad, dl));
5208       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5209       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5210                                    getF32Constant(DAG, 0x4042902c, dl));
5211     }
5212 
5213     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5214   }
5215 
5216   // No special expansion.
5217   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5218 }
5219 
5220 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5221 /// limited-precision mode.
5222 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5223                            const TargetLowering &TLI, SDNodeFlags Flags) {
5224   // TODO: What fast-math-flags should be set on the floating-point nodes?
5225 
5226   if (Op.getValueType() == MVT::f32 &&
5227       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5228     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5229 
5230     // Scale the exponent by log10(2) [0.30102999f].
5231     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5232     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5233                                         getF32Constant(DAG, 0x3e9a209a, dl));
5234 
5235     // Get the significand and build it into a floating-point number with
5236     // exponent of 1.
5237     SDValue X = GetSignificand(DAG, Op1, dl);
5238 
5239     SDValue Log10ofMantissa;
5240     if (LimitFloatPrecision <= 6) {
5241       // For floating-point precision of 6:
5242       //
5243       //   Log10ofMantissa =
5244       //     -0.50419619f +
5245       //       (0.60948995f - 0.10380950f * x) * x;
5246       //
5247       // error 0.0014886165, which is 6 bits
5248       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5249                                getF32Constant(DAG, 0xbdd49a13, dl));
5250       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5251                                getF32Constant(DAG, 0x3f1c0789, dl));
5252       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5253       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5254                                     getF32Constant(DAG, 0x3f011300, dl));
5255     } else if (LimitFloatPrecision <= 12) {
5256       // For floating-point precision of 12:
5257       //
5258       //   Log10ofMantissa =
5259       //     -0.64831180f +
5260       //       (0.91751397f +
5261       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5262       //
5263       // error 0.00019228036, which is better than 12 bits
5264       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5265                                getF32Constant(DAG, 0x3d431f31, dl));
5266       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5267                                getF32Constant(DAG, 0x3ea21fb2, dl));
5268       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5269       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5270                                getF32Constant(DAG, 0x3f6ae232, dl));
5271       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5272       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5273                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5274     } else { // LimitFloatPrecision <= 18
5275       // For floating-point precision of 18:
5276       //
5277       //   Log10ofMantissa =
5278       //     -0.84299375f +
5279       //       (1.5327582f +
5280       //         (-1.0688956f +
5281       //           (0.49102474f +
5282       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5283       //
5284       // error 0.0000037995730, which is better than 18 bits
5285       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5286                                getF32Constant(DAG, 0x3c5d51ce, dl));
5287       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5288                                getF32Constant(DAG, 0x3e00685a, dl));
5289       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5290       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5291                                getF32Constant(DAG, 0x3efb6798, dl));
5292       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5293       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5294                                getF32Constant(DAG, 0x3f88d192, dl));
5295       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5296       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5297                                getF32Constant(DAG, 0x3fc4316c, dl));
5298       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5299       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5300                                     getF32Constant(DAG, 0x3f57ce70, dl));
5301     }
5302 
5303     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5304   }
5305 
5306   // No special expansion.
5307   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5308 }
5309 
5310 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5311 /// limited-precision mode.
5312 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5313                           const TargetLowering &TLI, SDNodeFlags Flags) {
5314   if (Op.getValueType() == MVT::f32 &&
5315       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5316     return getLimitedPrecisionExp2(Op, dl, DAG);
5317 
5318   // No special expansion.
5319   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5320 }
5321 
5322 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5323 /// limited-precision mode with x == 10.0f.
5324 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5325                          SelectionDAG &DAG, const TargetLowering &TLI,
5326                          SDNodeFlags Flags) {
5327   bool IsExp10 = false;
5328   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5329       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5330     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5331       APFloat Ten(10.0f);
5332       IsExp10 = LHSC->isExactlyValue(Ten);
5333     }
5334   }
5335 
5336   // TODO: What fast-math-flags should be set on the FMUL node?
5337   if (IsExp10) {
5338     // Put the exponent in the right bit position for later addition to the
5339     // final result:
5340     //
5341     //   #define LOG2OF10 3.3219281f
5342     //   t0 = Op * LOG2OF10;
5343     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5344                              getF32Constant(DAG, 0x40549a78, dl));
5345     return getLimitedPrecisionExp2(t0, dl, DAG);
5346   }
5347 
5348   // No special expansion.
5349   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5350 }
5351 
5352 /// ExpandPowI - Expand a llvm.powi intrinsic.
5353 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5354                           SelectionDAG &DAG) {
5355   // If RHS is a constant, we can expand this out to a multiplication tree,
5356   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5357   // optimizing for size, we only want to do this if the expansion would produce
5358   // a small number of multiplies, otherwise we do the full expansion.
5359   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5360     // Get the exponent as a positive value.
5361     unsigned Val = RHSC->getSExtValue();
5362     if ((int)Val < 0) Val = -Val;
5363 
5364     // powi(x, 0) -> 1.0
5365     if (Val == 0)
5366       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5367 
5368     bool OptForSize = DAG.shouldOptForSize();
5369     if (!OptForSize ||
5370         // If optimizing for size, don't insert too many multiplies.
5371         // This inserts up to 5 multiplies.
5372         countPopulation(Val) + Log2_32(Val) < 7) {
5373       // We use the simple binary decomposition method to generate the multiply
5374       // sequence.  There are more optimal ways to do this (for example,
5375       // powi(x,15) generates one more multiply than it should), but this has
5376       // the benefit of being both really simple and much better than a libcall.
5377       SDValue Res;  // Logically starts equal to 1.0
5378       SDValue CurSquare = LHS;
5379       // TODO: Intrinsics should have fast-math-flags that propagate to these
5380       // nodes.
5381       while (Val) {
5382         if (Val & 1) {
5383           if (Res.getNode())
5384             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5385           else
5386             Res = CurSquare;  // 1.0*CurSquare.
5387         }
5388 
5389         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5390                                 CurSquare, CurSquare);
5391         Val >>= 1;
5392       }
5393 
5394       // If the original was negative, invert the result, producing 1/(x*x*x).
5395       if (RHSC->getSExtValue() < 0)
5396         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5397                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5398       return Res;
5399     }
5400   }
5401 
5402   // Otherwise, expand to a libcall.
5403   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5404 }
5405 
5406 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5407                             SDValue LHS, SDValue RHS, SDValue Scale,
5408                             SelectionDAG &DAG, const TargetLowering &TLI) {
5409   EVT VT = LHS.getValueType();
5410   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5411   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5412   LLVMContext &Ctx = *DAG.getContext();
5413 
5414   // If the type is legal but the operation isn't, this node might survive all
5415   // the way to operation legalization. If we end up there and we do not have
5416   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5417   // node.
5418 
5419   // Coax the legalizer into expanding the node during type legalization instead
5420   // by bumping the size by one bit. This will force it to Promote, enabling the
5421   // early expansion and avoiding the need to expand later.
5422 
5423   // We don't have to do this if Scale is 0; that can always be expanded, unless
5424   // it's a saturating signed operation. Those can experience true integer
5425   // division overflow, a case which we must avoid.
5426 
5427   // FIXME: We wouldn't have to do this (or any of the early
5428   // expansion/promotion) if it was possible to expand a libcall of an
5429   // illegal type during operation legalization. But it's not, so things
5430   // get a bit hacky.
5431   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5432   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5433       (TLI.isTypeLegal(VT) ||
5434        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5435     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5436         Opcode, VT, ScaleInt);
5437     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5438       EVT PromVT;
5439       if (VT.isScalarInteger())
5440         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5441       else if (VT.isVector()) {
5442         PromVT = VT.getVectorElementType();
5443         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5444         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5445       } else
5446         llvm_unreachable("Wrong VT for DIVFIX?");
5447       if (Signed) {
5448         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5449         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5450       } else {
5451         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5452         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5453       }
5454       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5455       // For saturating operations, we need to shift up the LHS to get the
5456       // proper saturation width, and then shift down again afterwards.
5457       if (Saturating)
5458         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5459                           DAG.getConstant(1, DL, ShiftTy));
5460       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5461       if (Saturating)
5462         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5463                           DAG.getConstant(1, DL, ShiftTy));
5464       return DAG.getZExtOrTrunc(Res, DL, VT);
5465     }
5466   }
5467 
5468   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5469 }
5470 
5471 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5472 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5473 static void
5474 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5475                      const SDValue &N) {
5476   switch (N.getOpcode()) {
5477   case ISD::CopyFromReg: {
5478     SDValue Op = N.getOperand(1);
5479     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5480                       Op.getValueType().getSizeInBits());
5481     return;
5482   }
5483   case ISD::BITCAST:
5484   case ISD::AssertZext:
5485   case ISD::AssertSext:
5486   case ISD::TRUNCATE:
5487     getUnderlyingArgRegs(Regs, N.getOperand(0));
5488     return;
5489   case ISD::BUILD_PAIR:
5490   case ISD::BUILD_VECTOR:
5491   case ISD::CONCAT_VECTORS:
5492     for (SDValue Op : N->op_values())
5493       getUnderlyingArgRegs(Regs, Op);
5494     return;
5495   default:
5496     return;
5497   }
5498 }
5499 
5500 /// If the DbgValueInst is a dbg_value of a function argument, create the
5501 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5502 /// instruction selection, they will be inserted to the entry BB.
5503 /// We don't currently support this for variadic dbg_values, as they shouldn't
5504 /// appear for function arguments or in the prologue.
5505 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5506     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5507     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5508   const Argument *Arg = dyn_cast<Argument>(V);
5509   if (!Arg)
5510     return false;
5511 
5512   MachineFunction &MF = DAG.getMachineFunction();
5513   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5514 
5515   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5516   // we've been asked to pursue.
5517   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5518                               bool Indirect) {
5519     if (Reg.isVirtual() && TM.Options.ValueTrackingVariableLocations) {
5520       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5521       // pointing at the VReg, which will be patched up later.
5522       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5523       auto MIB = BuildMI(MF, DL, Inst);
5524       MIB.addReg(Reg, RegState::Debug);
5525       MIB.addImm(0);
5526       MIB.addMetadata(Variable);
5527       auto *NewDIExpr = FragExpr;
5528       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5529       // the DIExpression.
5530       if (Indirect)
5531         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5532       MIB.addMetadata(NewDIExpr);
5533       return MIB;
5534     } else {
5535       // Create a completely standard DBG_VALUE.
5536       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5537       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5538     }
5539   };
5540 
5541   if (!IsDbgDeclare) {
5542     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5543     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5544     // the entry block.
5545     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5546     if (!IsInEntryBlock)
5547       return false;
5548 
5549     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5550     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5551     // variable that also is a param.
5552     //
5553     // Although, if we are at the top of the entry block already, we can still
5554     // emit using ArgDbgValue. This might catch some situations when the
5555     // dbg.value refers to an argument that isn't used in the entry block, so
5556     // any CopyToReg node would be optimized out and the only way to express
5557     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5558     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5559     // we should only emit as ArgDbgValue if the Variable is an argument to the
5560     // current function, and the dbg.value intrinsic is found in the entry
5561     // block.
5562     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5563         !DL->getInlinedAt();
5564     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5565     if (!IsInPrologue && !VariableIsFunctionInputArg)
5566       return false;
5567 
5568     // Here we assume that a function argument on IR level only can be used to
5569     // describe one input parameter on source level. If we for example have
5570     // source code like this
5571     //
5572     //    struct A { long x, y; };
5573     //    void foo(struct A a, long b) {
5574     //      ...
5575     //      b = a.x;
5576     //      ...
5577     //    }
5578     //
5579     // and IR like this
5580     //
5581     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5582     //  entry:
5583     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5584     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5585     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5586     //    ...
5587     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5588     //    ...
5589     //
5590     // then the last dbg.value is describing a parameter "b" using a value that
5591     // is an argument. But since we already has used %a1 to describe a parameter
5592     // we should not handle that last dbg.value here (that would result in an
5593     // incorrect hoisting of the DBG_VALUE to the function entry).
5594     // Notice that we allow one dbg.value per IR level argument, to accommodate
5595     // for the situation with fragments above.
5596     if (VariableIsFunctionInputArg) {
5597       unsigned ArgNo = Arg->getArgNo();
5598       if (ArgNo >= FuncInfo.DescribedArgs.size())
5599         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5600       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5601         return false;
5602       FuncInfo.DescribedArgs.set(ArgNo);
5603     }
5604   }
5605 
5606   bool IsIndirect = false;
5607   Optional<MachineOperand> Op;
5608   // Some arguments' frame index is recorded during argument lowering.
5609   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5610   if (FI != std::numeric_limits<int>::max())
5611     Op = MachineOperand::CreateFI(FI);
5612 
5613   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5614   if (!Op && N.getNode()) {
5615     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5616     Register Reg;
5617     if (ArgRegsAndSizes.size() == 1)
5618       Reg = ArgRegsAndSizes.front().first;
5619 
5620     if (Reg && Reg.isVirtual()) {
5621       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5622       Register PR = RegInfo.getLiveInPhysReg(Reg);
5623       if (PR)
5624         Reg = PR;
5625     }
5626     if (Reg) {
5627       Op = MachineOperand::CreateReg(Reg, false);
5628       IsIndirect = IsDbgDeclare;
5629     }
5630   }
5631 
5632   if (!Op && N.getNode()) {
5633     // Check if frame index is available.
5634     SDValue LCandidate = peekThroughBitcasts(N);
5635     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5636       if (FrameIndexSDNode *FINode =
5637           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5638         Op = MachineOperand::CreateFI(FINode->getIndex());
5639   }
5640 
5641   if (!Op) {
5642     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5643     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5644                                          SplitRegs) {
5645       unsigned Offset = 0;
5646       for (auto RegAndSize : SplitRegs) {
5647         // If the expression is already a fragment, the current register
5648         // offset+size might extend beyond the fragment. In this case, only
5649         // the register bits that are inside the fragment are relevant.
5650         int RegFragmentSizeInBits = RegAndSize.second;
5651         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5652           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5653           // The register is entirely outside the expression fragment,
5654           // so is irrelevant for debug info.
5655           if (Offset >= ExprFragmentSizeInBits)
5656             break;
5657           // The register is partially outside the expression fragment, only
5658           // the low bits within the fragment are relevant for debug info.
5659           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5660             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5661           }
5662         }
5663 
5664         auto FragmentExpr = DIExpression::createFragmentExpression(
5665             Expr, Offset, RegFragmentSizeInBits);
5666         Offset += RegAndSize.second;
5667         // If a valid fragment expression cannot be created, the variable's
5668         // correct value cannot be determined and so it is set as Undef.
5669         if (!FragmentExpr) {
5670           SDDbgValue *SDV = DAG.getConstantDbgValue(
5671               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5672           DAG.AddDbgValue(SDV, false);
5673           continue;
5674         }
5675         MachineInstr *NewMI =
5676             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
5677         FuncInfo.ArgDbgValues.push_back(NewMI);
5678       }
5679     };
5680 
5681     // Check if ValueMap has reg number.
5682     DenseMap<const Value *, Register>::const_iterator
5683       VMI = FuncInfo.ValueMap.find(V);
5684     if (VMI != FuncInfo.ValueMap.end()) {
5685       const auto &TLI = DAG.getTargetLoweringInfo();
5686       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5687                        V->getType(), None);
5688       if (RFV.occupiesMultipleRegs()) {
5689         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5690         return true;
5691       }
5692 
5693       Op = MachineOperand::CreateReg(VMI->second, false);
5694       IsIndirect = IsDbgDeclare;
5695     } else if (ArgRegsAndSizes.size() > 1) {
5696       // This was split due to the calling convention, and no virtual register
5697       // mapping exists for the value.
5698       splitMultiRegDbgValue(ArgRegsAndSizes);
5699       return true;
5700     }
5701   }
5702 
5703   if (!Op)
5704     return false;
5705 
5706   assert(Variable->isValidLocationForIntrinsic(DL) &&
5707          "Expected inlined-at fields to agree");
5708   MachineInstr *NewMI = nullptr;
5709 
5710   if (Op->isReg())
5711     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5712   else
5713     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5714                     Variable, Expr);
5715 
5716   FuncInfo.ArgDbgValues.push_back(NewMI);
5717   return true;
5718 }
5719 
5720 /// Return the appropriate SDDbgValue based on N.
5721 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5722                                              DILocalVariable *Variable,
5723                                              DIExpression *Expr,
5724                                              const DebugLoc &dl,
5725                                              unsigned DbgSDNodeOrder) {
5726   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5727     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5728     // stack slot locations.
5729     //
5730     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5731     // debug values here after optimization:
5732     //
5733     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5734     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5735     //
5736     // Both describe the direct values of their associated variables.
5737     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5738                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5739   }
5740   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5741                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5742 }
5743 
5744 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5745   switch (Intrinsic) {
5746   case Intrinsic::smul_fix:
5747     return ISD::SMULFIX;
5748   case Intrinsic::umul_fix:
5749     return ISD::UMULFIX;
5750   case Intrinsic::smul_fix_sat:
5751     return ISD::SMULFIXSAT;
5752   case Intrinsic::umul_fix_sat:
5753     return ISD::UMULFIXSAT;
5754   case Intrinsic::sdiv_fix:
5755     return ISD::SDIVFIX;
5756   case Intrinsic::udiv_fix:
5757     return ISD::UDIVFIX;
5758   case Intrinsic::sdiv_fix_sat:
5759     return ISD::SDIVFIXSAT;
5760   case Intrinsic::udiv_fix_sat:
5761     return ISD::UDIVFIXSAT;
5762   default:
5763     llvm_unreachable("Unhandled fixed point intrinsic");
5764   }
5765 }
5766 
5767 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5768                                            const char *FunctionName) {
5769   assert(FunctionName && "FunctionName must not be nullptr");
5770   SDValue Callee = DAG.getExternalSymbol(
5771       FunctionName,
5772       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5773   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5774 }
5775 
5776 /// Given a @llvm.call.preallocated.setup, return the corresponding
5777 /// preallocated call.
5778 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5779   assert(cast<CallBase>(PreallocatedSetup)
5780                  ->getCalledFunction()
5781                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5782          "expected call_preallocated_setup Value");
5783   for (auto *U : PreallocatedSetup->users()) {
5784     auto *UseCall = cast<CallBase>(U);
5785     const Function *Fn = UseCall->getCalledFunction();
5786     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5787       return UseCall;
5788     }
5789   }
5790   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5791 }
5792 
5793 /// Lower the call to the specified intrinsic function.
5794 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5795                                              unsigned Intrinsic) {
5796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5797   SDLoc sdl = getCurSDLoc();
5798   DebugLoc dl = getCurDebugLoc();
5799   SDValue Res;
5800 
5801   SDNodeFlags Flags;
5802   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5803     Flags.copyFMF(*FPOp);
5804 
5805   switch (Intrinsic) {
5806   default:
5807     // By default, turn this into a target intrinsic node.
5808     visitTargetIntrinsic(I, Intrinsic);
5809     return;
5810   case Intrinsic::vscale: {
5811     match(&I, m_VScale(DAG.getDataLayout()));
5812     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5813     setValue(&I,
5814              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5815     return;
5816   }
5817   case Intrinsic::vastart:  visitVAStart(I); return;
5818   case Intrinsic::vaend:    visitVAEnd(I); return;
5819   case Intrinsic::vacopy:   visitVACopy(I); return;
5820   case Intrinsic::returnaddress:
5821     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5822                              TLI.getPointerTy(DAG.getDataLayout()),
5823                              getValue(I.getArgOperand(0))));
5824     return;
5825   case Intrinsic::addressofreturnaddress:
5826     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5827                              TLI.getPointerTy(DAG.getDataLayout())));
5828     return;
5829   case Intrinsic::sponentry:
5830     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5831                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5832     return;
5833   case Intrinsic::frameaddress:
5834     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5835                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5836                              getValue(I.getArgOperand(0))));
5837     return;
5838   case Intrinsic::read_volatile_register:
5839   case Intrinsic::read_register: {
5840     Value *Reg = I.getArgOperand(0);
5841     SDValue Chain = getRoot();
5842     SDValue RegName =
5843         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5844     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5845     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5846       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5847     setValue(&I, Res);
5848     DAG.setRoot(Res.getValue(1));
5849     return;
5850   }
5851   case Intrinsic::write_register: {
5852     Value *Reg = I.getArgOperand(0);
5853     Value *RegValue = I.getArgOperand(1);
5854     SDValue Chain = getRoot();
5855     SDValue RegName =
5856         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5857     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5858                             RegName, getValue(RegValue)));
5859     return;
5860   }
5861   case Intrinsic::memcpy: {
5862     const auto &MCI = cast<MemCpyInst>(I);
5863     SDValue Op1 = getValue(I.getArgOperand(0));
5864     SDValue Op2 = getValue(I.getArgOperand(1));
5865     SDValue Op3 = getValue(I.getArgOperand(2));
5866     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5867     Align DstAlign = MCI.getDestAlign().valueOrOne();
5868     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5869     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5870     bool isVol = MCI.isVolatile();
5871     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5872     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5873     // node.
5874     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5875     AAMDNodes AAInfo;
5876     I.getAAMetadata(AAInfo);
5877     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5878                                /* AlwaysInline */ false, isTC,
5879                                MachinePointerInfo(I.getArgOperand(0)),
5880                                MachinePointerInfo(I.getArgOperand(1)), AAInfo);
5881     updateDAGForMaybeTailCall(MC);
5882     return;
5883   }
5884   case Intrinsic::memcpy_inline: {
5885     const auto &MCI = cast<MemCpyInlineInst>(I);
5886     SDValue Dst = getValue(I.getArgOperand(0));
5887     SDValue Src = getValue(I.getArgOperand(1));
5888     SDValue Size = getValue(I.getArgOperand(2));
5889     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5890     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5891     Align DstAlign = MCI.getDestAlign().valueOrOne();
5892     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5893     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5894     bool isVol = MCI.isVolatile();
5895     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5896     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5897     // node.
5898     AAMDNodes AAInfo;
5899     I.getAAMetadata(AAInfo);
5900     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5901                                /* AlwaysInline */ true, isTC,
5902                                MachinePointerInfo(I.getArgOperand(0)),
5903                                MachinePointerInfo(I.getArgOperand(1)), AAInfo);
5904     updateDAGForMaybeTailCall(MC);
5905     return;
5906   }
5907   case Intrinsic::memset: {
5908     const auto &MSI = cast<MemSetInst>(I);
5909     SDValue Op1 = getValue(I.getArgOperand(0));
5910     SDValue Op2 = getValue(I.getArgOperand(1));
5911     SDValue Op3 = getValue(I.getArgOperand(2));
5912     // @llvm.memset defines 0 and 1 to both mean no alignment.
5913     Align Alignment = MSI.getDestAlign().valueOrOne();
5914     bool isVol = MSI.isVolatile();
5915     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5916     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5917     AAMDNodes AAInfo;
5918     I.getAAMetadata(AAInfo);
5919     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5920                                MachinePointerInfo(I.getArgOperand(0)), AAInfo);
5921     updateDAGForMaybeTailCall(MS);
5922     return;
5923   }
5924   case Intrinsic::memmove: {
5925     const auto &MMI = cast<MemMoveInst>(I);
5926     SDValue Op1 = getValue(I.getArgOperand(0));
5927     SDValue Op2 = getValue(I.getArgOperand(1));
5928     SDValue Op3 = getValue(I.getArgOperand(2));
5929     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5930     Align DstAlign = MMI.getDestAlign().valueOrOne();
5931     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5932     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5933     bool isVol = MMI.isVolatile();
5934     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5935     // FIXME: Support passing different dest/src alignments to the memmove DAG
5936     // node.
5937     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5938     AAMDNodes AAInfo;
5939     I.getAAMetadata(AAInfo);
5940     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5941                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5942                                 MachinePointerInfo(I.getArgOperand(1)), AAInfo);
5943     updateDAGForMaybeTailCall(MM);
5944     return;
5945   }
5946   case Intrinsic::memcpy_element_unordered_atomic: {
5947     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5948     SDValue Dst = getValue(MI.getRawDest());
5949     SDValue Src = getValue(MI.getRawSource());
5950     SDValue Length = getValue(MI.getLength());
5951 
5952     unsigned DstAlign = MI.getDestAlignment();
5953     unsigned SrcAlign = MI.getSourceAlignment();
5954     Type *LengthTy = MI.getLength()->getType();
5955     unsigned ElemSz = MI.getElementSizeInBytes();
5956     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5957     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5958                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5959                                      MachinePointerInfo(MI.getRawDest()),
5960                                      MachinePointerInfo(MI.getRawSource()));
5961     updateDAGForMaybeTailCall(MC);
5962     return;
5963   }
5964   case Intrinsic::memmove_element_unordered_atomic: {
5965     auto &MI = cast<AtomicMemMoveInst>(I);
5966     SDValue Dst = getValue(MI.getRawDest());
5967     SDValue Src = getValue(MI.getRawSource());
5968     SDValue Length = getValue(MI.getLength());
5969 
5970     unsigned DstAlign = MI.getDestAlignment();
5971     unsigned SrcAlign = MI.getSourceAlignment();
5972     Type *LengthTy = MI.getLength()->getType();
5973     unsigned ElemSz = MI.getElementSizeInBytes();
5974     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5975     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5976                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5977                                       MachinePointerInfo(MI.getRawDest()),
5978                                       MachinePointerInfo(MI.getRawSource()));
5979     updateDAGForMaybeTailCall(MC);
5980     return;
5981   }
5982   case Intrinsic::memset_element_unordered_atomic: {
5983     auto &MI = cast<AtomicMemSetInst>(I);
5984     SDValue Dst = getValue(MI.getRawDest());
5985     SDValue Val = getValue(MI.getValue());
5986     SDValue Length = getValue(MI.getLength());
5987 
5988     unsigned DstAlign = MI.getDestAlignment();
5989     Type *LengthTy = MI.getLength()->getType();
5990     unsigned ElemSz = MI.getElementSizeInBytes();
5991     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5992     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5993                                      LengthTy, ElemSz, isTC,
5994                                      MachinePointerInfo(MI.getRawDest()));
5995     updateDAGForMaybeTailCall(MC);
5996     return;
5997   }
5998   case Intrinsic::call_preallocated_setup: {
5999     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6000     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6001     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6002                               getRoot(), SrcValue);
6003     setValue(&I, Res);
6004     DAG.setRoot(Res);
6005     return;
6006   }
6007   case Intrinsic::call_preallocated_arg: {
6008     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6009     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6010     SDValue Ops[3];
6011     Ops[0] = getRoot();
6012     Ops[1] = SrcValue;
6013     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6014                                    MVT::i32); // arg index
6015     SDValue Res = DAG.getNode(
6016         ISD::PREALLOCATED_ARG, sdl,
6017         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6018     setValue(&I, Res);
6019     DAG.setRoot(Res.getValue(1));
6020     return;
6021   }
6022   case Intrinsic::dbg_addr:
6023   case Intrinsic::dbg_declare: {
6024     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6025     // they are non-variadic.
6026     const auto &DI = cast<DbgVariableIntrinsic>(I);
6027     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6028     DILocalVariable *Variable = DI.getVariable();
6029     DIExpression *Expression = DI.getExpression();
6030     dropDanglingDebugInfo(Variable, Expression);
6031     assert(Variable && "Missing variable");
6032     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6033                       << "\n");
6034     // Check if address has undef value.
6035     const Value *Address = DI.getVariableLocationOp(0);
6036     if (!Address || isa<UndefValue>(Address) ||
6037         (Address->use_empty() && !isa<Argument>(Address))) {
6038       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6039                         << " (bad/undef/unused-arg address)\n");
6040       return;
6041     }
6042 
6043     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6044 
6045     // Check if this variable can be described by a frame index, typically
6046     // either as a static alloca or a byval parameter.
6047     int FI = std::numeric_limits<int>::max();
6048     if (const auto *AI =
6049             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6050       if (AI->isStaticAlloca()) {
6051         auto I = FuncInfo.StaticAllocaMap.find(AI);
6052         if (I != FuncInfo.StaticAllocaMap.end())
6053           FI = I->second;
6054       }
6055     } else if (const auto *Arg = dyn_cast<Argument>(
6056                    Address->stripInBoundsConstantOffsets())) {
6057       FI = FuncInfo.getArgumentFrameIndex(Arg);
6058     }
6059 
6060     // llvm.dbg.addr is control dependent and always generates indirect
6061     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6062     // the MachineFunction variable table.
6063     if (FI != std::numeric_limits<int>::max()) {
6064       if (Intrinsic == Intrinsic::dbg_addr) {
6065         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6066             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6067             dl, SDNodeOrder);
6068         DAG.AddDbgValue(SDV, isParameter);
6069       } else {
6070         LLVM_DEBUG(dbgs() << "Skipping " << DI
6071                           << " (variable info stashed in MF side table)\n");
6072       }
6073       return;
6074     }
6075 
6076     SDValue &N = NodeMap[Address];
6077     if (!N.getNode() && isa<Argument>(Address))
6078       // Check unused arguments map.
6079       N = UnusedArgNodeMap[Address];
6080     SDDbgValue *SDV;
6081     if (N.getNode()) {
6082       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6083         Address = BCI->getOperand(0);
6084       // Parameters are handled specially.
6085       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6086       if (isParameter && FINode) {
6087         // Byval parameter. We have a frame index at this point.
6088         SDV =
6089             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6090                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6091       } else if (isa<Argument>(Address)) {
6092         // Address is an argument, so try to emit its dbg value using
6093         // virtual register info from the FuncInfo.ValueMap.
6094         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6095         return;
6096       } else {
6097         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6098                               true, dl, SDNodeOrder);
6099       }
6100       DAG.AddDbgValue(SDV, isParameter);
6101     } else {
6102       // If Address is an argument then try to emit its dbg value using
6103       // virtual register info from the FuncInfo.ValueMap.
6104       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6105                                     N)) {
6106         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6107                           << " (could not emit func-arg dbg_value)\n");
6108       }
6109     }
6110     return;
6111   }
6112   case Intrinsic::dbg_label: {
6113     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6114     DILabel *Label = DI.getLabel();
6115     assert(Label && "Missing label");
6116 
6117     SDDbgLabel *SDV;
6118     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6119     DAG.AddDbgLabel(SDV);
6120     return;
6121   }
6122   case Intrinsic::dbg_value: {
6123     const DbgValueInst &DI = cast<DbgValueInst>(I);
6124     assert(DI.getVariable() && "Missing variable");
6125 
6126     DILocalVariable *Variable = DI.getVariable();
6127     DIExpression *Expression = DI.getExpression();
6128     dropDanglingDebugInfo(Variable, Expression);
6129     SmallVector<Value *, 4> Values(DI.getValues());
6130     if (Values.empty())
6131       return;
6132 
6133     if (std::count(Values.begin(), Values.end(), nullptr))
6134       return;
6135 
6136     bool IsVariadic = DI.hasArgList();
6137     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6138                           SDNodeOrder, IsVariadic))
6139       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6140     return;
6141   }
6142 
6143   case Intrinsic::eh_typeid_for: {
6144     // Find the type id for the given typeinfo.
6145     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6146     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6147     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6148     setValue(&I, Res);
6149     return;
6150   }
6151 
6152   case Intrinsic::eh_return_i32:
6153   case Intrinsic::eh_return_i64:
6154     DAG.getMachineFunction().setCallsEHReturn(true);
6155     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6156                             MVT::Other,
6157                             getControlRoot(),
6158                             getValue(I.getArgOperand(0)),
6159                             getValue(I.getArgOperand(1))));
6160     return;
6161   case Intrinsic::eh_unwind_init:
6162     DAG.getMachineFunction().setCallsUnwindInit(true);
6163     return;
6164   case Intrinsic::eh_dwarf_cfa:
6165     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6166                              TLI.getPointerTy(DAG.getDataLayout()),
6167                              getValue(I.getArgOperand(0))));
6168     return;
6169   case Intrinsic::eh_sjlj_callsite: {
6170     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6171     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6172     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6173     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6174 
6175     MMI.setCurrentCallSite(CI->getZExtValue());
6176     return;
6177   }
6178   case Intrinsic::eh_sjlj_functioncontext: {
6179     // Get and store the index of the function context.
6180     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6181     AllocaInst *FnCtx =
6182       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6183     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6184     MFI.setFunctionContextIndex(FI);
6185     return;
6186   }
6187   case Intrinsic::eh_sjlj_setjmp: {
6188     SDValue Ops[2];
6189     Ops[0] = getRoot();
6190     Ops[1] = getValue(I.getArgOperand(0));
6191     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6192                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6193     setValue(&I, Op.getValue(0));
6194     DAG.setRoot(Op.getValue(1));
6195     return;
6196   }
6197   case Intrinsic::eh_sjlj_longjmp:
6198     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6199                             getRoot(), getValue(I.getArgOperand(0))));
6200     return;
6201   case Intrinsic::eh_sjlj_setup_dispatch:
6202     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6203                             getRoot()));
6204     return;
6205   case Intrinsic::masked_gather:
6206     visitMaskedGather(I);
6207     return;
6208   case Intrinsic::masked_load:
6209     visitMaskedLoad(I);
6210     return;
6211   case Intrinsic::masked_scatter:
6212     visitMaskedScatter(I);
6213     return;
6214   case Intrinsic::masked_store:
6215     visitMaskedStore(I);
6216     return;
6217   case Intrinsic::masked_expandload:
6218     visitMaskedLoad(I, true /* IsExpanding */);
6219     return;
6220   case Intrinsic::masked_compressstore:
6221     visitMaskedStore(I, true /* IsCompressing */);
6222     return;
6223   case Intrinsic::powi:
6224     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6225                             getValue(I.getArgOperand(1)), DAG));
6226     return;
6227   case Intrinsic::log:
6228     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6229     return;
6230   case Intrinsic::log2:
6231     setValue(&I,
6232              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6233     return;
6234   case Intrinsic::log10:
6235     setValue(&I,
6236              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6237     return;
6238   case Intrinsic::exp:
6239     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6240     return;
6241   case Intrinsic::exp2:
6242     setValue(&I,
6243              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6244     return;
6245   case Intrinsic::pow:
6246     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6247                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6248     return;
6249   case Intrinsic::sqrt:
6250   case Intrinsic::fabs:
6251   case Intrinsic::sin:
6252   case Intrinsic::cos:
6253   case Intrinsic::floor:
6254   case Intrinsic::ceil:
6255   case Intrinsic::trunc:
6256   case Intrinsic::rint:
6257   case Intrinsic::nearbyint:
6258   case Intrinsic::round:
6259   case Intrinsic::roundeven:
6260   case Intrinsic::canonicalize: {
6261     unsigned Opcode;
6262     switch (Intrinsic) {
6263     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6264     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6265     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6266     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6267     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6268     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6269     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6270     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6271     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6272     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6273     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6274     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6275     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6276     }
6277 
6278     setValue(&I, DAG.getNode(Opcode, sdl,
6279                              getValue(I.getArgOperand(0)).getValueType(),
6280                              getValue(I.getArgOperand(0)), Flags));
6281     return;
6282   }
6283   case Intrinsic::lround:
6284   case Intrinsic::llround:
6285   case Intrinsic::lrint:
6286   case Intrinsic::llrint: {
6287     unsigned Opcode;
6288     switch (Intrinsic) {
6289     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6290     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6291     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6292     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6293     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6294     }
6295 
6296     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6297     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6298                              getValue(I.getArgOperand(0))));
6299     return;
6300   }
6301   case Intrinsic::minnum:
6302     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6303                              getValue(I.getArgOperand(0)).getValueType(),
6304                              getValue(I.getArgOperand(0)),
6305                              getValue(I.getArgOperand(1)), Flags));
6306     return;
6307   case Intrinsic::maxnum:
6308     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6309                              getValue(I.getArgOperand(0)).getValueType(),
6310                              getValue(I.getArgOperand(0)),
6311                              getValue(I.getArgOperand(1)), Flags));
6312     return;
6313   case Intrinsic::minimum:
6314     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6315                              getValue(I.getArgOperand(0)).getValueType(),
6316                              getValue(I.getArgOperand(0)),
6317                              getValue(I.getArgOperand(1)), Flags));
6318     return;
6319   case Intrinsic::maximum:
6320     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6321                              getValue(I.getArgOperand(0)).getValueType(),
6322                              getValue(I.getArgOperand(0)),
6323                              getValue(I.getArgOperand(1)), Flags));
6324     return;
6325   case Intrinsic::copysign:
6326     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6327                              getValue(I.getArgOperand(0)).getValueType(),
6328                              getValue(I.getArgOperand(0)),
6329                              getValue(I.getArgOperand(1)), Flags));
6330     return;
6331   case Intrinsic::arithmetic_fence: {
6332     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6333                              getValue(I.getArgOperand(0)).getValueType(),
6334                              getValue(I.getArgOperand(0)), Flags));
6335     return;
6336   }
6337   case Intrinsic::fma:
6338     setValue(&I, DAG.getNode(
6339                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6340                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6341                      getValue(I.getArgOperand(2)), Flags));
6342     return;
6343 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6344   case Intrinsic::INTRINSIC:
6345 #include "llvm/IR/ConstrainedOps.def"
6346     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6347     return;
6348 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6349 #include "llvm/IR/VPIntrinsics.def"
6350     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6351     return;
6352   case Intrinsic::fmuladd: {
6353     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6354     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6355         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6356       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6357                                getValue(I.getArgOperand(0)).getValueType(),
6358                                getValue(I.getArgOperand(0)),
6359                                getValue(I.getArgOperand(1)),
6360                                getValue(I.getArgOperand(2)), Flags));
6361     } else {
6362       // TODO: Intrinsic calls should have fast-math-flags.
6363       SDValue Mul = DAG.getNode(
6364           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6365           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6366       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6367                                 getValue(I.getArgOperand(0)).getValueType(),
6368                                 Mul, getValue(I.getArgOperand(2)), Flags);
6369       setValue(&I, Add);
6370     }
6371     return;
6372   }
6373   case Intrinsic::convert_to_fp16:
6374     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6375                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6376                                          getValue(I.getArgOperand(0)),
6377                                          DAG.getTargetConstant(0, sdl,
6378                                                                MVT::i32))));
6379     return;
6380   case Intrinsic::convert_from_fp16:
6381     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6382                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6383                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6384                                          getValue(I.getArgOperand(0)))));
6385     return;
6386   case Intrinsic::fptosi_sat: {
6387     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6388     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6389                              getValue(I.getArgOperand(0)),
6390                              DAG.getValueType(VT.getScalarType())));
6391     return;
6392   }
6393   case Intrinsic::fptoui_sat: {
6394     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6395     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6396                              getValue(I.getArgOperand(0)),
6397                              DAG.getValueType(VT.getScalarType())));
6398     return;
6399   }
6400   case Intrinsic::set_rounding:
6401     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6402                       {getRoot(), getValue(I.getArgOperand(0))});
6403     setValue(&I, Res);
6404     DAG.setRoot(Res.getValue(0));
6405     return;
6406   case Intrinsic::pcmarker: {
6407     SDValue Tmp = getValue(I.getArgOperand(0));
6408     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6409     return;
6410   }
6411   case Intrinsic::isnan: {
6412     const DataLayout DLayout = DAG.getDataLayout();
6413     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6414     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6415     MachineFunction &MF = DAG.getMachineFunction();
6416     const Function &F = MF.getFunction();
6417     SDValue Op = getValue(I.getArgOperand(0));
6418     SDNodeFlags Flags;
6419     Flags.setNoFPExcept(
6420         !F.getAttributes().hasFnAttribute(llvm::Attribute::StrictFP));
6421 
6422     // If ISD::ISNAN should be expanded, do it right now, because the expansion
6423     // can use illegal types. Making expansion early allows to legalize these
6424     // types prior to selection.
6425     if (!TLI.isOperationLegalOrCustom(ISD::ISNAN, ArgVT)) {
6426       SDValue Result = TLI.expandISNAN(DestVT, Op, Flags, sdl, DAG);
6427       setValue(&I, Result);
6428       return;
6429     }
6430 
6431     SDValue V = DAG.getNode(ISD::ISNAN, sdl, DestVT, Op, Flags);
6432     setValue(&I, V);
6433     return;
6434   }
6435   case Intrinsic::readcyclecounter: {
6436     SDValue Op = getRoot();
6437     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6438                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6439     setValue(&I, Res);
6440     DAG.setRoot(Res.getValue(1));
6441     return;
6442   }
6443   case Intrinsic::bitreverse:
6444     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6445                              getValue(I.getArgOperand(0)).getValueType(),
6446                              getValue(I.getArgOperand(0))));
6447     return;
6448   case Intrinsic::bswap:
6449     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6450                              getValue(I.getArgOperand(0)).getValueType(),
6451                              getValue(I.getArgOperand(0))));
6452     return;
6453   case Intrinsic::cttz: {
6454     SDValue Arg = getValue(I.getArgOperand(0));
6455     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6456     EVT Ty = Arg.getValueType();
6457     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6458                              sdl, Ty, Arg));
6459     return;
6460   }
6461   case Intrinsic::ctlz: {
6462     SDValue Arg = getValue(I.getArgOperand(0));
6463     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6464     EVT Ty = Arg.getValueType();
6465     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6466                              sdl, Ty, Arg));
6467     return;
6468   }
6469   case Intrinsic::ctpop: {
6470     SDValue Arg = getValue(I.getArgOperand(0));
6471     EVT Ty = Arg.getValueType();
6472     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6473     return;
6474   }
6475   case Intrinsic::fshl:
6476   case Intrinsic::fshr: {
6477     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6478     SDValue X = getValue(I.getArgOperand(0));
6479     SDValue Y = getValue(I.getArgOperand(1));
6480     SDValue Z = getValue(I.getArgOperand(2));
6481     EVT VT = X.getValueType();
6482 
6483     if (X == Y) {
6484       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6485       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6486     } else {
6487       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6488       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6489     }
6490     return;
6491   }
6492   case Intrinsic::sadd_sat: {
6493     SDValue Op1 = getValue(I.getArgOperand(0));
6494     SDValue Op2 = getValue(I.getArgOperand(1));
6495     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6496     return;
6497   }
6498   case Intrinsic::uadd_sat: {
6499     SDValue Op1 = getValue(I.getArgOperand(0));
6500     SDValue Op2 = getValue(I.getArgOperand(1));
6501     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6502     return;
6503   }
6504   case Intrinsic::ssub_sat: {
6505     SDValue Op1 = getValue(I.getArgOperand(0));
6506     SDValue Op2 = getValue(I.getArgOperand(1));
6507     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6508     return;
6509   }
6510   case Intrinsic::usub_sat: {
6511     SDValue Op1 = getValue(I.getArgOperand(0));
6512     SDValue Op2 = getValue(I.getArgOperand(1));
6513     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6514     return;
6515   }
6516   case Intrinsic::sshl_sat: {
6517     SDValue Op1 = getValue(I.getArgOperand(0));
6518     SDValue Op2 = getValue(I.getArgOperand(1));
6519     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6520     return;
6521   }
6522   case Intrinsic::ushl_sat: {
6523     SDValue Op1 = getValue(I.getArgOperand(0));
6524     SDValue Op2 = getValue(I.getArgOperand(1));
6525     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6526     return;
6527   }
6528   case Intrinsic::smul_fix:
6529   case Intrinsic::umul_fix:
6530   case Intrinsic::smul_fix_sat:
6531   case Intrinsic::umul_fix_sat: {
6532     SDValue Op1 = getValue(I.getArgOperand(0));
6533     SDValue Op2 = getValue(I.getArgOperand(1));
6534     SDValue Op3 = getValue(I.getArgOperand(2));
6535     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6536                              Op1.getValueType(), Op1, Op2, Op3));
6537     return;
6538   }
6539   case Intrinsic::sdiv_fix:
6540   case Intrinsic::udiv_fix:
6541   case Intrinsic::sdiv_fix_sat:
6542   case Intrinsic::udiv_fix_sat: {
6543     SDValue Op1 = getValue(I.getArgOperand(0));
6544     SDValue Op2 = getValue(I.getArgOperand(1));
6545     SDValue Op3 = getValue(I.getArgOperand(2));
6546     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6547                               Op1, Op2, Op3, DAG, TLI));
6548     return;
6549   }
6550   case Intrinsic::smax: {
6551     SDValue Op1 = getValue(I.getArgOperand(0));
6552     SDValue Op2 = getValue(I.getArgOperand(1));
6553     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6554     return;
6555   }
6556   case Intrinsic::smin: {
6557     SDValue Op1 = getValue(I.getArgOperand(0));
6558     SDValue Op2 = getValue(I.getArgOperand(1));
6559     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6560     return;
6561   }
6562   case Intrinsic::umax: {
6563     SDValue Op1 = getValue(I.getArgOperand(0));
6564     SDValue Op2 = getValue(I.getArgOperand(1));
6565     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6566     return;
6567   }
6568   case Intrinsic::umin: {
6569     SDValue Op1 = getValue(I.getArgOperand(0));
6570     SDValue Op2 = getValue(I.getArgOperand(1));
6571     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6572     return;
6573   }
6574   case Intrinsic::abs: {
6575     // TODO: Preserve "int min is poison" arg in SDAG?
6576     SDValue Op1 = getValue(I.getArgOperand(0));
6577     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6578     return;
6579   }
6580   case Intrinsic::stacksave: {
6581     SDValue Op = getRoot();
6582     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6583     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6584     setValue(&I, Res);
6585     DAG.setRoot(Res.getValue(1));
6586     return;
6587   }
6588   case Intrinsic::stackrestore:
6589     Res = getValue(I.getArgOperand(0));
6590     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6591     return;
6592   case Intrinsic::get_dynamic_area_offset: {
6593     SDValue Op = getRoot();
6594     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6595     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6596     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6597     // target.
6598     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6599       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6600                          " intrinsic!");
6601     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6602                       Op);
6603     DAG.setRoot(Op);
6604     setValue(&I, Res);
6605     return;
6606   }
6607   case Intrinsic::stackguard: {
6608     MachineFunction &MF = DAG.getMachineFunction();
6609     const Module &M = *MF.getFunction().getParent();
6610     SDValue Chain = getRoot();
6611     if (TLI.useLoadStackGuardNode()) {
6612       Res = getLoadStackGuard(DAG, sdl, Chain);
6613     } else {
6614       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6615       const Value *Global = TLI.getSDagStackGuard(M);
6616       Align Align = DL->getPrefTypeAlign(Global->getType());
6617       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6618                         MachinePointerInfo(Global, 0), Align,
6619                         MachineMemOperand::MOVolatile);
6620     }
6621     if (TLI.useStackGuardXorFP())
6622       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6623     DAG.setRoot(Chain);
6624     setValue(&I, Res);
6625     return;
6626   }
6627   case Intrinsic::stackprotector: {
6628     // Emit code into the DAG to store the stack guard onto the stack.
6629     MachineFunction &MF = DAG.getMachineFunction();
6630     MachineFrameInfo &MFI = MF.getFrameInfo();
6631     SDValue Src, Chain = getRoot();
6632 
6633     if (TLI.useLoadStackGuardNode())
6634       Src = getLoadStackGuard(DAG, sdl, Chain);
6635     else
6636       Src = getValue(I.getArgOperand(0));   // The guard's value.
6637 
6638     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6639 
6640     int FI = FuncInfo.StaticAllocaMap[Slot];
6641     MFI.setStackProtectorIndex(FI);
6642     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6643 
6644     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6645 
6646     // Store the stack protector onto the stack.
6647     Res = DAG.getStore(
6648         Chain, sdl, Src, FIN,
6649         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6650         MaybeAlign(), MachineMemOperand::MOVolatile);
6651     setValue(&I, Res);
6652     DAG.setRoot(Res);
6653     return;
6654   }
6655   case Intrinsic::objectsize:
6656     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6657 
6658   case Intrinsic::is_constant:
6659     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6660 
6661   case Intrinsic::annotation:
6662   case Intrinsic::ptr_annotation:
6663   case Intrinsic::launder_invariant_group:
6664   case Intrinsic::strip_invariant_group:
6665     // Drop the intrinsic, but forward the value
6666     setValue(&I, getValue(I.getOperand(0)));
6667     return;
6668 
6669   case Intrinsic::assume:
6670   case Intrinsic::experimental_noalias_scope_decl:
6671   case Intrinsic::var_annotation:
6672   case Intrinsic::sideeffect:
6673     // Discard annotate attributes, noalias scope declarations, assumptions, and
6674     // artificial side-effects.
6675     return;
6676 
6677   case Intrinsic::codeview_annotation: {
6678     // Emit a label associated with this metadata.
6679     MachineFunction &MF = DAG.getMachineFunction();
6680     MCSymbol *Label =
6681         MF.getMMI().getContext().createTempSymbol("annotation", true);
6682     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6683     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6684     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6685     DAG.setRoot(Res);
6686     return;
6687   }
6688 
6689   case Intrinsic::init_trampoline: {
6690     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6691 
6692     SDValue Ops[6];
6693     Ops[0] = getRoot();
6694     Ops[1] = getValue(I.getArgOperand(0));
6695     Ops[2] = getValue(I.getArgOperand(1));
6696     Ops[3] = getValue(I.getArgOperand(2));
6697     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6698     Ops[5] = DAG.getSrcValue(F);
6699 
6700     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6701 
6702     DAG.setRoot(Res);
6703     return;
6704   }
6705   case Intrinsic::adjust_trampoline:
6706     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6707                              TLI.getPointerTy(DAG.getDataLayout()),
6708                              getValue(I.getArgOperand(0))));
6709     return;
6710   case Intrinsic::gcroot: {
6711     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6712            "only valid in functions with gc specified, enforced by Verifier");
6713     assert(GFI && "implied by previous");
6714     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6715     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6716 
6717     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6718     GFI->addStackRoot(FI->getIndex(), TypeMap);
6719     return;
6720   }
6721   case Intrinsic::gcread:
6722   case Intrinsic::gcwrite:
6723     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6724   case Intrinsic::flt_rounds:
6725     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6726     setValue(&I, Res);
6727     DAG.setRoot(Res.getValue(1));
6728     return;
6729 
6730   case Intrinsic::expect:
6731     // Just replace __builtin_expect(exp, c) with EXP.
6732     setValue(&I, getValue(I.getArgOperand(0)));
6733     return;
6734 
6735   case Intrinsic::ubsantrap:
6736   case Intrinsic::debugtrap:
6737   case Intrinsic::trap: {
6738     StringRef TrapFuncName =
6739         I.getAttributes()
6740             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6741             .getValueAsString();
6742     if (TrapFuncName.empty()) {
6743       switch (Intrinsic) {
6744       case Intrinsic::trap:
6745         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6746         break;
6747       case Intrinsic::debugtrap:
6748         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6749         break;
6750       case Intrinsic::ubsantrap:
6751         DAG.setRoot(DAG.getNode(
6752             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6753             DAG.getTargetConstant(
6754                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6755                 MVT::i32)));
6756         break;
6757       default: llvm_unreachable("unknown trap intrinsic");
6758       }
6759       return;
6760     }
6761     TargetLowering::ArgListTy Args;
6762     if (Intrinsic == Intrinsic::ubsantrap) {
6763       Args.push_back(TargetLoweringBase::ArgListEntry());
6764       Args[0].Val = I.getArgOperand(0);
6765       Args[0].Node = getValue(Args[0].Val);
6766       Args[0].Ty = Args[0].Val->getType();
6767     }
6768 
6769     TargetLowering::CallLoweringInfo CLI(DAG);
6770     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6771         CallingConv::C, I.getType(),
6772         DAG.getExternalSymbol(TrapFuncName.data(),
6773                               TLI.getPointerTy(DAG.getDataLayout())),
6774         std::move(Args));
6775 
6776     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6777     DAG.setRoot(Result.second);
6778     return;
6779   }
6780 
6781   case Intrinsic::uadd_with_overflow:
6782   case Intrinsic::sadd_with_overflow:
6783   case Intrinsic::usub_with_overflow:
6784   case Intrinsic::ssub_with_overflow:
6785   case Intrinsic::umul_with_overflow:
6786   case Intrinsic::smul_with_overflow: {
6787     ISD::NodeType Op;
6788     switch (Intrinsic) {
6789     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6790     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6791     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6792     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6793     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6794     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6795     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6796     }
6797     SDValue Op1 = getValue(I.getArgOperand(0));
6798     SDValue Op2 = getValue(I.getArgOperand(1));
6799 
6800     EVT ResultVT = Op1.getValueType();
6801     EVT OverflowVT = MVT::i1;
6802     if (ResultVT.isVector())
6803       OverflowVT = EVT::getVectorVT(
6804           *Context, OverflowVT, ResultVT.getVectorElementCount());
6805 
6806     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6807     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6808     return;
6809   }
6810   case Intrinsic::prefetch: {
6811     SDValue Ops[5];
6812     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6813     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6814     Ops[0] = DAG.getRoot();
6815     Ops[1] = getValue(I.getArgOperand(0));
6816     Ops[2] = getValue(I.getArgOperand(1));
6817     Ops[3] = getValue(I.getArgOperand(2));
6818     Ops[4] = getValue(I.getArgOperand(3));
6819     SDValue Result = DAG.getMemIntrinsicNode(
6820         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6821         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6822         /* align */ None, Flags);
6823 
6824     // Chain the prefetch in parallell with any pending loads, to stay out of
6825     // the way of later optimizations.
6826     PendingLoads.push_back(Result);
6827     Result = getRoot();
6828     DAG.setRoot(Result);
6829     return;
6830   }
6831   case Intrinsic::lifetime_start:
6832   case Intrinsic::lifetime_end: {
6833     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6834     // Stack coloring is not enabled in O0, discard region information.
6835     if (TM.getOptLevel() == CodeGenOpt::None)
6836       return;
6837 
6838     const int64_t ObjectSize =
6839         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6840     Value *const ObjectPtr = I.getArgOperand(1);
6841     SmallVector<const Value *, 4> Allocas;
6842     getUnderlyingObjects(ObjectPtr, Allocas);
6843 
6844     for (const Value *Alloca : Allocas) {
6845       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6846 
6847       // Could not find an Alloca.
6848       if (!LifetimeObject)
6849         continue;
6850 
6851       // First check that the Alloca is static, otherwise it won't have a
6852       // valid frame index.
6853       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6854       if (SI == FuncInfo.StaticAllocaMap.end())
6855         return;
6856 
6857       const int FrameIndex = SI->second;
6858       int64_t Offset;
6859       if (GetPointerBaseWithConstantOffset(
6860               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6861         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6862       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6863                                 Offset);
6864       DAG.setRoot(Res);
6865     }
6866     return;
6867   }
6868   case Intrinsic::pseudoprobe: {
6869     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6870     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6871     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6872     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6873     DAG.setRoot(Res);
6874     return;
6875   }
6876   case Intrinsic::invariant_start:
6877     // Discard region information.
6878     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6879     return;
6880   case Intrinsic::invariant_end:
6881     // Discard region information.
6882     return;
6883   case Intrinsic::clear_cache:
6884     /// FunctionName may be null.
6885     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6886       lowerCallToExternalSymbol(I, FunctionName);
6887     return;
6888   case Intrinsic::donothing:
6889   case Intrinsic::seh_try_begin:
6890   case Intrinsic::seh_scope_begin:
6891   case Intrinsic::seh_try_end:
6892   case Intrinsic::seh_scope_end:
6893     // ignore
6894     return;
6895   case Intrinsic::experimental_stackmap:
6896     visitStackmap(I);
6897     return;
6898   case Intrinsic::experimental_patchpoint_void:
6899   case Intrinsic::experimental_patchpoint_i64:
6900     visitPatchpoint(I);
6901     return;
6902   case Intrinsic::experimental_gc_statepoint:
6903     LowerStatepoint(cast<GCStatepointInst>(I));
6904     return;
6905   case Intrinsic::experimental_gc_result:
6906     visitGCResult(cast<GCResultInst>(I));
6907     return;
6908   case Intrinsic::experimental_gc_relocate:
6909     visitGCRelocate(cast<GCRelocateInst>(I));
6910     return;
6911   case Intrinsic::instrprof_increment:
6912     llvm_unreachable("instrprof failed to lower an increment");
6913   case Intrinsic::instrprof_value_profile:
6914     llvm_unreachable("instrprof failed to lower a value profiling call");
6915   case Intrinsic::localescape: {
6916     MachineFunction &MF = DAG.getMachineFunction();
6917     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6918 
6919     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6920     // is the same on all targets.
6921     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6922       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6923       if (isa<ConstantPointerNull>(Arg))
6924         continue; // Skip null pointers. They represent a hole in index space.
6925       AllocaInst *Slot = cast<AllocaInst>(Arg);
6926       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6927              "can only escape static allocas");
6928       int FI = FuncInfo.StaticAllocaMap[Slot];
6929       MCSymbol *FrameAllocSym =
6930           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6931               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6932       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6933               TII->get(TargetOpcode::LOCAL_ESCAPE))
6934           .addSym(FrameAllocSym)
6935           .addFrameIndex(FI);
6936     }
6937 
6938     return;
6939   }
6940 
6941   case Intrinsic::localrecover: {
6942     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6943     MachineFunction &MF = DAG.getMachineFunction();
6944 
6945     // Get the symbol that defines the frame offset.
6946     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6947     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6948     unsigned IdxVal =
6949         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6950     MCSymbol *FrameAllocSym =
6951         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6952             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6953 
6954     Value *FP = I.getArgOperand(1);
6955     SDValue FPVal = getValue(FP);
6956     EVT PtrVT = FPVal.getValueType();
6957 
6958     // Create a MCSymbol for the label to avoid any target lowering
6959     // that would make this PC relative.
6960     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6961     SDValue OffsetVal =
6962         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6963 
6964     // Add the offset to the FP.
6965     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6966     setValue(&I, Add);
6967 
6968     return;
6969   }
6970 
6971   case Intrinsic::eh_exceptionpointer:
6972   case Intrinsic::eh_exceptioncode: {
6973     // Get the exception pointer vreg, copy from it, and resize it to fit.
6974     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6975     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6976     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6977     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6978     SDValue N =
6979         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6980     if (Intrinsic == Intrinsic::eh_exceptioncode)
6981       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6982     setValue(&I, N);
6983     return;
6984   }
6985   case Intrinsic::xray_customevent: {
6986     // Here we want to make sure that the intrinsic behaves as if it has a
6987     // specific calling convention, and only for x86_64.
6988     // FIXME: Support other platforms later.
6989     const auto &Triple = DAG.getTarget().getTargetTriple();
6990     if (Triple.getArch() != Triple::x86_64)
6991       return;
6992 
6993     SDLoc DL = getCurSDLoc();
6994     SmallVector<SDValue, 8> Ops;
6995 
6996     // We want to say that we always want the arguments in registers.
6997     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6998     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6999     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7000     SDValue Chain = getRoot();
7001     Ops.push_back(LogEntryVal);
7002     Ops.push_back(StrSizeVal);
7003     Ops.push_back(Chain);
7004 
7005     // We need to enforce the calling convention for the callsite, so that
7006     // argument ordering is enforced correctly, and that register allocation can
7007     // see that some registers may be assumed clobbered and have to preserve
7008     // them across calls to the intrinsic.
7009     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7010                                            DL, NodeTys, Ops);
7011     SDValue patchableNode = SDValue(MN, 0);
7012     DAG.setRoot(patchableNode);
7013     setValue(&I, patchableNode);
7014     return;
7015   }
7016   case Intrinsic::xray_typedevent: {
7017     // Here we want to make sure that the intrinsic behaves as if it has a
7018     // specific calling convention, and only for x86_64.
7019     // FIXME: Support other platforms later.
7020     const auto &Triple = DAG.getTarget().getTargetTriple();
7021     if (Triple.getArch() != Triple::x86_64)
7022       return;
7023 
7024     SDLoc DL = getCurSDLoc();
7025     SmallVector<SDValue, 8> Ops;
7026 
7027     // We want to say that we always want the arguments in registers.
7028     // It's unclear to me how manipulating the selection DAG here forces callers
7029     // to provide arguments in registers instead of on the stack.
7030     SDValue LogTypeId = getValue(I.getArgOperand(0));
7031     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7032     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7033     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7034     SDValue Chain = getRoot();
7035     Ops.push_back(LogTypeId);
7036     Ops.push_back(LogEntryVal);
7037     Ops.push_back(StrSizeVal);
7038     Ops.push_back(Chain);
7039 
7040     // We need to enforce the calling convention for the callsite, so that
7041     // argument ordering is enforced correctly, and that register allocation can
7042     // see that some registers may be assumed clobbered and have to preserve
7043     // them across calls to the intrinsic.
7044     MachineSDNode *MN = DAG.getMachineNode(
7045         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
7046     SDValue patchableNode = SDValue(MN, 0);
7047     DAG.setRoot(patchableNode);
7048     setValue(&I, patchableNode);
7049     return;
7050   }
7051   case Intrinsic::experimental_deoptimize:
7052     LowerDeoptimizeCall(&I);
7053     return;
7054   case Intrinsic::experimental_stepvector:
7055     visitStepVector(I);
7056     return;
7057   case Intrinsic::vector_reduce_fadd:
7058   case Intrinsic::vector_reduce_fmul:
7059   case Intrinsic::vector_reduce_add:
7060   case Intrinsic::vector_reduce_mul:
7061   case Intrinsic::vector_reduce_and:
7062   case Intrinsic::vector_reduce_or:
7063   case Intrinsic::vector_reduce_xor:
7064   case Intrinsic::vector_reduce_smax:
7065   case Intrinsic::vector_reduce_smin:
7066   case Intrinsic::vector_reduce_umax:
7067   case Intrinsic::vector_reduce_umin:
7068   case Intrinsic::vector_reduce_fmax:
7069   case Intrinsic::vector_reduce_fmin:
7070     visitVectorReduce(I, Intrinsic);
7071     return;
7072 
7073   case Intrinsic::icall_branch_funnel: {
7074     SmallVector<SDValue, 16> Ops;
7075     Ops.push_back(getValue(I.getArgOperand(0)));
7076 
7077     int64_t Offset;
7078     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7079         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7080     if (!Base)
7081       report_fatal_error(
7082           "llvm.icall.branch.funnel operand must be a GlobalValue");
7083     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
7084 
7085     struct BranchFunnelTarget {
7086       int64_t Offset;
7087       SDValue Target;
7088     };
7089     SmallVector<BranchFunnelTarget, 8> Targets;
7090 
7091     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
7092       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7093           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7094       if (ElemBase != Base)
7095         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7096                            "to the same GlobalValue");
7097 
7098       SDValue Val = getValue(I.getArgOperand(Op + 1));
7099       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7100       if (!GA)
7101         report_fatal_error(
7102             "llvm.icall.branch.funnel operand must be a GlobalValue");
7103       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7104                                      GA->getGlobal(), getCurSDLoc(),
7105                                      Val.getValueType(), GA->getOffset())});
7106     }
7107     llvm::sort(Targets,
7108                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7109                  return T1.Offset < T2.Offset;
7110                });
7111 
7112     for (auto &T : Targets) {
7113       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
7114       Ops.push_back(T.Target);
7115     }
7116 
7117     Ops.push_back(DAG.getRoot()); // Chain
7118     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
7119                                  getCurSDLoc(), MVT::Other, Ops),
7120               0);
7121     DAG.setRoot(N);
7122     setValue(&I, N);
7123     HasTailCall = true;
7124     return;
7125   }
7126 
7127   case Intrinsic::wasm_landingpad_index:
7128     // Information this intrinsic contained has been transferred to
7129     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7130     // delete it now.
7131     return;
7132 
7133   case Intrinsic::aarch64_settag:
7134   case Intrinsic::aarch64_settag_zero: {
7135     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7136     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7137     SDValue Val = TSI.EmitTargetCodeForSetTag(
7138         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
7139         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7140         ZeroMemory);
7141     DAG.setRoot(Val);
7142     setValue(&I, Val);
7143     return;
7144   }
7145   case Intrinsic::ptrmask: {
7146     SDValue Ptr = getValue(I.getOperand(0));
7147     SDValue Const = getValue(I.getOperand(1));
7148 
7149     EVT PtrVT = Ptr.getValueType();
7150     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
7151                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
7152     return;
7153   }
7154   case Intrinsic::get_active_lane_mask: {
7155     auto DL = getCurSDLoc();
7156     SDValue Index = getValue(I.getOperand(0));
7157     SDValue TripCount = getValue(I.getOperand(1));
7158     Type *ElementTy = I.getOperand(0)->getType();
7159     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7160     unsigned VecWidth = VT.getVectorNumElements();
7161 
7162     SmallVector<SDValue, 16> OpsTripCount;
7163     SmallVector<SDValue, 16> OpsIndex;
7164     SmallVector<SDValue, 16> OpsStepConstants;
7165     for (unsigned i = 0; i < VecWidth; i++) {
7166       OpsTripCount.push_back(TripCount);
7167       OpsIndex.push_back(Index);
7168       OpsStepConstants.push_back(
7169           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
7170     }
7171 
7172     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
7173 
7174     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
7175     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
7176     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
7177     SDValue VectorInduction = DAG.getNode(
7178        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
7179     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
7180     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
7181                                  VectorTripCount, ISD::CondCode::SETULT);
7182     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
7183                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
7184                              SetCC));
7185     return;
7186   }
7187   case Intrinsic::experimental_vector_insert: {
7188     auto DL = getCurSDLoc();
7189 
7190     SDValue Vec = getValue(I.getOperand(0));
7191     SDValue SubVec = getValue(I.getOperand(1));
7192     SDValue Index = getValue(I.getOperand(2));
7193 
7194     // The intrinsic's index type is i64, but the SDNode requires an index type
7195     // suitable for the target. Convert the index as required.
7196     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7197     if (Index.getValueType() != VectorIdxTy)
7198       Index = DAG.getVectorIdxConstant(
7199           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7200 
7201     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7202     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
7203                              Index));
7204     return;
7205   }
7206   case Intrinsic::experimental_vector_extract: {
7207     auto DL = getCurSDLoc();
7208 
7209     SDValue Vec = getValue(I.getOperand(0));
7210     SDValue Index = getValue(I.getOperand(1));
7211     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7212 
7213     // The intrinsic's index type is i64, but the SDNode requires an index type
7214     // suitable for the target. Convert the index as required.
7215     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7216     if (Index.getValueType() != VectorIdxTy)
7217       Index = DAG.getVectorIdxConstant(
7218           cast<ConstantSDNode>(Index)->getZExtValue(), DL);
7219 
7220     setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
7221     return;
7222   }
7223   case Intrinsic::experimental_vector_reverse:
7224     visitVectorReverse(I);
7225     return;
7226   case Intrinsic::experimental_vector_splice:
7227     visitVectorSplice(I);
7228     return;
7229   }
7230 }
7231 
7232 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7233     const ConstrainedFPIntrinsic &FPI) {
7234   SDLoc sdl = getCurSDLoc();
7235 
7236   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7237   SmallVector<EVT, 4> ValueVTs;
7238   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7239   ValueVTs.push_back(MVT::Other); // Out chain
7240 
7241   // We do not need to serialize constrained FP intrinsics against
7242   // each other or against (nonvolatile) loads, so they can be
7243   // chained like loads.
7244   SDValue Chain = DAG.getRoot();
7245   SmallVector<SDValue, 4> Opers;
7246   Opers.push_back(Chain);
7247   if (FPI.isUnaryOp()) {
7248     Opers.push_back(getValue(FPI.getArgOperand(0)));
7249   } else if (FPI.isTernaryOp()) {
7250     Opers.push_back(getValue(FPI.getArgOperand(0)));
7251     Opers.push_back(getValue(FPI.getArgOperand(1)));
7252     Opers.push_back(getValue(FPI.getArgOperand(2)));
7253   } else {
7254     Opers.push_back(getValue(FPI.getArgOperand(0)));
7255     Opers.push_back(getValue(FPI.getArgOperand(1)));
7256   }
7257 
7258   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7259     assert(Result.getNode()->getNumValues() == 2);
7260 
7261     // Push node to the appropriate list so that future instructions can be
7262     // chained up correctly.
7263     SDValue OutChain = Result.getValue(1);
7264     switch (EB) {
7265     case fp::ExceptionBehavior::ebIgnore:
7266       // The only reason why ebIgnore nodes still need to be chained is that
7267       // they might depend on the current rounding mode, and therefore must
7268       // not be moved across instruction that may change that mode.
7269       LLVM_FALLTHROUGH;
7270     case fp::ExceptionBehavior::ebMayTrap:
7271       // These must not be moved across calls or instructions that may change
7272       // floating-point exception masks.
7273       PendingConstrainedFP.push_back(OutChain);
7274       break;
7275     case fp::ExceptionBehavior::ebStrict:
7276       // These must not be moved across calls or instructions that may change
7277       // floating-point exception masks or read floating-point exception flags.
7278       // In addition, they cannot be optimized out even if unused.
7279       PendingConstrainedFPStrict.push_back(OutChain);
7280       break;
7281     }
7282   };
7283 
7284   SDVTList VTs = DAG.getVTList(ValueVTs);
7285   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7286 
7287   SDNodeFlags Flags;
7288   if (EB == fp::ExceptionBehavior::ebIgnore)
7289     Flags.setNoFPExcept(true);
7290 
7291   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7292     Flags.copyFMF(*FPOp);
7293 
7294   unsigned Opcode;
7295   switch (FPI.getIntrinsicID()) {
7296   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7297 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7298   case Intrinsic::INTRINSIC:                                                   \
7299     Opcode = ISD::STRICT_##DAGN;                                               \
7300     break;
7301 #include "llvm/IR/ConstrainedOps.def"
7302   case Intrinsic::experimental_constrained_fmuladd: {
7303     Opcode = ISD::STRICT_FMA;
7304     // Break fmuladd into fmul and fadd.
7305     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7306         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7307                                         ValueVTs[0])) {
7308       Opers.pop_back();
7309       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7310       pushOutChain(Mul, EB);
7311       Opcode = ISD::STRICT_FADD;
7312       Opers.clear();
7313       Opers.push_back(Mul.getValue(1));
7314       Opers.push_back(Mul.getValue(0));
7315       Opers.push_back(getValue(FPI.getArgOperand(2)));
7316     }
7317     break;
7318   }
7319   }
7320 
7321   // A few strict DAG nodes carry additional operands that are not
7322   // set up by the default code above.
7323   switch (Opcode) {
7324   default: break;
7325   case ISD::STRICT_FP_ROUND:
7326     Opers.push_back(
7327         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7328     break;
7329   case ISD::STRICT_FSETCC:
7330   case ISD::STRICT_FSETCCS: {
7331     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7332     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7333     if (TM.Options.NoNaNsFPMath)
7334       Condition = getFCmpCodeWithoutNaN(Condition);
7335     Opers.push_back(DAG.getCondCode(Condition));
7336     break;
7337   }
7338   }
7339 
7340   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7341   pushOutChain(Result, EB);
7342 
7343   SDValue FPResult = Result.getValue(0);
7344   setValue(&FPI, FPResult);
7345 }
7346 
7347 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7348   Optional<unsigned> ResOPC;
7349   switch (VPIntrin.getIntrinsicID()) {
7350 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
7351 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
7352 #define END_REGISTER_VP_INTRINSIC(...) break;
7353 #include "llvm/IR/VPIntrinsics.def"
7354   }
7355 
7356   if (!ResOPC.hasValue())
7357     llvm_unreachable(
7358         "Inconsistency: no SDNode available for this VPIntrinsic!");
7359 
7360   return ResOPC.getValue();
7361 }
7362 
7363 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7364     const VPIntrinsic &VPIntrin) {
7365   SDLoc DL = getCurSDLoc();
7366   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7367 
7368   SmallVector<EVT, 4> ValueVTs;
7369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7370   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7371   SDVTList VTs = DAG.getVTList(ValueVTs);
7372 
7373   auto EVLParamPos =
7374       VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
7375 
7376   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7377   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7378          "Unexpected target EVL type");
7379 
7380   // Request operands.
7381   SmallVector<SDValue, 7> OpValues;
7382   for (unsigned I = 0; I < VPIntrin.getNumArgOperands(); ++I) {
7383     auto Op = getValue(VPIntrin.getArgOperand(I));
7384     if (I == EVLParamPos)
7385       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7386     OpValues.push_back(Op);
7387   }
7388 
7389   SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7390   setValue(&VPIntrin, Result);
7391 }
7392 
7393 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7394                                           const BasicBlock *EHPadBB,
7395                                           MCSymbol *&BeginLabel) {
7396   MachineFunction &MF = DAG.getMachineFunction();
7397   MachineModuleInfo &MMI = MF.getMMI();
7398 
7399   // Insert a label before the invoke call to mark the try range.  This can be
7400   // used to detect deletion of the invoke via the MachineModuleInfo.
7401   BeginLabel = MMI.getContext().createTempSymbol();
7402 
7403   // For SjLj, keep track of which landing pads go with which invokes
7404   // so as to maintain the ordering of pads in the LSDA.
7405   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7406   if (CallSiteIndex) {
7407     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7408     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7409 
7410     // Now that the call site is handled, stop tracking it.
7411     MMI.setCurrentCallSite(0);
7412   }
7413 
7414   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7415 }
7416 
7417 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7418                                         const BasicBlock *EHPadBB,
7419                                         MCSymbol *BeginLabel) {
7420   assert(BeginLabel && "BeginLabel should've been set");
7421 
7422   MachineFunction &MF = DAG.getMachineFunction();
7423   MachineModuleInfo &MMI = MF.getMMI();
7424 
7425   // Insert a label at the end of the invoke call to mark the try range.  This
7426   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7427   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7428   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7429 
7430   // Inform MachineModuleInfo of range.
7431   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7432   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7433   // actually use outlined funclets and their LSDA info style.
7434   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7435     assert(II && "II should've been set");
7436     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7437     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7438   } else if (!isScopedEHPersonality(Pers)) {
7439     assert(EHPadBB);
7440     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7441   }
7442 
7443   return Chain;
7444 }
7445 
7446 std::pair<SDValue, SDValue>
7447 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7448                                     const BasicBlock *EHPadBB) {
7449   MCSymbol *BeginLabel = nullptr;
7450 
7451   if (EHPadBB) {
7452     // Both PendingLoads and PendingExports must be flushed here;
7453     // this call might not return.
7454     (void)getRoot();
7455     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7456     CLI.setChain(getRoot());
7457   }
7458 
7459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7460   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7461 
7462   assert((CLI.IsTailCall || Result.second.getNode()) &&
7463          "Non-null chain expected with non-tail call!");
7464   assert((Result.second.getNode() || !Result.first.getNode()) &&
7465          "Null value expected with tail call!");
7466 
7467   if (!Result.second.getNode()) {
7468     // As a special case, a null chain means that a tail call has been emitted
7469     // and the DAG root is already updated.
7470     HasTailCall = true;
7471 
7472     // Since there's no actual continuation from this block, nothing can be
7473     // relying on us setting vregs for them.
7474     PendingExports.clear();
7475   } else {
7476     DAG.setRoot(Result.second);
7477   }
7478 
7479   if (EHPadBB) {
7480     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7481                            BeginLabel));
7482   }
7483 
7484   return Result;
7485 }
7486 
7487 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7488                                       bool isTailCall,
7489                                       bool isMustTailCall,
7490                                       const BasicBlock *EHPadBB) {
7491   auto &DL = DAG.getDataLayout();
7492   FunctionType *FTy = CB.getFunctionType();
7493   Type *RetTy = CB.getType();
7494 
7495   TargetLowering::ArgListTy Args;
7496   Args.reserve(CB.arg_size());
7497 
7498   const Value *SwiftErrorVal = nullptr;
7499   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7500 
7501   if (isTailCall) {
7502     // Avoid emitting tail calls in functions with the disable-tail-calls
7503     // attribute.
7504     auto *Caller = CB.getParent()->getParent();
7505     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7506         "true" && !isMustTailCall)
7507       isTailCall = false;
7508 
7509     // We can't tail call inside a function with a swifterror argument. Lowering
7510     // does not support this yet. It would have to move into the swifterror
7511     // register before the call.
7512     if (TLI.supportSwiftError() &&
7513         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7514       isTailCall = false;
7515   }
7516 
7517   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7518     TargetLowering::ArgListEntry Entry;
7519     const Value *V = *I;
7520 
7521     // Skip empty types
7522     if (V->getType()->isEmptyTy())
7523       continue;
7524 
7525     SDValue ArgNode = getValue(V);
7526     Entry.Node = ArgNode; Entry.Ty = V->getType();
7527 
7528     Entry.setAttributes(&CB, I - CB.arg_begin());
7529 
7530     // Use swifterror virtual register as input to the call.
7531     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7532       SwiftErrorVal = V;
7533       // We find the virtual register for the actual swifterror argument.
7534       // Instead of using the Value, we use the virtual register instead.
7535       Entry.Node =
7536           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7537                           EVT(TLI.getPointerTy(DL)));
7538     }
7539 
7540     Args.push_back(Entry);
7541 
7542     // If we have an explicit sret argument that is an Instruction, (i.e., it
7543     // might point to function-local memory), we can't meaningfully tail-call.
7544     if (Entry.IsSRet && isa<Instruction>(V))
7545       isTailCall = false;
7546   }
7547 
7548   // If call site has a cfguardtarget operand bundle, create and add an
7549   // additional ArgListEntry.
7550   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7551     TargetLowering::ArgListEntry Entry;
7552     Value *V = Bundle->Inputs[0];
7553     SDValue ArgNode = getValue(V);
7554     Entry.Node = ArgNode;
7555     Entry.Ty = V->getType();
7556     Entry.IsCFGuardTarget = true;
7557     Args.push_back(Entry);
7558   }
7559 
7560   // Check if target-independent constraints permit a tail call here.
7561   // Target-dependent constraints are checked within TLI->LowerCallTo.
7562   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7563     isTailCall = false;
7564 
7565   // Disable tail calls if there is an swifterror argument. Targets have not
7566   // been updated to support tail calls.
7567   if (TLI.supportSwiftError() && SwiftErrorVal)
7568     isTailCall = false;
7569 
7570   TargetLowering::CallLoweringInfo CLI(DAG);
7571   CLI.setDebugLoc(getCurSDLoc())
7572       .setChain(getRoot())
7573       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7574       .setTailCall(isTailCall)
7575       .setConvergent(CB.isConvergent())
7576       .setIsPreallocated(
7577           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7578   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7579 
7580   if (Result.first.getNode()) {
7581     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7582     setValue(&CB, Result.first);
7583   }
7584 
7585   // The last element of CLI.InVals has the SDValue for swifterror return.
7586   // Here we copy it to a virtual register and update SwiftErrorMap for
7587   // book-keeping.
7588   if (SwiftErrorVal && TLI.supportSwiftError()) {
7589     // Get the last element of InVals.
7590     SDValue Src = CLI.InVals.back();
7591     Register VReg =
7592         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7593     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7594     DAG.setRoot(CopyNode);
7595   }
7596 }
7597 
7598 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7599                              SelectionDAGBuilder &Builder) {
7600   // Check to see if this load can be trivially constant folded, e.g. if the
7601   // input is from a string literal.
7602   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7603     // Cast pointer to the type we really want to load.
7604     Type *LoadTy =
7605         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7606     if (LoadVT.isVector())
7607       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7608 
7609     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7610                                          PointerType::getUnqual(LoadTy));
7611 
7612     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7613             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7614       return Builder.getValue(LoadCst);
7615   }
7616 
7617   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7618   // still constant memory, the input chain can be the entry node.
7619   SDValue Root;
7620   bool ConstantMemory = false;
7621 
7622   // Do not serialize (non-volatile) loads of constant memory with anything.
7623   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7624     Root = Builder.DAG.getEntryNode();
7625     ConstantMemory = true;
7626   } else {
7627     // Do not serialize non-volatile loads against each other.
7628     Root = Builder.DAG.getRoot();
7629   }
7630 
7631   SDValue Ptr = Builder.getValue(PtrVal);
7632   SDValue LoadVal =
7633       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7634                           MachinePointerInfo(PtrVal), Align(1));
7635 
7636   if (!ConstantMemory)
7637     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7638   return LoadVal;
7639 }
7640 
7641 /// Record the value for an instruction that produces an integer result,
7642 /// converting the type where necessary.
7643 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7644                                                   SDValue Value,
7645                                                   bool IsSigned) {
7646   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7647                                                     I.getType(), true);
7648   if (IsSigned)
7649     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7650   else
7651     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7652   setValue(&I, Value);
7653 }
7654 
7655 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7656 /// true and lower it. Otherwise return false, and it will be lowered like a
7657 /// normal call.
7658 /// The caller already checked that \p I calls the appropriate LibFunc with a
7659 /// correct prototype.
7660 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7661   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7662   const Value *Size = I.getArgOperand(2);
7663   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7664   if (CSize && CSize->getZExtValue() == 0) {
7665     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7666                                                           I.getType(), true);
7667     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7668     return true;
7669   }
7670 
7671   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7672   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7673       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7674       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7675   if (Res.first.getNode()) {
7676     processIntegerCallValue(I, Res.first, true);
7677     PendingLoads.push_back(Res.second);
7678     return true;
7679   }
7680 
7681   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7682   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7683   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7684     return false;
7685 
7686   // If the target has a fast compare for the given size, it will return a
7687   // preferred load type for that size. Require that the load VT is legal and
7688   // that the target supports unaligned loads of that type. Otherwise, return
7689   // INVALID.
7690   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7691     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7692     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7693     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7694       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7695       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7696       // TODO: Check alignment of src and dest ptrs.
7697       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7698       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7699       if (!TLI.isTypeLegal(LVT) ||
7700           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7701           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7702         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7703     }
7704 
7705     return LVT;
7706   };
7707 
7708   // This turns into unaligned loads. We only do this if the target natively
7709   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7710   // we'll only produce a small number of byte loads.
7711   MVT LoadVT;
7712   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7713   switch (NumBitsToCompare) {
7714   default:
7715     return false;
7716   case 16:
7717     LoadVT = MVT::i16;
7718     break;
7719   case 32:
7720     LoadVT = MVT::i32;
7721     break;
7722   case 64:
7723   case 128:
7724   case 256:
7725     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7726     break;
7727   }
7728 
7729   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7730     return false;
7731 
7732   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7733   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7734 
7735   // Bitcast to a wide integer type if the loads are vectors.
7736   if (LoadVT.isVector()) {
7737     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7738     LoadL = DAG.getBitcast(CmpVT, LoadL);
7739     LoadR = DAG.getBitcast(CmpVT, LoadR);
7740   }
7741 
7742   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7743   processIntegerCallValue(I, Cmp, false);
7744   return true;
7745 }
7746 
7747 /// See if we can lower a memchr call into an optimized form. If so, return
7748 /// true and lower it. Otherwise return false, and it will be lowered like a
7749 /// normal call.
7750 /// The caller already checked that \p I calls the appropriate LibFunc with a
7751 /// correct prototype.
7752 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7753   const Value *Src = I.getArgOperand(0);
7754   const Value *Char = I.getArgOperand(1);
7755   const Value *Length = I.getArgOperand(2);
7756 
7757   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7758   std::pair<SDValue, SDValue> Res =
7759     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7760                                 getValue(Src), getValue(Char), getValue(Length),
7761                                 MachinePointerInfo(Src));
7762   if (Res.first.getNode()) {
7763     setValue(&I, Res.first);
7764     PendingLoads.push_back(Res.second);
7765     return true;
7766   }
7767 
7768   return false;
7769 }
7770 
7771 /// See if we can lower a mempcpy call into an optimized form. If so, return
7772 /// true and lower it. Otherwise return false, and it will be lowered like a
7773 /// normal call.
7774 /// The caller already checked that \p I calls the appropriate LibFunc with a
7775 /// correct prototype.
7776 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7777   SDValue Dst = getValue(I.getArgOperand(0));
7778   SDValue Src = getValue(I.getArgOperand(1));
7779   SDValue Size = getValue(I.getArgOperand(2));
7780 
7781   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7782   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7783   // DAG::getMemcpy needs Alignment to be defined.
7784   Align Alignment = std::min(DstAlign, SrcAlign);
7785 
7786   bool isVol = false;
7787   SDLoc sdl = getCurSDLoc();
7788 
7789   // In the mempcpy context we need to pass in a false value for isTailCall
7790   // because the return pointer needs to be adjusted by the size of
7791   // the copied memory.
7792   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7793   AAMDNodes AAInfo;
7794   I.getAAMetadata(AAInfo);
7795   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7796                              /*isTailCall=*/false,
7797                              MachinePointerInfo(I.getArgOperand(0)),
7798                              MachinePointerInfo(I.getArgOperand(1)), AAInfo);
7799   assert(MC.getNode() != nullptr &&
7800          "** memcpy should not be lowered as TailCall in mempcpy context **");
7801   DAG.setRoot(MC);
7802 
7803   // Check if Size needs to be truncated or extended.
7804   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7805 
7806   // Adjust return pointer to point just past the last dst byte.
7807   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7808                                     Dst, Size);
7809   setValue(&I, DstPlusSize);
7810   return true;
7811 }
7812 
7813 /// See if we can lower a strcpy call into an optimized form.  If so, return
7814 /// true and lower it, otherwise return false and it will be lowered like a
7815 /// normal call.
7816 /// The caller already checked that \p I calls the appropriate LibFunc with a
7817 /// correct prototype.
7818 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7819   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7820 
7821   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7822   std::pair<SDValue, SDValue> Res =
7823     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7824                                 getValue(Arg0), getValue(Arg1),
7825                                 MachinePointerInfo(Arg0),
7826                                 MachinePointerInfo(Arg1), isStpcpy);
7827   if (Res.first.getNode()) {
7828     setValue(&I, Res.first);
7829     DAG.setRoot(Res.second);
7830     return true;
7831   }
7832 
7833   return false;
7834 }
7835 
7836 /// See if we can lower a strcmp call into an optimized form.  If so, return
7837 /// true and lower it, otherwise return false and it will be lowered like a
7838 /// normal call.
7839 /// The caller already checked that \p I calls the appropriate LibFunc with a
7840 /// correct prototype.
7841 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7842   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7843 
7844   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7845   std::pair<SDValue, SDValue> Res =
7846     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7847                                 getValue(Arg0), getValue(Arg1),
7848                                 MachinePointerInfo(Arg0),
7849                                 MachinePointerInfo(Arg1));
7850   if (Res.first.getNode()) {
7851     processIntegerCallValue(I, Res.first, true);
7852     PendingLoads.push_back(Res.second);
7853     return true;
7854   }
7855 
7856   return false;
7857 }
7858 
7859 /// See if we can lower a strlen call into an optimized form.  If so, return
7860 /// true and lower it, otherwise return false and it will be lowered like a
7861 /// normal call.
7862 /// The caller already checked that \p I calls the appropriate LibFunc with a
7863 /// correct prototype.
7864 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7865   const Value *Arg0 = I.getArgOperand(0);
7866 
7867   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7868   std::pair<SDValue, SDValue> Res =
7869     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7870                                 getValue(Arg0), MachinePointerInfo(Arg0));
7871   if (Res.first.getNode()) {
7872     processIntegerCallValue(I, Res.first, false);
7873     PendingLoads.push_back(Res.second);
7874     return true;
7875   }
7876 
7877   return false;
7878 }
7879 
7880 /// See if we can lower a strnlen call into an optimized form.  If so, return
7881 /// true and lower it, otherwise return false and it will be lowered like a
7882 /// normal call.
7883 /// The caller already checked that \p I calls the appropriate LibFunc with a
7884 /// correct prototype.
7885 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7886   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7887 
7888   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7889   std::pair<SDValue, SDValue> Res =
7890     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7891                                  getValue(Arg0), getValue(Arg1),
7892                                  MachinePointerInfo(Arg0));
7893   if (Res.first.getNode()) {
7894     processIntegerCallValue(I, Res.first, false);
7895     PendingLoads.push_back(Res.second);
7896     return true;
7897   }
7898 
7899   return false;
7900 }
7901 
7902 /// See if we can lower a unary floating-point operation into an SDNode with
7903 /// the specified Opcode.  If so, return true and lower it, otherwise return
7904 /// false and it will be lowered like a normal call.
7905 /// The caller already checked that \p I calls the appropriate LibFunc with a
7906 /// correct prototype.
7907 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7908                                               unsigned Opcode) {
7909   // We already checked this call's prototype; verify it doesn't modify errno.
7910   if (!I.onlyReadsMemory())
7911     return false;
7912 
7913   SDNodeFlags Flags;
7914   Flags.copyFMF(cast<FPMathOperator>(I));
7915 
7916   SDValue Tmp = getValue(I.getArgOperand(0));
7917   setValue(&I,
7918            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7919   return true;
7920 }
7921 
7922 /// See if we can lower a binary floating-point operation into an SDNode with
7923 /// the specified Opcode. If so, return true and lower it. Otherwise return
7924 /// false, and it will be lowered like a normal call.
7925 /// The caller already checked that \p I calls the appropriate LibFunc with a
7926 /// correct prototype.
7927 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7928                                                unsigned Opcode) {
7929   // We already checked this call's prototype; verify it doesn't modify errno.
7930   if (!I.onlyReadsMemory())
7931     return false;
7932 
7933   SDNodeFlags Flags;
7934   Flags.copyFMF(cast<FPMathOperator>(I));
7935 
7936   SDValue Tmp0 = getValue(I.getArgOperand(0));
7937   SDValue Tmp1 = getValue(I.getArgOperand(1));
7938   EVT VT = Tmp0.getValueType();
7939   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
7940   return true;
7941 }
7942 
7943 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7944   // Handle inline assembly differently.
7945   if (I.isInlineAsm()) {
7946     visitInlineAsm(I);
7947     return;
7948   }
7949 
7950   if (Function *F = I.getCalledFunction()) {
7951     if (F->isDeclaration()) {
7952       // Is this an LLVM intrinsic or a target-specific intrinsic?
7953       unsigned IID = F->getIntrinsicID();
7954       if (!IID)
7955         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7956           IID = II->getIntrinsicID(F);
7957 
7958       if (IID) {
7959         visitIntrinsicCall(I, IID);
7960         return;
7961       }
7962     }
7963 
7964     // Check for well-known libc/libm calls.  If the function is internal, it
7965     // can't be a library call.  Don't do the check if marked as nobuiltin for
7966     // some reason or the call site requires strict floating point semantics.
7967     LibFunc Func;
7968     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7969         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7970         LibInfo->hasOptimizedCodeGen(Func)) {
7971       switch (Func) {
7972       default: break;
7973       case LibFunc_bcmp:
7974         if (visitMemCmpBCmpCall(I))
7975           return;
7976         break;
7977       case LibFunc_copysign:
7978       case LibFunc_copysignf:
7979       case LibFunc_copysignl:
7980         // We already checked this call's prototype; verify it doesn't modify
7981         // errno.
7982         if (I.onlyReadsMemory()) {
7983           SDValue LHS = getValue(I.getArgOperand(0));
7984           SDValue RHS = getValue(I.getArgOperand(1));
7985           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7986                                    LHS.getValueType(), LHS, RHS));
7987           return;
7988         }
7989         break;
7990       case LibFunc_fabs:
7991       case LibFunc_fabsf:
7992       case LibFunc_fabsl:
7993         if (visitUnaryFloatCall(I, ISD::FABS))
7994           return;
7995         break;
7996       case LibFunc_fmin:
7997       case LibFunc_fminf:
7998       case LibFunc_fminl:
7999         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8000           return;
8001         break;
8002       case LibFunc_fmax:
8003       case LibFunc_fmaxf:
8004       case LibFunc_fmaxl:
8005         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8006           return;
8007         break;
8008       case LibFunc_sin:
8009       case LibFunc_sinf:
8010       case LibFunc_sinl:
8011         if (visitUnaryFloatCall(I, ISD::FSIN))
8012           return;
8013         break;
8014       case LibFunc_cos:
8015       case LibFunc_cosf:
8016       case LibFunc_cosl:
8017         if (visitUnaryFloatCall(I, ISD::FCOS))
8018           return;
8019         break;
8020       case LibFunc_sqrt:
8021       case LibFunc_sqrtf:
8022       case LibFunc_sqrtl:
8023       case LibFunc_sqrt_finite:
8024       case LibFunc_sqrtf_finite:
8025       case LibFunc_sqrtl_finite:
8026         if (visitUnaryFloatCall(I, ISD::FSQRT))
8027           return;
8028         break;
8029       case LibFunc_floor:
8030       case LibFunc_floorf:
8031       case LibFunc_floorl:
8032         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8033           return;
8034         break;
8035       case LibFunc_nearbyint:
8036       case LibFunc_nearbyintf:
8037       case LibFunc_nearbyintl:
8038         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8039           return;
8040         break;
8041       case LibFunc_ceil:
8042       case LibFunc_ceilf:
8043       case LibFunc_ceill:
8044         if (visitUnaryFloatCall(I, ISD::FCEIL))
8045           return;
8046         break;
8047       case LibFunc_rint:
8048       case LibFunc_rintf:
8049       case LibFunc_rintl:
8050         if (visitUnaryFloatCall(I, ISD::FRINT))
8051           return;
8052         break;
8053       case LibFunc_round:
8054       case LibFunc_roundf:
8055       case LibFunc_roundl:
8056         if (visitUnaryFloatCall(I, ISD::FROUND))
8057           return;
8058         break;
8059       case LibFunc_trunc:
8060       case LibFunc_truncf:
8061       case LibFunc_truncl:
8062         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8063           return;
8064         break;
8065       case LibFunc_log2:
8066       case LibFunc_log2f:
8067       case LibFunc_log2l:
8068         if (visitUnaryFloatCall(I, ISD::FLOG2))
8069           return;
8070         break;
8071       case LibFunc_exp2:
8072       case LibFunc_exp2f:
8073       case LibFunc_exp2l:
8074         if (visitUnaryFloatCall(I, ISD::FEXP2))
8075           return;
8076         break;
8077       case LibFunc_memcmp:
8078         if (visitMemCmpBCmpCall(I))
8079           return;
8080         break;
8081       case LibFunc_mempcpy:
8082         if (visitMemPCpyCall(I))
8083           return;
8084         break;
8085       case LibFunc_memchr:
8086         if (visitMemChrCall(I))
8087           return;
8088         break;
8089       case LibFunc_strcpy:
8090         if (visitStrCpyCall(I, false))
8091           return;
8092         break;
8093       case LibFunc_stpcpy:
8094         if (visitStrCpyCall(I, true))
8095           return;
8096         break;
8097       case LibFunc_strcmp:
8098         if (visitStrCmpCall(I))
8099           return;
8100         break;
8101       case LibFunc_strlen:
8102         if (visitStrLenCall(I))
8103           return;
8104         break;
8105       case LibFunc_strnlen:
8106         if (visitStrNLenCall(I))
8107           return;
8108         break;
8109       }
8110     }
8111   }
8112 
8113   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8114   // have to do anything here to lower funclet bundles.
8115   // CFGuardTarget bundles are lowered in LowerCallTo.
8116   assert(!I.hasOperandBundlesOtherThan(
8117              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8118               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8119               LLVMContext::OB_clang_arc_attachedcall}) &&
8120          "Cannot lower calls with arbitrary operand bundles!");
8121 
8122   SDValue Callee = getValue(I.getCalledOperand());
8123 
8124   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8125     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8126   else
8127     // Check if we can potentially perform a tail call. More detailed checking
8128     // is be done within LowerCallTo, after more information about the call is
8129     // known.
8130     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8131 }
8132 
8133 namespace {
8134 
8135 /// AsmOperandInfo - This contains information for each constraint that we are
8136 /// lowering.
8137 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8138 public:
8139   /// CallOperand - If this is the result output operand or a clobber
8140   /// this is null, otherwise it is the incoming operand to the CallInst.
8141   /// This gets modified as the asm is processed.
8142   SDValue CallOperand;
8143 
8144   /// AssignedRegs - If this is a register or register class operand, this
8145   /// contains the set of register corresponding to the operand.
8146   RegsForValue AssignedRegs;
8147 
8148   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8149     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8150   }
8151 
8152   /// Whether or not this operand accesses memory
8153   bool hasMemory(const TargetLowering &TLI) const {
8154     // Indirect operand accesses access memory.
8155     if (isIndirect)
8156       return true;
8157 
8158     for (const auto &Code : Codes)
8159       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8160         return true;
8161 
8162     return false;
8163   }
8164 
8165   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8166   /// corresponds to.  If there is no Value* for this operand, it returns
8167   /// MVT::Other.
8168   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8169                            const DataLayout &DL) const {
8170     if (!CallOperandVal) return MVT::Other;
8171 
8172     if (isa<BasicBlock>(CallOperandVal))
8173       return TLI.getProgramPointerTy(DL);
8174 
8175     llvm::Type *OpTy = CallOperandVal->getType();
8176 
8177     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8178     // If this is an indirect operand, the operand is a pointer to the
8179     // accessed type.
8180     if (isIndirect) {
8181       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
8182       if (!PtrTy)
8183         report_fatal_error("Indirect operand for inline asm not a pointer!");
8184       OpTy = PtrTy->getElementType();
8185     }
8186 
8187     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8188     if (StructType *STy = dyn_cast<StructType>(OpTy))
8189       if (STy->getNumElements() == 1)
8190         OpTy = STy->getElementType(0);
8191 
8192     // If OpTy is not a single value, it may be a struct/union that we
8193     // can tile with integers.
8194     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8195       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8196       switch (BitSize) {
8197       default: break;
8198       case 1:
8199       case 8:
8200       case 16:
8201       case 32:
8202       case 64:
8203       case 128:
8204         OpTy = IntegerType::get(Context, BitSize);
8205         break;
8206       }
8207     }
8208 
8209     return TLI.getAsmOperandValueType(DL, OpTy, true);
8210   }
8211 };
8212 
8213 
8214 } // end anonymous namespace
8215 
8216 /// Make sure that the output operand \p OpInfo and its corresponding input
8217 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8218 /// out).
8219 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8220                                SDISelAsmOperandInfo &MatchingOpInfo,
8221                                SelectionDAG &DAG) {
8222   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8223     return;
8224 
8225   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8226   const auto &TLI = DAG.getTargetLoweringInfo();
8227 
8228   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8229       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8230                                        OpInfo.ConstraintVT);
8231   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8232       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8233                                        MatchingOpInfo.ConstraintVT);
8234   if ((OpInfo.ConstraintVT.isInteger() !=
8235        MatchingOpInfo.ConstraintVT.isInteger()) ||
8236       (MatchRC.second != InputRC.second)) {
8237     // FIXME: error out in a more elegant fashion
8238     report_fatal_error("Unsupported asm: input constraint"
8239                        " with a matching output constraint of"
8240                        " incompatible type!");
8241   }
8242   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8243 }
8244 
8245 /// Get a direct memory input to behave well as an indirect operand.
8246 /// This may introduce stores, hence the need for a \p Chain.
8247 /// \return The (possibly updated) chain.
8248 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8249                                         SDISelAsmOperandInfo &OpInfo,
8250                                         SelectionDAG &DAG) {
8251   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8252 
8253   // If we don't have an indirect input, put it in the constpool if we can,
8254   // otherwise spill it to a stack slot.
8255   // TODO: This isn't quite right. We need to handle these according to
8256   // the addressing mode that the constraint wants. Also, this may take
8257   // an additional register for the computation and we don't want that
8258   // either.
8259 
8260   // If the operand is a float, integer, or vector constant, spill to a
8261   // constant pool entry to get its address.
8262   const Value *OpVal = OpInfo.CallOperandVal;
8263   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8264       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8265     OpInfo.CallOperand = DAG.getConstantPool(
8266         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8267     return Chain;
8268   }
8269 
8270   // Otherwise, create a stack slot and emit a store to it before the asm.
8271   Type *Ty = OpVal->getType();
8272   auto &DL = DAG.getDataLayout();
8273   uint64_t TySize = DL.getTypeAllocSize(Ty);
8274   MachineFunction &MF = DAG.getMachineFunction();
8275   int SSFI = MF.getFrameInfo().CreateStackObject(
8276       TySize, DL.getPrefTypeAlign(Ty), false);
8277   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8278   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8279                             MachinePointerInfo::getFixedStack(MF, SSFI),
8280                             TLI.getMemValueType(DL, Ty));
8281   OpInfo.CallOperand = StackSlot;
8282 
8283   return Chain;
8284 }
8285 
8286 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8287 /// specified operand.  We prefer to assign virtual registers, to allow the
8288 /// register allocator to handle the assignment process.  However, if the asm
8289 /// uses features that we can't model on machineinstrs, we have SDISel do the
8290 /// allocation.  This produces generally horrible, but correct, code.
8291 ///
8292 ///   OpInfo describes the operand
8293 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8294 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8295                                  SDISelAsmOperandInfo &OpInfo,
8296                                  SDISelAsmOperandInfo &RefOpInfo) {
8297   LLVMContext &Context = *DAG.getContext();
8298   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8299 
8300   MachineFunction &MF = DAG.getMachineFunction();
8301   SmallVector<unsigned, 4> Regs;
8302   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8303 
8304   // No work to do for memory operations.
8305   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8306     return;
8307 
8308   // If this is a constraint for a single physreg, or a constraint for a
8309   // register class, find it.
8310   unsigned AssignedReg;
8311   const TargetRegisterClass *RC;
8312   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8313       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8314   // RC is unset only on failure. Return immediately.
8315   if (!RC)
8316     return;
8317 
8318   // Get the actual register value type.  This is important, because the user
8319   // may have asked for (e.g.) the AX register in i32 type.  We need to
8320   // remember that AX is actually i16 to get the right extension.
8321   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8322 
8323   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8324     // If this is an FP operand in an integer register (or visa versa), or more
8325     // generally if the operand value disagrees with the register class we plan
8326     // to stick it in, fix the operand type.
8327     //
8328     // If this is an input value, the bitcast to the new type is done now.
8329     // Bitcast for output value is done at the end of visitInlineAsm().
8330     if ((OpInfo.Type == InlineAsm::isOutput ||
8331          OpInfo.Type == InlineAsm::isInput) &&
8332         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8333       // Try to convert to the first EVT that the reg class contains.  If the
8334       // types are identical size, use a bitcast to convert (e.g. two differing
8335       // vector types).  Note: output bitcast is done at the end of
8336       // visitInlineAsm().
8337       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8338         // Exclude indirect inputs while they are unsupported because the code
8339         // to perform the load is missing and thus OpInfo.CallOperand still
8340         // refers to the input address rather than the pointed-to value.
8341         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8342           OpInfo.CallOperand =
8343               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8344         OpInfo.ConstraintVT = RegVT;
8345         // If the operand is an FP value and we want it in integer registers,
8346         // use the corresponding integer type. This turns an f64 value into
8347         // i64, which can be passed with two i32 values on a 32-bit machine.
8348       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8349         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8350         if (OpInfo.Type == InlineAsm::isInput)
8351           OpInfo.CallOperand =
8352               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8353         OpInfo.ConstraintVT = VT;
8354       }
8355     }
8356   }
8357 
8358   // No need to allocate a matching input constraint since the constraint it's
8359   // matching to has already been allocated.
8360   if (OpInfo.isMatchingInputConstraint())
8361     return;
8362 
8363   EVT ValueVT = OpInfo.ConstraintVT;
8364   if (OpInfo.ConstraintVT == MVT::Other)
8365     ValueVT = RegVT;
8366 
8367   // Initialize NumRegs.
8368   unsigned NumRegs = 1;
8369   if (OpInfo.ConstraintVT != MVT::Other)
8370     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8371 
8372   // If this is a constraint for a specific physical register, like {r17},
8373   // assign it now.
8374 
8375   // If this associated to a specific register, initialize iterator to correct
8376   // place. If virtual, make sure we have enough registers
8377 
8378   // Initialize iterator if necessary
8379   TargetRegisterClass::iterator I = RC->begin();
8380   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8381 
8382   // Do not check for single registers.
8383   if (AssignedReg) {
8384       for (; *I != AssignedReg; ++I)
8385         assert(I != RC->end() && "AssignedReg should be member of RC");
8386   }
8387 
8388   for (; NumRegs; --NumRegs, ++I) {
8389     assert(I != RC->end() && "Ran out of registers to allocate!");
8390     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8391     Regs.push_back(R);
8392   }
8393 
8394   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8395 }
8396 
8397 static unsigned
8398 findMatchingInlineAsmOperand(unsigned OperandNo,
8399                              const std::vector<SDValue> &AsmNodeOperands) {
8400   // Scan until we find the definition we already emitted of this operand.
8401   unsigned CurOp = InlineAsm::Op_FirstOperand;
8402   for (; OperandNo; --OperandNo) {
8403     // Advance to the next operand.
8404     unsigned OpFlag =
8405         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8406     assert((InlineAsm::isRegDefKind(OpFlag) ||
8407             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8408             InlineAsm::isMemKind(OpFlag)) &&
8409            "Skipped past definitions?");
8410     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8411   }
8412   return CurOp;
8413 }
8414 
8415 namespace {
8416 
8417 class ExtraFlags {
8418   unsigned Flags = 0;
8419 
8420 public:
8421   explicit ExtraFlags(const CallBase &Call) {
8422     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8423     if (IA->hasSideEffects())
8424       Flags |= InlineAsm::Extra_HasSideEffects;
8425     if (IA->isAlignStack())
8426       Flags |= InlineAsm::Extra_IsAlignStack;
8427     if (Call.isConvergent())
8428       Flags |= InlineAsm::Extra_IsConvergent;
8429     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8430   }
8431 
8432   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8433     // Ideally, we would only check against memory constraints.  However, the
8434     // meaning of an Other constraint can be target-specific and we can't easily
8435     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8436     // for Other constraints as well.
8437     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8438         OpInfo.ConstraintType == TargetLowering::C_Other) {
8439       if (OpInfo.Type == InlineAsm::isInput)
8440         Flags |= InlineAsm::Extra_MayLoad;
8441       else if (OpInfo.Type == InlineAsm::isOutput)
8442         Flags |= InlineAsm::Extra_MayStore;
8443       else if (OpInfo.Type == InlineAsm::isClobber)
8444         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8445     }
8446   }
8447 
8448   unsigned get() const { return Flags; }
8449 };
8450 
8451 } // end anonymous namespace
8452 
8453 /// visitInlineAsm - Handle a call to an InlineAsm object.
8454 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8455                                          const BasicBlock *EHPadBB) {
8456   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8457 
8458   /// ConstraintOperands - Information about all of the constraints.
8459   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8460 
8461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8462   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8463       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8464 
8465   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8466   // AsmDialect, MayLoad, MayStore).
8467   bool HasSideEffect = IA->hasSideEffects();
8468   ExtraFlags ExtraInfo(Call);
8469 
8470   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8471   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8472   unsigned NumMatchingOps = 0;
8473   for (auto &T : TargetConstraints) {
8474     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8475     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8476 
8477     // Compute the value type for each operand.
8478     if (OpInfo.Type == InlineAsm::isInput ||
8479         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8480       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8481 
8482       // Process the call argument. BasicBlocks are labels, currently appearing
8483       // only in asm's.
8484       if (isa<CallBrInst>(Call) &&
8485           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8486                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8487                         NumMatchingOps) &&
8488           (NumMatchingOps == 0 ||
8489            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8490                         NumMatchingOps))) {
8491         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8492         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8493         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8494       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8495         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8496       } else {
8497         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8498       }
8499 
8500       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8501                                            DAG.getDataLayout());
8502       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8503     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8504       // The return value of the call is this value.  As such, there is no
8505       // corresponding argument.
8506       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8507       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8508         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8509             DAG.getDataLayout(), STy->getElementType(ResNo));
8510       } else {
8511         assert(ResNo == 0 && "Asm only has one result!");
8512         OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
8513             DAG.getDataLayout(), Call.getType()).getSimpleVT();
8514       }
8515       ++ResNo;
8516     } else {
8517       OpInfo.ConstraintVT = MVT::Other;
8518     }
8519 
8520     if (OpInfo.hasMatchingInput())
8521       ++NumMatchingOps;
8522 
8523     if (!HasSideEffect)
8524       HasSideEffect = OpInfo.hasMemory(TLI);
8525 
8526     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8527     // FIXME: Could we compute this on OpInfo rather than T?
8528 
8529     // Compute the constraint code and ConstraintType to use.
8530     TLI.ComputeConstraintToUse(T, SDValue());
8531 
8532     if (T.ConstraintType == TargetLowering::C_Immediate &&
8533         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8534       // We've delayed emitting a diagnostic like the "n" constraint because
8535       // inlining could cause an integer showing up.
8536       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8537                                           "' expects an integer constant "
8538                                           "expression");
8539 
8540     ExtraInfo.update(T);
8541   }
8542 
8543   // We won't need to flush pending loads if this asm doesn't touch
8544   // memory and is nonvolatile.
8545   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8546 
8547   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8548   if (EmitEHLabels) {
8549     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8550   }
8551   bool IsCallBr = isa<CallBrInst>(Call);
8552 
8553   if (IsCallBr || EmitEHLabels) {
8554     // If this is a callbr or invoke we need to flush pending exports since
8555     // inlineasm_br and invoke are terminators.
8556     // We need to do this before nodes are glued to the inlineasm_br node.
8557     Chain = getControlRoot();
8558   }
8559 
8560   MCSymbol *BeginLabel = nullptr;
8561   if (EmitEHLabels) {
8562     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8563   }
8564 
8565   // Second pass over the constraints: compute which constraint option to use.
8566   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8567     // If this is an output operand with a matching input operand, look up the
8568     // matching input. If their types mismatch, e.g. one is an integer, the
8569     // other is floating point, or their sizes are different, flag it as an
8570     // error.
8571     if (OpInfo.hasMatchingInput()) {
8572       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8573       patchMatchingInput(OpInfo, Input, DAG);
8574     }
8575 
8576     // Compute the constraint code and ConstraintType to use.
8577     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8578 
8579     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8580         OpInfo.Type == InlineAsm::isClobber)
8581       continue;
8582 
8583     // If this is a memory input, and if the operand is not indirect, do what we
8584     // need to provide an address for the memory input.
8585     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8586         !OpInfo.isIndirect) {
8587       assert((OpInfo.isMultipleAlternative ||
8588               (OpInfo.Type == InlineAsm::isInput)) &&
8589              "Can only indirectify direct input operands!");
8590 
8591       // Memory operands really want the address of the value.
8592       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8593 
8594       // There is no longer a Value* corresponding to this operand.
8595       OpInfo.CallOperandVal = nullptr;
8596 
8597       // It is now an indirect operand.
8598       OpInfo.isIndirect = true;
8599     }
8600 
8601   }
8602 
8603   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8604   std::vector<SDValue> AsmNodeOperands;
8605   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8606   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8607       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8608 
8609   // If we have a !srcloc metadata node associated with it, we want to attach
8610   // this to the ultimately generated inline asm machineinstr.  To do this, we
8611   // pass in the third operand as this (potentially null) inline asm MDNode.
8612   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8613   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8614 
8615   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8616   // bits as operand 3.
8617   AsmNodeOperands.push_back(DAG.getTargetConstant(
8618       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8619 
8620   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8621   // this, assign virtual and physical registers for inputs and otput.
8622   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8623     // Assign Registers.
8624     SDISelAsmOperandInfo &RefOpInfo =
8625         OpInfo.isMatchingInputConstraint()
8626             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8627             : OpInfo;
8628     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8629 
8630     auto DetectWriteToReservedRegister = [&]() {
8631       const MachineFunction &MF = DAG.getMachineFunction();
8632       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8633       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8634         if (Register::isPhysicalRegister(Reg) &&
8635             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8636           const char *RegName = TRI.getName(Reg);
8637           emitInlineAsmError(Call, "write to reserved register '" +
8638                                        Twine(RegName) + "'");
8639           return true;
8640         }
8641       }
8642       return false;
8643     };
8644 
8645     switch (OpInfo.Type) {
8646     case InlineAsm::isOutput:
8647       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8648         unsigned ConstraintID =
8649             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8650         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8651                "Failed to convert memory constraint code to constraint id.");
8652 
8653         // Add information to the INLINEASM node to know about this output.
8654         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8655         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8656         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8657                                                         MVT::i32));
8658         AsmNodeOperands.push_back(OpInfo.CallOperand);
8659       } else {
8660         // Otherwise, this outputs to a register (directly for C_Register /
8661         // C_RegisterClass, and a target-defined fashion for
8662         // C_Immediate/C_Other). Find a register that we can use.
8663         if (OpInfo.AssignedRegs.Regs.empty()) {
8664           emitInlineAsmError(
8665               Call, "couldn't allocate output register for constraint '" +
8666                         Twine(OpInfo.ConstraintCode) + "'");
8667           return;
8668         }
8669 
8670         if (DetectWriteToReservedRegister())
8671           return;
8672 
8673         // Add information to the INLINEASM node to know that this register is
8674         // set.
8675         OpInfo.AssignedRegs.AddInlineAsmOperands(
8676             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8677                                   : InlineAsm::Kind_RegDef,
8678             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8679       }
8680       break;
8681 
8682     case InlineAsm::isInput: {
8683       SDValue InOperandVal = OpInfo.CallOperand;
8684 
8685       if (OpInfo.isMatchingInputConstraint()) {
8686         // If this is required to match an output register we have already set,
8687         // just use its register.
8688         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8689                                                   AsmNodeOperands);
8690         unsigned OpFlag =
8691           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8692         if (InlineAsm::isRegDefKind(OpFlag) ||
8693             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8694           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8695           if (OpInfo.isIndirect) {
8696             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8697             emitInlineAsmError(Call, "inline asm not supported yet: "
8698                                      "don't know how to handle tied "
8699                                      "indirect register inputs");
8700             return;
8701           }
8702 
8703           SmallVector<unsigned, 4> Regs;
8704           MachineFunction &MF = DAG.getMachineFunction();
8705           MachineRegisterInfo &MRI = MF.getRegInfo();
8706           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8707           RegisterSDNode *R = dyn_cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8708           Register TiedReg = R->getReg();
8709           MVT RegVT = R->getSimpleValueType(0);
8710           const TargetRegisterClass *RC = TiedReg.isVirtual() ?
8711             MRI.getRegClass(TiedReg) : TRI.getMinimalPhysRegClass(TiedReg);
8712           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8713           for (unsigned i = 0; i != NumRegs; ++i)
8714             Regs.push_back(MRI.createVirtualRegister(RC));
8715 
8716           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8717 
8718           SDLoc dl = getCurSDLoc();
8719           // Use the produced MatchedRegs object to
8720           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8721           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8722                                            true, OpInfo.getMatchedOperand(), dl,
8723                                            DAG, AsmNodeOperands);
8724           break;
8725         }
8726 
8727         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8728         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8729                "Unexpected number of operands");
8730         // Add information to the INLINEASM node to know about this input.
8731         // See InlineAsm.h isUseOperandTiedToDef.
8732         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8733         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8734                                                     OpInfo.getMatchedOperand());
8735         AsmNodeOperands.push_back(DAG.getTargetConstant(
8736             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8737         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8738         break;
8739       }
8740 
8741       // Treat indirect 'X' constraint as memory.
8742       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8743           OpInfo.isIndirect)
8744         OpInfo.ConstraintType = TargetLowering::C_Memory;
8745 
8746       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8747           OpInfo.ConstraintType == TargetLowering::C_Other) {
8748         std::vector<SDValue> Ops;
8749         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8750                                           Ops, DAG);
8751         if (Ops.empty()) {
8752           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8753             if (isa<ConstantSDNode>(InOperandVal)) {
8754               emitInlineAsmError(Call, "value out of range for constraint '" +
8755                                            Twine(OpInfo.ConstraintCode) + "'");
8756               return;
8757             }
8758 
8759           emitInlineAsmError(Call,
8760                              "invalid operand for inline asm constraint '" +
8761                                  Twine(OpInfo.ConstraintCode) + "'");
8762           return;
8763         }
8764 
8765         // Add information to the INLINEASM node to know about this input.
8766         unsigned ResOpType =
8767           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8768         AsmNodeOperands.push_back(DAG.getTargetConstant(
8769             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8770         llvm::append_range(AsmNodeOperands, Ops);
8771         break;
8772       }
8773 
8774       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8775         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8776         assert(InOperandVal.getValueType() ==
8777                    TLI.getPointerTy(DAG.getDataLayout()) &&
8778                "Memory operands expect pointer values");
8779 
8780         unsigned ConstraintID =
8781             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8782         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8783                "Failed to convert memory constraint code to constraint id.");
8784 
8785         // Add information to the INLINEASM node to know about this input.
8786         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8787         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8788         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8789                                                         getCurSDLoc(),
8790                                                         MVT::i32));
8791         AsmNodeOperands.push_back(InOperandVal);
8792         break;
8793       }
8794 
8795       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8796               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8797              "Unknown constraint type!");
8798 
8799       // TODO: Support this.
8800       if (OpInfo.isIndirect) {
8801         emitInlineAsmError(
8802             Call, "Don't know how to handle indirect register inputs yet "
8803                   "for constraint '" +
8804                       Twine(OpInfo.ConstraintCode) + "'");
8805         return;
8806       }
8807 
8808       // Copy the input into the appropriate registers.
8809       if (OpInfo.AssignedRegs.Regs.empty()) {
8810         emitInlineAsmError(Call,
8811                            "couldn't allocate input reg for constraint '" +
8812                                Twine(OpInfo.ConstraintCode) + "'");
8813         return;
8814       }
8815 
8816       if (DetectWriteToReservedRegister())
8817         return;
8818 
8819       SDLoc dl = getCurSDLoc();
8820 
8821       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8822                                         &Call);
8823 
8824       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8825                                                dl, DAG, AsmNodeOperands);
8826       break;
8827     }
8828     case InlineAsm::isClobber:
8829       // Add the clobbered value to the operand list, so that the register
8830       // allocator is aware that the physreg got clobbered.
8831       if (!OpInfo.AssignedRegs.Regs.empty())
8832         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8833                                                  false, 0, getCurSDLoc(), DAG,
8834                                                  AsmNodeOperands);
8835       break;
8836     }
8837   }
8838 
8839   // Finish up input operands.  Set the input chain and add the flag last.
8840   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8841   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8842 
8843   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8844   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8845                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8846   Flag = Chain.getValue(1);
8847 
8848   // Do additional work to generate outputs.
8849 
8850   SmallVector<EVT, 1> ResultVTs;
8851   SmallVector<SDValue, 1> ResultValues;
8852   SmallVector<SDValue, 8> OutChains;
8853 
8854   llvm::Type *CallResultType = Call.getType();
8855   ArrayRef<Type *> ResultTypes;
8856   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8857     ResultTypes = StructResult->elements();
8858   else if (!CallResultType->isVoidTy())
8859     ResultTypes = makeArrayRef(CallResultType);
8860 
8861   auto CurResultType = ResultTypes.begin();
8862   auto handleRegAssign = [&](SDValue V) {
8863     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8864     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8865     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8866     ++CurResultType;
8867     // If the type of the inline asm call site return value is different but has
8868     // same size as the type of the asm output bitcast it.  One example of this
8869     // is for vectors with different width / number of elements.  This can
8870     // happen for register classes that can contain multiple different value
8871     // types.  The preg or vreg allocated may not have the same VT as was
8872     // expected.
8873     //
8874     // This can also happen for a return value that disagrees with the register
8875     // class it is put in, eg. a double in a general-purpose register on a
8876     // 32-bit machine.
8877     if (ResultVT != V.getValueType() &&
8878         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8879       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8880     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8881              V.getValueType().isInteger()) {
8882       // If a result value was tied to an input value, the computed result
8883       // may have a wider width than the expected result.  Extract the
8884       // relevant portion.
8885       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8886     }
8887     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8888     ResultVTs.push_back(ResultVT);
8889     ResultValues.push_back(V);
8890   };
8891 
8892   // Deal with output operands.
8893   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8894     if (OpInfo.Type == InlineAsm::isOutput) {
8895       SDValue Val;
8896       // Skip trivial output operands.
8897       if (OpInfo.AssignedRegs.Regs.empty())
8898         continue;
8899 
8900       switch (OpInfo.ConstraintType) {
8901       case TargetLowering::C_Register:
8902       case TargetLowering::C_RegisterClass:
8903         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8904                                                   Chain, &Flag, &Call);
8905         break;
8906       case TargetLowering::C_Immediate:
8907       case TargetLowering::C_Other:
8908         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8909                                               OpInfo, DAG);
8910         break;
8911       case TargetLowering::C_Memory:
8912         break; // Already handled.
8913       case TargetLowering::C_Unknown:
8914         assert(false && "Unexpected unknown constraint");
8915       }
8916 
8917       // Indirect output manifest as stores. Record output chains.
8918       if (OpInfo.isIndirect) {
8919         const Value *Ptr = OpInfo.CallOperandVal;
8920         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8921         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8922                                      MachinePointerInfo(Ptr));
8923         OutChains.push_back(Store);
8924       } else {
8925         // generate CopyFromRegs to associated registers.
8926         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8927         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8928           for (const SDValue &V : Val->op_values())
8929             handleRegAssign(V);
8930         } else
8931           handleRegAssign(Val);
8932       }
8933     }
8934   }
8935 
8936   // Set results.
8937   if (!ResultValues.empty()) {
8938     assert(CurResultType == ResultTypes.end() &&
8939            "Mismatch in number of ResultTypes");
8940     assert(ResultValues.size() == ResultTypes.size() &&
8941            "Mismatch in number of output operands in asm result");
8942 
8943     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8944                             DAG.getVTList(ResultVTs), ResultValues);
8945     setValue(&Call, V);
8946   }
8947 
8948   // Collect store chains.
8949   if (!OutChains.empty())
8950     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8951 
8952   if (EmitEHLabels) {
8953     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
8954   }
8955 
8956   // Only Update Root if inline assembly has a memory effect.
8957   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
8958       EmitEHLabels)
8959     DAG.setRoot(Chain);
8960 }
8961 
8962 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8963                                              const Twine &Message) {
8964   LLVMContext &Ctx = *DAG.getContext();
8965   Ctx.emitError(&Call, Message);
8966 
8967   // Make sure we leave the DAG in a valid state
8968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8969   SmallVector<EVT, 1> ValueVTs;
8970   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8971 
8972   if (ValueVTs.empty())
8973     return;
8974 
8975   SmallVector<SDValue, 1> Ops;
8976   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8977     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8978 
8979   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8980 }
8981 
8982 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8983   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8984                           MVT::Other, getRoot(),
8985                           getValue(I.getArgOperand(0)),
8986                           DAG.getSrcValue(I.getArgOperand(0))));
8987 }
8988 
8989 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8991   const DataLayout &DL = DAG.getDataLayout();
8992   SDValue V = DAG.getVAArg(
8993       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8994       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8995       DL.getABITypeAlign(I.getType()).value());
8996   DAG.setRoot(V.getValue(1));
8997 
8998   if (I.getType()->isPointerTy())
8999     V = DAG.getPtrExtOrTrunc(
9000         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9001   setValue(&I, V);
9002 }
9003 
9004 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9005   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9006                           MVT::Other, getRoot(),
9007                           getValue(I.getArgOperand(0)),
9008                           DAG.getSrcValue(I.getArgOperand(0))));
9009 }
9010 
9011 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9012   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9013                           MVT::Other, getRoot(),
9014                           getValue(I.getArgOperand(0)),
9015                           getValue(I.getArgOperand(1)),
9016                           DAG.getSrcValue(I.getArgOperand(0)),
9017                           DAG.getSrcValue(I.getArgOperand(1))));
9018 }
9019 
9020 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9021                                                     const Instruction &I,
9022                                                     SDValue Op) {
9023   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9024   if (!Range)
9025     return Op;
9026 
9027   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9028   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9029     return Op;
9030 
9031   APInt Lo = CR.getUnsignedMin();
9032   if (!Lo.isMinValue())
9033     return Op;
9034 
9035   APInt Hi = CR.getUnsignedMax();
9036   unsigned Bits = std::max(Hi.getActiveBits(),
9037                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9038 
9039   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9040 
9041   SDLoc SL = getCurSDLoc();
9042 
9043   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9044                              DAG.getValueType(SmallVT));
9045   unsigned NumVals = Op.getNode()->getNumValues();
9046   if (NumVals == 1)
9047     return ZExt;
9048 
9049   SmallVector<SDValue, 4> Ops;
9050 
9051   Ops.push_back(ZExt);
9052   for (unsigned I = 1; I != NumVals; ++I)
9053     Ops.push_back(Op.getValue(I));
9054 
9055   return DAG.getMergeValues(Ops, SL);
9056 }
9057 
9058 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9059 /// the call being lowered.
9060 ///
9061 /// This is a helper for lowering intrinsics that follow a target calling
9062 /// convention or require stack pointer adjustment. Only a subset of the
9063 /// intrinsic's operands need to participate in the calling convention.
9064 void SelectionDAGBuilder::populateCallLoweringInfo(
9065     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9066     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9067     bool IsPatchPoint) {
9068   TargetLowering::ArgListTy Args;
9069   Args.reserve(NumArgs);
9070 
9071   // Populate the argument list.
9072   // Attributes for args start at offset 1, after the return attribute.
9073   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9074        ArgI != ArgE; ++ArgI) {
9075     const Value *V = Call->getOperand(ArgI);
9076 
9077     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9078 
9079     TargetLowering::ArgListEntry Entry;
9080     Entry.Node = getValue(V);
9081     Entry.Ty = V->getType();
9082     Entry.setAttributes(Call, ArgI);
9083     Args.push_back(Entry);
9084   }
9085 
9086   CLI.setDebugLoc(getCurSDLoc())
9087       .setChain(getRoot())
9088       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9089       .setDiscardResult(Call->use_empty())
9090       .setIsPatchPoint(IsPatchPoint)
9091       .setIsPreallocated(
9092           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9093 }
9094 
9095 /// Add a stack map intrinsic call's live variable operands to a stackmap
9096 /// or patchpoint target node's operand list.
9097 ///
9098 /// Constants are converted to TargetConstants purely as an optimization to
9099 /// avoid constant materialization and register allocation.
9100 ///
9101 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9102 /// generate addess computation nodes, and so FinalizeISel can convert the
9103 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9104 /// address materialization and register allocation, but may also be required
9105 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9106 /// alloca in the entry block, then the runtime may assume that the alloca's
9107 /// StackMap location can be read immediately after compilation and that the
9108 /// location is valid at any point during execution (this is similar to the
9109 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9110 /// only available in a register, then the runtime would need to trap when
9111 /// execution reaches the StackMap in order to read the alloca's location.
9112 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9113                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9114                                 SelectionDAGBuilder &Builder) {
9115   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9116     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9117     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9118       Ops.push_back(
9119         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9120       Ops.push_back(
9121         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9122     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9123       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9124       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9125           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9126     } else
9127       Ops.push_back(OpVal);
9128   }
9129 }
9130 
9131 /// Lower llvm.experimental.stackmap directly to its target opcode.
9132 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9133   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9134   //                                  [live variables...])
9135 
9136   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9137 
9138   SDValue Chain, InFlag, Callee, NullPtr;
9139   SmallVector<SDValue, 32> Ops;
9140 
9141   SDLoc DL = getCurSDLoc();
9142   Callee = getValue(CI.getCalledOperand());
9143   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9144 
9145   // The stackmap intrinsic only records the live variables (the arguments
9146   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9147   // intrinsic, this won't be lowered to a function call. This means we don't
9148   // have to worry about calling conventions and target specific lowering code.
9149   // Instead we perform the call lowering right here.
9150   //
9151   // chain, flag = CALLSEQ_START(chain, 0, 0)
9152   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9153   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9154   //
9155   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9156   InFlag = Chain.getValue(1);
9157 
9158   // Add the <id> and <numBytes> constants.
9159   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9160   Ops.push_back(DAG.getTargetConstant(
9161                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9162   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9163   Ops.push_back(DAG.getTargetConstant(
9164                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9165                   MVT::i32));
9166 
9167   // Push live variables for the stack map.
9168   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9169 
9170   // We are not pushing any register mask info here on the operands list,
9171   // because the stackmap doesn't clobber anything.
9172 
9173   // Push the chain and the glue flag.
9174   Ops.push_back(Chain);
9175   Ops.push_back(InFlag);
9176 
9177   // Create the STACKMAP node.
9178   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9179   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9180   Chain = SDValue(SM, 0);
9181   InFlag = Chain.getValue(1);
9182 
9183   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9184 
9185   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9186 
9187   // Set the root to the target-lowered call chain.
9188   DAG.setRoot(Chain);
9189 
9190   // Inform the Frame Information that we have a stackmap in this function.
9191   FuncInfo.MF->getFrameInfo().setHasStackMap();
9192 }
9193 
9194 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9195 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9196                                           const BasicBlock *EHPadBB) {
9197   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9198   //                                                 i32 <numBytes>,
9199   //                                                 i8* <target>,
9200   //                                                 i32 <numArgs>,
9201   //                                                 [Args...],
9202   //                                                 [live variables...])
9203 
9204   CallingConv::ID CC = CB.getCallingConv();
9205   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9206   bool HasDef = !CB.getType()->isVoidTy();
9207   SDLoc dl = getCurSDLoc();
9208   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9209 
9210   // Handle immediate and symbolic callees.
9211   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9212     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9213                                    /*isTarget=*/true);
9214   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9215     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9216                                          SDLoc(SymbolicCallee),
9217                                          SymbolicCallee->getValueType(0));
9218 
9219   // Get the real number of arguments participating in the call <numArgs>
9220   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9221   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9222 
9223   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9224   // Intrinsics include all meta-operands up to but not including CC.
9225   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9226   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9227          "Not enough arguments provided to the patchpoint intrinsic");
9228 
9229   // For AnyRegCC the arguments are lowered later on manually.
9230   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9231   Type *ReturnTy =
9232       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9233 
9234   TargetLowering::CallLoweringInfo CLI(DAG);
9235   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9236                            ReturnTy, true);
9237   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9238 
9239   SDNode *CallEnd = Result.second.getNode();
9240   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9241     CallEnd = CallEnd->getOperand(0).getNode();
9242 
9243   /// Get a call instruction from the call sequence chain.
9244   /// Tail calls are not allowed.
9245   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9246          "Expected a callseq node.");
9247   SDNode *Call = CallEnd->getOperand(0).getNode();
9248   bool HasGlue = Call->getGluedNode();
9249 
9250   // Replace the target specific call node with the patchable intrinsic.
9251   SmallVector<SDValue, 8> Ops;
9252 
9253   // Add the <id> and <numBytes> constants.
9254   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9255   Ops.push_back(DAG.getTargetConstant(
9256                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9257   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9258   Ops.push_back(DAG.getTargetConstant(
9259                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9260                   MVT::i32));
9261 
9262   // Add the callee.
9263   Ops.push_back(Callee);
9264 
9265   // Adjust <numArgs> to account for any arguments that have been passed on the
9266   // stack instead.
9267   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9268   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9269   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9270   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9271 
9272   // Add the calling convention
9273   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9274 
9275   // Add the arguments we omitted previously. The register allocator should
9276   // place these in any free register.
9277   if (IsAnyRegCC)
9278     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9279       Ops.push_back(getValue(CB.getArgOperand(i)));
9280 
9281   // Push the arguments from the call instruction up to the register mask.
9282   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9283   Ops.append(Call->op_begin() + 2, e);
9284 
9285   // Push live variables for the stack map.
9286   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9287 
9288   // Push the register mask info.
9289   if (HasGlue)
9290     Ops.push_back(*(Call->op_end()-2));
9291   else
9292     Ops.push_back(*(Call->op_end()-1));
9293 
9294   // Push the chain (this is originally the first operand of the call, but
9295   // becomes now the last or second to last operand).
9296   Ops.push_back(*(Call->op_begin()));
9297 
9298   // Push the glue flag (last operand).
9299   if (HasGlue)
9300     Ops.push_back(*(Call->op_end()-1));
9301 
9302   SDVTList NodeTys;
9303   if (IsAnyRegCC && HasDef) {
9304     // Create the return types based on the intrinsic definition
9305     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9306     SmallVector<EVT, 3> ValueVTs;
9307     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9308     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9309 
9310     // There is always a chain and a glue type at the end
9311     ValueVTs.push_back(MVT::Other);
9312     ValueVTs.push_back(MVT::Glue);
9313     NodeTys = DAG.getVTList(ValueVTs);
9314   } else
9315     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9316 
9317   // Replace the target specific call node with a PATCHPOINT node.
9318   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9319                                          dl, NodeTys, Ops);
9320 
9321   // Update the NodeMap.
9322   if (HasDef) {
9323     if (IsAnyRegCC)
9324       setValue(&CB, SDValue(MN, 0));
9325     else
9326       setValue(&CB, Result.first);
9327   }
9328 
9329   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9330   // call sequence. Furthermore the location of the chain and glue can change
9331   // when the AnyReg calling convention is used and the intrinsic returns a
9332   // value.
9333   if (IsAnyRegCC && HasDef) {
9334     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9335     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9336     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9337   } else
9338     DAG.ReplaceAllUsesWith(Call, MN);
9339   DAG.DeleteNode(Call);
9340 
9341   // Inform the Frame Information that we have a patchpoint in this function.
9342   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9343 }
9344 
9345 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9346                                             unsigned Intrinsic) {
9347   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9348   SDValue Op1 = getValue(I.getArgOperand(0));
9349   SDValue Op2;
9350   if (I.getNumArgOperands() > 1)
9351     Op2 = getValue(I.getArgOperand(1));
9352   SDLoc dl = getCurSDLoc();
9353   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9354   SDValue Res;
9355   SDNodeFlags SDFlags;
9356   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9357     SDFlags.copyFMF(*FPMO);
9358 
9359   switch (Intrinsic) {
9360   case Intrinsic::vector_reduce_fadd:
9361     if (SDFlags.hasAllowReassociation())
9362       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9363                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9364                         SDFlags);
9365     else
9366       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9367     break;
9368   case Intrinsic::vector_reduce_fmul:
9369     if (SDFlags.hasAllowReassociation())
9370       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9371                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9372                         SDFlags);
9373     else
9374       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9375     break;
9376   case Intrinsic::vector_reduce_add:
9377     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9378     break;
9379   case Intrinsic::vector_reduce_mul:
9380     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9381     break;
9382   case Intrinsic::vector_reduce_and:
9383     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9384     break;
9385   case Intrinsic::vector_reduce_or:
9386     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9387     break;
9388   case Intrinsic::vector_reduce_xor:
9389     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9390     break;
9391   case Intrinsic::vector_reduce_smax:
9392     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9393     break;
9394   case Intrinsic::vector_reduce_smin:
9395     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9396     break;
9397   case Intrinsic::vector_reduce_umax:
9398     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9399     break;
9400   case Intrinsic::vector_reduce_umin:
9401     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9402     break;
9403   case Intrinsic::vector_reduce_fmax:
9404     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9405     break;
9406   case Intrinsic::vector_reduce_fmin:
9407     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9408     break;
9409   default:
9410     llvm_unreachable("Unhandled vector reduce intrinsic");
9411   }
9412   setValue(&I, Res);
9413 }
9414 
9415 /// Returns an AttributeList representing the attributes applied to the return
9416 /// value of the given call.
9417 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9418   SmallVector<Attribute::AttrKind, 2> Attrs;
9419   if (CLI.RetSExt)
9420     Attrs.push_back(Attribute::SExt);
9421   if (CLI.RetZExt)
9422     Attrs.push_back(Attribute::ZExt);
9423   if (CLI.IsInReg)
9424     Attrs.push_back(Attribute::InReg);
9425 
9426   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9427                             Attrs);
9428 }
9429 
9430 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9431 /// implementation, which just calls LowerCall.
9432 /// FIXME: When all targets are
9433 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9434 std::pair<SDValue, SDValue>
9435 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9436   // Handle the incoming return values from the call.
9437   CLI.Ins.clear();
9438   Type *OrigRetTy = CLI.RetTy;
9439   SmallVector<EVT, 4> RetTys;
9440   SmallVector<uint64_t, 4> Offsets;
9441   auto &DL = CLI.DAG.getDataLayout();
9442   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9443 
9444   if (CLI.IsPostTypeLegalization) {
9445     // If we are lowering a libcall after legalization, split the return type.
9446     SmallVector<EVT, 4> OldRetTys;
9447     SmallVector<uint64_t, 4> OldOffsets;
9448     RetTys.swap(OldRetTys);
9449     Offsets.swap(OldOffsets);
9450 
9451     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9452       EVT RetVT = OldRetTys[i];
9453       uint64_t Offset = OldOffsets[i];
9454       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9455       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9456       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9457       RetTys.append(NumRegs, RegisterVT);
9458       for (unsigned j = 0; j != NumRegs; ++j)
9459         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9460     }
9461   }
9462 
9463   SmallVector<ISD::OutputArg, 4> Outs;
9464   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9465 
9466   bool CanLowerReturn =
9467       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9468                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9469 
9470   SDValue DemoteStackSlot;
9471   int DemoteStackIdx = -100;
9472   if (!CanLowerReturn) {
9473     // FIXME: equivalent assert?
9474     // assert(!CS.hasInAllocaArgument() &&
9475     //        "sret demotion is incompatible with inalloca");
9476     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9477     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9478     MachineFunction &MF = CLI.DAG.getMachineFunction();
9479     DemoteStackIdx =
9480         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9481     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9482                                               DL.getAllocaAddrSpace());
9483 
9484     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9485     ArgListEntry Entry;
9486     Entry.Node = DemoteStackSlot;
9487     Entry.Ty = StackSlotPtrType;
9488     Entry.IsSExt = false;
9489     Entry.IsZExt = false;
9490     Entry.IsInReg = false;
9491     Entry.IsSRet = true;
9492     Entry.IsNest = false;
9493     Entry.IsByVal = false;
9494     Entry.IsByRef = false;
9495     Entry.IsReturned = false;
9496     Entry.IsSwiftSelf = false;
9497     Entry.IsSwiftAsync = false;
9498     Entry.IsSwiftError = false;
9499     Entry.IsCFGuardTarget = false;
9500     Entry.Alignment = Alignment;
9501     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9502     CLI.NumFixedArgs += 1;
9503     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9504 
9505     // sret demotion isn't compatible with tail-calls, since the sret argument
9506     // points into the callers stack frame.
9507     CLI.IsTailCall = false;
9508   } else {
9509     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9510         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9511     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9512       ISD::ArgFlagsTy Flags;
9513       if (NeedsRegBlock) {
9514         Flags.setInConsecutiveRegs();
9515         if (I == RetTys.size() - 1)
9516           Flags.setInConsecutiveRegsLast();
9517       }
9518       EVT VT = RetTys[I];
9519       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9520                                                      CLI.CallConv, VT);
9521       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9522                                                        CLI.CallConv, VT);
9523       for (unsigned i = 0; i != NumRegs; ++i) {
9524         ISD::InputArg MyFlags;
9525         MyFlags.Flags = Flags;
9526         MyFlags.VT = RegisterVT;
9527         MyFlags.ArgVT = VT;
9528         MyFlags.Used = CLI.IsReturnValueUsed;
9529         if (CLI.RetTy->isPointerTy()) {
9530           MyFlags.Flags.setPointer();
9531           MyFlags.Flags.setPointerAddrSpace(
9532               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9533         }
9534         if (CLI.RetSExt)
9535           MyFlags.Flags.setSExt();
9536         if (CLI.RetZExt)
9537           MyFlags.Flags.setZExt();
9538         if (CLI.IsInReg)
9539           MyFlags.Flags.setInReg();
9540         CLI.Ins.push_back(MyFlags);
9541       }
9542     }
9543   }
9544 
9545   // We push in swifterror return as the last element of CLI.Ins.
9546   ArgListTy &Args = CLI.getArgs();
9547   if (supportSwiftError()) {
9548     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9549       if (Args[i].IsSwiftError) {
9550         ISD::InputArg MyFlags;
9551         MyFlags.VT = getPointerTy(DL);
9552         MyFlags.ArgVT = EVT(getPointerTy(DL));
9553         MyFlags.Flags.setSwiftError();
9554         CLI.Ins.push_back(MyFlags);
9555       }
9556     }
9557   }
9558 
9559   // Handle all of the outgoing arguments.
9560   CLI.Outs.clear();
9561   CLI.OutVals.clear();
9562   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9563     SmallVector<EVT, 4> ValueVTs;
9564     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9565     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9566     Type *FinalType = Args[i].Ty;
9567     if (Args[i].IsByVal)
9568       FinalType = Args[i].IndirectType;
9569     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9570         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9571     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9572          ++Value) {
9573       EVT VT = ValueVTs[Value];
9574       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9575       SDValue Op = SDValue(Args[i].Node.getNode(),
9576                            Args[i].Node.getResNo() + Value);
9577       ISD::ArgFlagsTy Flags;
9578 
9579       // Certain targets (such as MIPS), may have a different ABI alignment
9580       // for a type depending on the context. Give the target a chance to
9581       // specify the alignment it wants.
9582       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9583       Flags.setOrigAlign(OriginalAlignment);
9584 
9585       if (Args[i].Ty->isPointerTy()) {
9586         Flags.setPointer();
9587         Flags.setPointerAddrSpace(
9588             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9589       }
9590       if (Args[i].IsZExt)
9591         Flags.setZExt();
9592       if (Args[i].IsSExt)
9593         Flags.setSExt();
9594       if (Args[i].IsInReg) {
9595         // If we are using vectorcall calling convention, a structure that is
9596         // passed InReg - is surely an HVA
9597         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9598             isa<StructType>(FinalType)) {
9599           // The first value of a structure is marked
9600           if (0 == Value)
9601             Flags.setHvaStart();
9602           Flags.setHva();
9603         }
9604         // Set InReg Flag
9605         Flags.setInReg();
9606       }
9607       if (Args[i].IsSRet)
9608         Flags.setSRet();
9609       if (Args[i].IsSwiftSelf)
9610         Flags.setSwiftSelf();
9611       if (Args[i].IsSwiftAsync)
9612         Flags.setSwiftAsync();
9613       if (Args[i].IsSwiftError)
9614         Flags.setSwiftError();
9615       if (Args[i].IsCFGuardTarget)
9616         Flags.setCFGuardTarget();
9617       if (Args[i].IsByVal)
9618         Flags.setByVal();
9619       if (Args[i].IsByRef)
9620         Flags.setByRef();
9621       if (Args[i].IsPreallocated) {
9622         Flags.setPreallocated();
9623         // Set the byval flag for CCAssignFn callbacks that don't know about
9624         // preallocated.  This way we can know how many bytes we should've
9625         // allocated and how many bytes a callee cleanup function will pop.  If
9626         // we port preallocated to more targets, we'll have to add custom
9627         // preallocated handling in the various CC lowering callbacks.
9628         Flags.setByVal();
9629       }
9630       if (Args[i].IsInAlloca) {
9631         Flags.setInAlloca();
9632         // Set the byval flag for CCAssignFn callbacks that don't know about
9633         // inalloca.  This way we can know how many bytes we should've allocated
9634         // and how many bytes a callee cleanup function will pop.  If we port
9635         // inalloca to more targets, we'll have to add custom inalloca handling
9636         // in the various CC lowering callbacks.
9637         Flags.setByVal();
9638       }
9639       Align MemAlign;
9640       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9641         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9642         Flags.setByValSize(FrameSize);
9643 
9644         // info is not there but there are cases it cannot get right.
9645         if (auto MA = Args[i].Alignment)
9646           MemAlign = *MA;
9647         else
9648           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9649       } else if (auto MA = Args[i].Alignment) {
9650         MemAlign = *MA;
9651       } else {
9652         MemAlign = OriginalAlignment;
9653       }
9654       Flags.setMemAlign(MemAlign);
9655       if (Args[i].IsNest)
9656         Flags.setNest();
9657       if (NeedsRegBlock)
9658         Flags.setInConsecutiveRegs();
9659 
9660       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9661                                                  CLI.CallConv, VT);
9662       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9663                                                         CLI.CallConv, VT);
9664       SmallVector<SDValue, 4> Parts(NumParts);
9665       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9666 
9667       if (Args[i].IsSExt)
9668         ExtendKind = ISD::SIGN_EXTEND;
9669       else if (Args[i].IsZExt)
9670         ExtendKind = ISD::ZERO_EXTEND;
9671 
9672       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9673       // for now.
9674       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9675           CanLowerReturn) {
9676         assert((CLI.RetTy == Args[i].Ty ||
9677                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9678                  CLI.RetTy->getPointerAddressSpace() ==
9679                      Args[i].Ty->getPointerAddressSpace())) &&
9680                RetTys.size() == NumValues && "unexpected use of 'returned'");
9681         // Before passing 'returned' to the target lowering code, ensure that
9682         // either the register MVT and the actual EVT are the same size or that
9683         // the return value and argument are extended in the same way; in these
9684         // cases it's safe to pass the argument register value unchanged as the
9685         // return register value (although it's at the target's option whether
9686         // to do so)
9687         // TODO: allow code generation to take advantage of partially preserved
9688         // registers rather than clobbering the entire register when the
9689         // parameter extension method is not compatible with the return
9690         // extension method
9691         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9692             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9693              CLI.RetZExt == Args[i].IsZExt))
9694           Flags.setReturned();
9695       }
9696 
9697       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9698                      CLI.CallConv, ExtendKind);
9699 
9700       for (unsigned j = 0; j != NumParts; ++j) {
9701         // if it isn't first piece, alignment must be 1
9702         // For scalable vectors the scalable part is currently handled
9703         // by individual targets, so we just use the known minimum size here.
9704         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9705                     i < CLI.NumFixedArgs, i,
9706                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9707         if (NumParts > 1 && j == 0)
9708           MyFlags.Flags.setSplit();
9709         else if (j != 0) {
9710           MyFlags.Flags.setOrigAlign(Align(1));
9711           if (j == NumParts - 1)
9712             MyFlags.Flags.setSplitEnd();
9713         }
9714 
9715         CLI.Outs.push_back(MyFlags);
9716         CLI.OutVals.push_back(Parts[j]);
9717       }
9718 
9719       if (NeedsRegBlock && Value == NumValues - 1)
9720         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9721     }
9722   }
9723 
9724   SmallVector<SDValue, 4> InVals;
9725   CLI.Chain = LowerCall(CLI, InVals);
9726 
9727   // Update CLI.InVals to use outside of this function.
9728   CLI.InVals = InVals;
9729 
9730   // Verify that the target's LowerCall behaved as expected.
9731   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9732          "LowerCall didn't return a valid chain!");
9733   assert((!CLI.IsTailCall || InVals.empty()) &&
9734          "LowerCall emitted a return value for a tail call!");
9735   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9736          "LowerCall didn't emit the correct number of values!");
9737 
9738   // For a tail call, the return value is merely live-out and there aren't
9739   // any nodes in the DAG representing it. Return a special value to
9740   // indicate that a tail call has been emitted and no more Instructions
9741   // should be processed in the current block.
9742   if (CLI.IsTailCall) {
9743     CLI.DAG.setRoot(CLI.Chain);
9744     return std::make_pair(SDValue(), SDValue());
9745   }
9746 
9747 #ifndef NDEBUG
9748   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9749     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9750     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9751            "LowerCall emitted a value with the wrong type!");
9752   }
9753 #endif
9754 
9755   SmallVector<SDValue, 4> ReturnValues;
9756   if (!CanLowerReturn) {
9757     // The instruction result is the result of loading from the
9758     // hidden sret parameter.
9759     SmallVector<EVT, 1> PVTs;
9760     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9761 
9762     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9763     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9764     EVT PtrVT = PVTs[0];
9765 
9766     unsigned NumValues = RetTys.size();
9767     ReturnValues.resize(NumValues);
9768     SmallVector<SDValue, 4> Chains(NumValues);
9769 
9770     // An aggregate return value cannot wrap around the address space, so
9771     // offsets to its parts don't wrap either.
9772     SDNodeFlags Flags;
9773     Flags.setNoUnsignedWrap(true);
9774 
9775     MachineFunction &MF = CLI.DAG.getMachineFunction();
9776     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9777     for (unsigned i = 0; i < NumValues; ++i) {
9778       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9779                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9780                                                         PtrVT), Flags);
9781       SDValue L = CLI.DAG.getLoad(
9782           RetTys[i], CLI.DL, CLI.Chain, Add,
9783           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9784                                             DemoteStackIdx, Offsets[i]),
9785           HiddenSRetAlign);
9786       ReturnValues[i] = L;
9787       Chains[i] = L.getValue(1);
9788     }
9789 
9790     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9791   } else {
9792     // Collect the legal value parts into potentially illegal values
9793     // that correspond to the original function's return values.
9794     Optional<ISD::NodeType> AssertOp;
9795     if (CLI.RetSExt)
9796       AssertOp = ISD::AssertSext;
9797     else if (CLI.RetZExt)
9798       AssertOp = ISD::AssertZext;
9799     unsigned CurReg = 0;
9800     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9801       EVT VT = RetTys[I];
9802       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9803                                                      CLI.CallConv, VT);
9804       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9805                                                        CLI.CallConv, VT);
9806 
9807       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9808                                               NumRegs, RegisterVT, VT, nullptr,
9809                                               CLI.CallConv, AssertOp));
9810       CurReg += NumRegs;
9811     }
9812 
9813     // For a function returning void, there is no return value. We can't create
9814     // such a node, so we just return a null return value in that case. In
9815     // that case, nothing will actually look at the value.
9816     if (ReturnValues.empty())
9817       return std::make_pair(SDValue(), CLI.Chain);
9818   }
9819 
9820   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9821                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9822   return std::make_pair(Res, CLI.Chain);
9823 }
9824 
9825 /// Places new result values for the node in Results (their number
9826 /// and types must exactly match those of the original return values of
9827 /// the node), or leaves Results empty, which indicates that the node is not
9828 /// to be custom lowered after all.
9829 void TargetLowering::LowerOperationWrapper(SDNode *N,
9830                                            SmallVectorImpl<SDValue> &Results,
9831                                            SelectionDAG &DAG) const {
9832   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9833 
9834   if (!Res.getNode())
9835     return;
9836 
9837   // If the original node has one result, take the return value from
9838   // LowerOperation as is. It might not be result number 0.
9839   if (N->getNumValues() == 1) {
9840     Results.push_back(Res);
9841     return;
9842   }
9843 
9844   // If the original node has multiple results, then the return node should
9845   // have the same number of results.
9846   assert((N->getNumValues() == Res->getNumValues()) &&
9847       "Lowering returned the wrong number of results!");
9848 
9849   // Places new result values base on N result number.
9850   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9851     Results.push_back(Res.getValue(I));
9852 }
9853 
9854 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9855   llvm_unreachable("LowerOperation not implemented for this target!");
9856 }
9857 
9858 void
9859 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9860   SDValue Op = getNonRegisterValue(V);
9861   assert((Op.getOpcode() != ISD::CopyFromReg ||
9862           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9863          "Copy from a reg to the same reg!");
9864   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9865 
9866   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9867   // If this is an InlineAsm we have to match the registers required, not the
9868   // notional registers required by the type.
9869 
9870   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9871                    None); // This is not an ABI copy.
9872   SDValue Chain = DAG.getEntryNode();
9873 
9874   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9875                               FuncInfo.PreferredExtendType.end())
9876                                  ? ISD::ANY_EXTEND
9877                                  : FuncInfo.PreferredExtendType[V];
9878   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9879   PendingExports.push_back(Chain);
9880 }
9881 
9882 #include "llvm/CodeGen/SelectionDAGISel.h"
9883 
9884 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9885 /// entry block, return true.  This includes arguments used by switches, since
9886 /// the switch may expand into multiple basic blocks.
9887 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9888   // With FastISel active, we may be splitting blocks, so force creation
9889   // of virtual registers for all non-dead arguments.
9890   if (FastISel)
9891     return A->use_empty();
9892 
9893   const BasicBlock &Entry = A->getParent()->front();
9894   for (const User *U : A->users())
9895     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9896       return false;  // Use not in entry block.
9897 
9898   return true;
9899 }
9900 
9901 using ArgCopyElisionMapTy =
9902     DenseMap<const Argument *,
9903              std::pair<const AllocaInst *, const StoreInst *>>;
9904 
9905 /// Scan the entry block of the function in FuncInfo for arguments that look
9906 /// like copies into a local alloca. Record any copied arguments in
9907 /// ArgCopyElisionCandidates.
9908 static void
9909 findArgumentCopyElisionCandidates(const DataLayout &DL,
9910                                   FunctionLoweringInfo *FuncInfo,
9911                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9912   // Record the state of every static alloca used in the entry block. Argument
9913   // allocas are all used in the entry block, so we need approximately as many
9914   // entries as we have arguments.
9915   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9916   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9917   unsigned NumArgs = FuncInfo->Fn->arg_size();
9918   StaticAllocas.reserve(NumArgs * 2);
9919 
9920   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9921     if (!V)
9922       return nullptr;
9923     V = V->stripPointerCasts();
9924     const auto *AI = dyn_cast<AllocaInst>(V);
9925     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9926       return nullptr;
9927     auto Iter = StaticAllocas.insert({AI, Unknown});
9928     return &Iter.first->second;
9929   };
9930 
9931   // Look for stores of arguments to static allocas. Look through bitcasts and
9932   // GEPs to handle type coercions, as long as the alloca is fully initialized
9933   // by the store. Any non-store use of an alloca escapes it and any subsequent
9934   // unanalyzed store might write it.
9935   // FIXME: Handle structs initialized with multiple stores.
9936   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9937     // Look for stores, and handle non-store uses conservatively.
9938     const auto *SI = dyn_cast<StoreInst>(&I);
9939     if (!SI) {
9940       // We will look through cast uses, so ignore them completely.
9941       if (I.isCast())
9942         continue;
9943       // Ignore debug info and pseudo op intrinsics, they don't escape or store
9944       // to allocas.
9945       if (I.isDebugOrPseudoInst())
9946         continue;
9947       // This is an unknown instruction. Assume it escapes or writes to all
9948       // static alloca operands.
9949       for (const Use &U : I.operands()) {
9950         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9951           *Info = StaticAllocaInfo::Clobbered;
9952       }
9953       continue;
9954     }
9955 
9956     // If the stored value is a static alloca, mark it as escaped.
9957     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9958       *Info = StaticAllocaInfo::Clobbered;
9959 
9960     // Check if the destination is a static alloca.
9961     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9962     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9963     if (!Info)
9964       continue;
9965     const AllocaInst *AI = cast<AllocaInst>(Dst);
9966 
9967     // Skip allocas that have been initialized or clobbered.
9968     if (*Info != StaticAllocaInfo::Unknown)
9969       continue;
9970 
9971     // Check if the stored value is an argument, and that this store fully
9972     // initializes the alloca.
9973     // If the argument type has padding bits we can't directly forward a pointer
9974     // as the upper bits may contain garbage.
9975     // Don't elide copies from the same argument twice.
9976     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9977     const auto *Arg = dyn_cast<Argument>(Val);
9978     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9979         Arg->getType()->isEmptyTy() ||
9980         DL.getTypeStoreSize(Arg->getType()) !=
9981             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9982         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
9983         ArgCopyElisionCandidates.count(Arg)) {
9984       *Info = StaticAllocaInfo::Clobbered;
9985       continue;
9986     }
9987 
9988     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9989                       << '\n');
9990 
9991     // Mark this alloca and store for argument copy elision.
9992     *Info = StaticAllocaInfo::Elidable;
9993     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9994 
9995     // Stop scanning if we've seen all arguments. This will happen early in -O0
9996     // builds, which is useful, because -O0 builds have large entry blocks and
9997     // many allocas.
9998     if (ArgCopyElisionCandidates.size() == NumArgs)
9999       break;
10000   }
10001 }
10002 
10003 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10004 /// ArgVal is a load from a suitable fixed stack object.
10005 static void tryToElideArgumentCopy(
10006     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10007     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10008     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10009     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10010     SDValue ArgVal, bool &ArgHasUses) {
10011   // Check if this is a load from a fixed stack object.
10012   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10013   if (!LNode)
10014     return;
10015   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10016   if (!FINode)
10017     return;
10018 
10019   // Check that the fixed stack object is the right size and alignment.
10020   // Look at the alignment that the user wrote on the alloca instead of looking
10021   // at the stack object.
10022   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10023   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10024   const AllocaInst *AI = ArgCopyIter->second.first;
10025   int FixedIndex = FINode->getIndex();
10026   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10027   int OldIndex = AllocaIndex;
10028   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10029   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10030     LLVM_DEBUG(
10031         dbgs() << "  argument copy elision failed due to bad fixed stack "
10032                   "object size\n");
10033     return;
10034   }
10035   Align RequiredAlignment = AI->getAlign();
10036   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10037     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10038                          "greater than stack argument alignment ("
10039                       << DebugStr(RequiredAlignment) << " vs "
10040                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10041     return;
10042   }
10043 
10044   // Perform the elision. Delete the old stack object and replace its only use
10045   // in the variable info map. Mark the stack object as mutable.
10046   LLVM_DEBUG({
10047     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10048            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10049            << '\n';
10050   });
10051   MFI.RemoveStackObject(OldIndex);
10052   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10053   AllocaIndex = FixedIndex;
10054   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10055   Chains.push_back(ArgVal.getValue(1));
10056 
10057   // Avoid emitting code for the store implementing the copy.
10058   const StoreInst *SI = ArgCopyIter->second.second;
10059   ElidedArgCopyInstrs.insert(SI);
10060 
10061   // Check for uses of the argument again so that we can avoid exporting ArgVal
10062   // if it is't used by anything other than the store.
10063   for (const Value *U : Arg.users()) {
10064     if (U != SI) {
10065       ArgHasUses = true;
10066       break;
10067     }
10068   }
10069 }
10070 
10071 void SelectionDAGISel::LowerArguments(const Function &F) {
10072   SelectionDAG &DAG = SDB->DAG;
10073   SDLoc dl = SDB->getCurSDLoc();
10074   const DataLayout &DL = DAG.getDataLayout();
10075   SmallVector<ISD::InputArg, 16> Ins;
10076 
10077   // In Naked functions we aren't going to save any registers.
10078   if (F.hasFnAttribute(Attribute::Naked))
10079     return;
10080 
10081   if (!FuncInfo->CanLowerReturn) {
10082     // Put in an sret pointer parameter before all the other parameters.
10083     SmallVector<EVT, 1> ValueVTs;
10084     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10085                     F.getReturnType()->getPointerTo(
10086                         DAG.getDataLayout().getAllocaAddrSpace()),
10087                     ValueVTs);
10088 
10089     // NOTE: Assuming that a pointer will never break down to more than one VT
10090     // or one register.
10091     ISD::ArgFlagsTy Flags;
10092     Flags.setSRet();
10093     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10094     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10095                          ISD::InputArg::NoArgIndex, 0);
10096     Ins.push_back(RetArg);
10097   }
10098 
10099   // Look for stores of arguments to static allocas. Mark such arguments with a
10100   // flag to ask the target to give us the memory location of that argument if
10101   // available.
10102   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10103   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10104                                     ArgCopyElisionCandidates);
10105 
10106   // Set up the incoming argument description vector.
10107   for (const Argument &Arg : F.args()) {
10108     unsigned ArgNo = Arg.getArgNo();
10109     SmallVector<EVT, 4> ValueVTs;
10110     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10111     bool isArgValueUsed = !Arg.use_empty();
10112     unsigned PartBase = 0;
10113     Type *FinalType = Arg.getType();
10114     if (Arg.hasAttribute(Attribute::ByVal))
10115       FinalType = Arg.getParamByValType();
10116     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10117         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10118     for (unsigned Value = 0, NumValues = ValueVTs.size();
10119          Value != NumValues; ++Value) {
10120       EVT VT = ValueVTs[Value];
10121       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10122       ISD::ArgFlagsTy Flags;
10123 
10124 
10125       if (Arg.getType()->isPointerTy()) {
10126         Flags.setPointer();
10127         Flags.setPointerAddrSpace(
10128             cast<PointerType>(Arg.getType())->getAddressSpace());
10129       }
10130       if (Arg.hasAttribute(Attribute::ZExt))
10131         Flags.setZExt();
10132       if (Arg.hasAttribute(Attribute::SExt))
10133         Flags.setSExt();
10134       if (Arg.hasAttribute(Attribute::InReg)) {
10135         // If we are using vectorcall calling convention, a structure that is
10136         // passed InReg - is surely an HVA
10137         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10138             isa<StructType>(Arg.getType())) {
10139           // The first value of a structure is marked
10140           if (0 == Value)
10141             Flags.setHvaStart();
10142           Flags.setHva();
10143         }
10144         // Set InReg Flag
10145         Flags.setInReg();
10146       }
10147       if (Arg.hasAttribute(Attribute::StructRet))
10148         Flags.setSRet();
10149       if (Arg.hasAttribute(Attribute::SwiftSelf))
10150         Flags.setSwiftSelf();
10151       if (Arg.hasAttribute(Attribute::SwiftAsync))
10152         Flags.setSwiftAsync();
10153       if (Arg.hasAttribute(Attribute::SwiftError))
10154         Flags.setSwiftError();
10155       if (Arg.hasAttribute(Attribute::ByVal))
10156         Flags.setByVal();
10157       if (Arg.hasAttribute(Attribute::ByRef))
10158         Flags.setByRef();
10159       if (Arg.hasAttribute(Attribute::InAlloca)) {
10160         Flags.setInAlloca();
10161         // Set the byval flag for CCAssignFn callbacks that don't know about
10162         // inalloca.  This way we can know how many bytes we should've allocated
10163         // and how many bytes a callee cleanup function will pop.  If we port
10164         // inalloca to more targets, we'll have to add custom inalloca handling
10165         // in the various CC lowering callbacks.
10166         Flags.setByVal();
10167       }
10168       if (Arg.hasAttribute(Attribute::Preallocated)) {
10169         Flags.setPreallocated();
10170         // Set the byval flag for CCAssignFn callbacks that don't know about
10171         // preallocated.  This way we can know how many bytes we should've
10172         // allocated and how many bytes a callee cleanup function will pop.  If
10173         // we port preallocated to more targets, we'll have to add custom
10174         // preallocated handling in the various CC lowering callbacks.
10175         Flags.setByVal();
10176       }
10177 
10178       // Certain targets (such as MIPS), may have a different ABI alignment
10179       // for a type depending on the context. Give the target a chance to
10180       // specify the alignment it wants.
10181       const Align OriginalAlignment(
10182           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10183       Flags.setOrigAlign(OriginalAlignment);
10184 
10185       Align MemAlign;
10186       Type *ArgMemTy = nullptr;
10187       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10188           Flags.isByRef()) {
10189         if (!ArgMemTy)
10190           ArgMemTy = Arg.getPointeeInMemoryValueType();
10191 
10192         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10193 
10194         // For in-memory arguments, size and alignment should be passed from FE.
10195         // BE will guess if this info is not there but there are cases it cannot
10196         // get right.
10197         if (auto ParamAlign = Arg.getParamStackAlign())
10198           MemAlign = *ParamAlign;
10199         else if ((ParamAlign = Arg.getParamAlign()))
10200           MemAlign = *ParamAlign;
10201         else
10202           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10203         if (Flags.isByRef())
10204           Flags.setByRefSize(MemSize);
10205         else
10206           Flags.setByValSize(MemSize);
10207       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10208         MemAlign = *ParamAlign;
10209       } else {
10210         MemAlign = OriginalAlignment;
10211       }
10212       Flags.setMemAlign(MemAlign);
10213 
10214       if (Arg.hasAttribute(Attribute::Nest))
10215         Flags.setNest();
10216       if (NeedsRegBlock)
10217         Flags.setInConsecutiveRegs();
10218       if (ArgCopyElisionCandidates.count(&Arg))
10219         Flags.setCopyElisionCandidate();
10220       if (Arg.hasAttribute(Attribute::Returned))
10221         Flags.setReturned();
10222 
10223       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10224           *CurDAG->getContext(), F.getCallingConv(), VT);
10225       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10226           *CurDAG->getContext(), F.getCallingConv(), VT);
10227       for (unsigned i = 0; i != NumRegs; ++i) {
10228         // For scalable vectors, use the minimum size; individual targets
10229         // are responsible for handling scalable vector arguments and
10230         // return values.
10231         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10232                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10233         if (NumRegs > 1 && i == 0)
10234           MyFlags.Flags.setSplit();
10235         // if it isn't first piece, alignment must be 1
10236         else if (i > 0) {
10237           MyFlags.Flags.setOrigAlign(Align(1));
10238           if (i == NumRegs - 1)
10239             MyFlags.Flags.setSplitEnd();
10240         }
10241         Ins.push_back(MyFlags);
10242       }
10243       if (NeedsRegBlock && Value == NumValues - 1)
10244         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10245       PartBase += VT.getStoreSize().getKnownMinSize();
10246     }
10247   }
10248 
10249   // Call the target to set up the argument values.
10250   SmallVector<SDValue, 8> InVals;
10251   SDValue NewRoot = TLI->LowerFormalArguments(
10252       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10253 
10254   // Verify that the target's LowerFormalArguments behaved as expected.
10255   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10256          "LowerFormalArguments didn't return a valid chain!");
10257   assert(InVals.size() == Ins.size() &&
10258          "LowerFormalArguments didn't emit the correct number of values!");
10259   LLVM_DEBUG({
10260     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10261       assert(InVals[i].getNode() &&
10262              "LowerFormalArguments emitted a null value!");
10263       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10264              "LowerFormalArguments emitted a value with the wrong type!");
10265     }
10266   });
10267 
10268   // Update the DAG with the new chain value resulting from argument lowering.
10269   DAG.setRoot(NewRoot);
10270 
10271   // Set up the argument values.
10272   unsigned i = 0;
10273   if (!FuncInfo->CanLowerReturn) {
10274     // Create a virtual register for the sret pointer, and put in a copy
10275     // from the sret argument into it.
10276     SmallVector<EVT, 1> ValueVTs;
10277     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10278                     F.getReturnType()->getPointerTo(
10279                         DAG.getDataLayout().getAllocaAddrSpace()),
10280                     ValueVTs);
10281     MVT VT = ValueVTs[0].getSimpleVT();
10282     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10283     Optional<ISD::NodeType> AssertOp = None;
10284     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10285                                         nullptr, F.getCallingConv(), AssertOp);
10286 
10287     MachineFunction& MF = SDB->DAG.getMachineFunction();
10288     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10289     Register SRetReg =
10290         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10291     FuncInfo->DemoteRegister = SRetReg;
10292     NewRoot =
10293         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10294     DAG.setRoot(NewRoot);
10295 
10296     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10297     ++i;
10298   }
10299 
10300   SmallVector<SDValue, 4> Chains;
10301   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10302   for (const Argument &Arg : F.args()) {
10303     SmallVector<SDValue, 4> ArgValues;
10304     SmallVector<EVT, 4> ValueVTs;
10305     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10306     unsigned NumValues = ValueVTs.size();
10307     if (NumValues == 0)
10308       continue;
10309 
10310     bool ArgHasUses = !Arg.use_empty();
10311 
10312     // Elide the copying store if the target loaded this argument from a
10313     // suitable fixed stack object.
10314     if (Ins[i].Flags.isCopyElisionCandidate()) {
10315       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10316                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10317                              InVals[i], ArgHasUses);
10318     }
10319 
10320     // If this argument is unused then remember its value. It is used to generate
10321     // debugging information.
10322     bool isSwiftErrorArg =
10323         TLI->supportSwiftError() &&
10324         Arg.hasAttribute(Attribute::SwiftError);
10325     if (!ArgHasUses && !isSwiftErrorArg) {
10326       SDB->setUnusedArgValue(&Arg, InVals[i]);
10327 
10328       // Also remember any frame index for use in FastISel.
10329       if (FrameIndexSDNode *FI =
10330           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10331         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10332     }
10333 
10334     for (unsigned Val = 0; Val != NumValues; ++Val) {
10335       EVT VT = ValueVTs[Val];
10336       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10337                                                       F.getCallingConv(), VT);
10338       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10339           *CurDAG->getContext(), F.getCallingConv(), VT);
10340 
10341       // Even an apparent 'unused' swifterror argument needs to be returned. So
10342       // we do generate a copy for it that can be used on return from the
10343       // function.
10344       if (ArgHasUses || isSwiftErrorArg) {
10345         Optional<ISD::NodeType> AssertOp;
10346         if (Arg.hasAttribute(Attribute::SExt))
10347           AssertOp = ISD::AssertSext;
10348         else if (Arg.hasAttribute(Attribute::ZExt))
10349           AssertOp = ISD::AssertZext;
10350 
10351         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10352                                              PartVT, VT, nullptr,
10353                                              F.getCallingConv(), AssertOp));
10354       }
10355 
10356       i += NumParts;
10357     }
10358 
10359     // We don't need to do anything else for unused arguments.
10360     if (ArgValues.empty())
10361       continue;
10362 
10363     // Note down frame index.
10364     if (FrameIndexSDNode *FI =
10365         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10366       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10367 
10368     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10369                                      SDB->getCurSDLoc());
10370 
10371     SDB->setValue(&Arg, Res);
10372     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10373       // We want to associate the argument with the frame index, among
10374       // involved operands, that correspond to the lowest address. The
10375       // getCopyFromParts function, called earlier, is swapping the order of
10376       // the operands to BUILD_PAIR depending on endianness. The result of
10377       // that swapping is that the least significant bits of the argument will
10378       // be in the first operand of the BUILD_PAIR node, and the most
10379       // significant bits will be in the second operand.
10380       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10381       if (LoadSDNode *LNode =
10382           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10383         if (FrameIndexSDNode *FI =
10384             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10385           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10386     }
10387 
10388     // Analyses past this point are naive and don't expect an assertion.
10389     if (Res.getOpcode() == ISD::AssertZext)
10390       Res = Res.getOperand(0);
10391 
10392     // Update the SwiftErrorVRegDefMap.
10393     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10394       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10395       if (Register::isVirtualRegister(Reg))
10396         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10397                                    Reg);
10398     }
10399 
10400     // If this argument is live outside of the entry block, insert a copy from
10401     // wherever we got it to the vreg that other BB's will reference it as.
10402     if (Res.getOpcode() == ISD::CopyFromReg) {
10403       // If we can, though, try to skip creating an unnecessary vreg.
10404       // FIXME: This isn't very clean... it would be nice to make this more
10405       // general.
10406       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10407       if (Register::isVirtualRegister(Reg)) {
10408         FuncInfo->ValueMap[&Arg] = Reg;
10409         continue;
10410       }
10411     }
10412     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10413       FuncInfo->InitializeRegForValue(&Arg);
10414       SDB->CopyToExportRegsIfNeeded(&Arg);
10415     }
10416   }
10417 
10418   if (!Chains.empty()) {
10419     Chains.push_back(NewRoot);
10420     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10421   }
10422 
10423   DAG.setRoot(NewRoot);
10424 
10425   assert(i == InVals.size() && "Argument register count mismatch!");
10426 
10427   // If any argument copy elisions occurred and we have debug info, update the
10428   // stale frame indices used in the dbg.declare variable info table.
10429   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10430   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10431     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10432       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10433       if (I != ArgCopyElisionFrameIndexMap.end())
10434         VI.Slot = I->second;
10435     }
10436   }
10437 
10438   // Finally, if the target has anything special to do, allow it to do so.
10439   emitFunctionEntryCode();
10440 }
10441 
10442 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10443 /// ensure constants are generated when needed.  Remember the virtual registers
10444 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10445 /// directly add them, because expansion might result in multiple MBB's for one
10446 /// BB.  As such, the start of the BB might correspond to a different MBB than
10447 /// the end.
10448 void
10449 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10450   const Instruction *TI = LLVMBB->getTerminator();
10451 
10452   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10453 
10454   // Check PHI nodes in successors that expect a value to be available from this
10455   // block.
10456   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10457     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10458     if (!isa<PHINode>(SuccBB->begin())) continue;
10459     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10460 
10461     // If this terminator has multiple identical successors (common for
10462     // switches), only handle each succ once.
10463     if (!SuccsHandled.insert(SuccMBB).second)
10464       continue;
10465 
10466     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10467 
10468     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10469     // nodes and Machine PHI nodes, but the incoming operands have not been
10470     // emitted yet.
10471     for (const PHINode &PN : SuccBB->phis()) {
10472       // Ignore dead phi's.
10473       if (PN.use_empty())
10474         continue;
10475 
10476       // Skip empty types
10477       if (PN.getType()->isEmptyTy())
10478         continue;
10479 
10480       unsigned Reg;
10481       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10482 
10483       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10484         unsigned &RegOut = ConstantsOut[C];
10485         if (RegOut == 0) {
10486           RegOut = FuncInfo.CreateRegs(C);
10487           CopyValueToVirtualRegister(C, RegOut);
10488         }
10489         Reg = RegOut;
10490       } else {
10491         DenseMap<const Value *, Register>::iterator I =
10492           FuncInfo.ValueMap.find(PHIOp);
10493         if (I != FuncInfo.ValueMap.end())
10494           Reg = I->second;
10495         else {
10496           assert(isa<AllocaInst>(PHIOp) &&
10497                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10498                  "Didn't codegen value into a register!??");
10499           Reg = FuncInfo.CreateRegs(PHIOp);
10500           CopyValueToVirtualRegister(PHIOp, Reg);
10501         }
10502       }
10503 
10504       // Remember that this register needs to added to the machine PHI node as
10505       // the input for this MBB.
10506       SmallVector<EVT, 4> ValueVTs;
10507       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10508       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10509       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10510         EVT VT = ValueVTs[vti];
10511         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10512         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10513           FuncInfo.PHINodesToUpdate.push_back(
10514               std::make_pair(&*MBBI++, Reg + i));
10515         Reg += NumRegisters;
10516       }
10517     }
10518   }
10519 
10520   ConstantsOut.clear();
10521 }
10522 
10523 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10524 /// is 0.
10525 MachineBasicBlock *
10526 SelectionDAGBuilder::StackProtectorDescriptor::
10527 AddSuccessorMBB(const BasicBlock *BB,
10528                 MachineBasicBlock *ParentMBB,
10529                 bool IsLikely,
10530                 MachineBasicBlock *SuccMBB) {
10531   // If SuccBB has not been created yet, create it.
10532   if (!SuccMBB) {
10533     MachineFunction *MF = ParentMBB->getParent();
10534     MachineFunction::iterator BBI(ParentMBB);
10535     SuccMBB = MF->CreateMachineBasicBlock(BB);
10536     MF->insert(++BBI, SuccMBB);
10537   }
10538   // Add it as a successor of ParentMBB.
10539   ParentMBB->addSuccessor(
10540       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10541   return SuccMBB;
10542 }
10543 
10544 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10545   MachineFunction::iterator I(MBB);
10546   if (++I == FuncInfo.MF->end())
10547     return nullptr;
10548   return &*I;
10549 }
10550 
10551 /// During lowering new call nodes can be created (such as memset, etc.).
10552 /// Those will become new roots of the current DAG, but complications arise
10553 /// when they are tail calls. In such cases, the call lowering will update
10554 /// the root, but the builder still needs to know that a tail call has been
10555 /// lowered in order to avoid generating an additional return.
10556 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10557   // If the node is null, we do have a tail call.
10558   if (MaybeTC.getNode() != nullptr)
10559     DAG.setRoot(MaybeTC);
10560   else
10561     HasTailCall = true;
10562 }
10563 
10564 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10565                                         MachineBasicBlock *SwitchMBB,
10566                                         MachineBasicBlock *DefaultMBB) {
10567   MachineFunction *CurMF = FuncInfo.MF;
10568   MachineBasicBlock *NextMBB = nullptr;
10569   MachineFunction::iterator BBI(W.MBB);
10570   if (++BBI != FuncInfo.MF->end())
10571     NextMBB = &*BBI;
10572 
10573   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10574 
10575   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10576 
10577   if (Size == 2 && W.MBB == SwitchMBB) {
10578     // If any two of the cases has the same destination, and if one value
10579     // is the same as the other, but has one bit unset that the other has set,
10580     // use bit manipulation to do two compares at once.  For example:
10581     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10582     // TODO: This could be extended to merge any 2 cases in switches with 3
10583     // cases.
10584     // TODO: Handle cases where W.CaseBB != SwitchBB.
10585     CaseCluster &Small = *W.FirstCluster;
10586     CaseCluster &Big = *W.LastCluster;
10587 
10588     if (Small.Low == Small.High && Big.Low == Big.High &&
10589         Small.MBB == Big.MBB) {
10590       const APInt &SmallValue = Small.Low->getValue();
10591       const APInt &BigValue = Big.Low->getValue();
10592 
10593       // Check that there is only one bit different.
10594       APInt CommonBit = BigValue ^ SmallValue;
10595       if (CommonBit.isPowerOf2()) {
10596         SDValue CondLHS = getValue(Cond);
10597         EVT VT = CondLHS.getValueType();
10598         SDLoc DL = getCurSDLoc();
10599 
10600         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10601                                  DAG.getConstant(CommonBit, DL, VT));
10602         SDValue Cond = DAG.getSetCC(
10603             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10604             ISD::SETEQ);
10605 
10606         // Update successor info.
10607         // Both Small and Big will jump to Small.BB, so we sum up the
10608         // probabilities.
10609         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10610         if (BPI)
10611           addSuccessorWithProb(
10612               SwitchMBB, DefaultMBB,
10613               // The default destination is the first successor in IR.
10614               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10615         else
10616           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10617 
10618         // Insert the true branch.
10619         SDValue BrCond =
10620             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10621                         DAG.getBasicBlock(Small.MBB));
10622         // Insert the false branch.
10623         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10624                              DAG.getBasicBlock(DefaultMBB));
10625 
10626         DAG.setRoot(BrCond);
10627         return;
10628       }
10629     }
10630   }
10631 
10632   if (TM.getOptLevel() != CodeGenOpt::None) {
10633     // Here, we order cases by probability so the most likely case will be
10634     // checked first. However, two clusters can have the same probability in
10635     // which case their relative ordering is non-deterministic. So we use Low
10636     // as a tie-breaker as clusters are guaranteed to never overlap.
10637     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10638                [](const CaseCluster &a, const CaseCluster &b) {
10639       return a.Prob != b.Prob ?
10640              a.Prob > b.Prob :
10641              a.Low->getValue().slt(b.Low->getValue());
10642     });
10643 
10644     // Rearrange the case blocks so that the last one falls through if possible
10645     // without changing the order of probabilities.
10646     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10647       --I;
10648       if (I->Prob > W.LastCluster->Prob)
10649         break;
10650       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10651         std::swap(*I, *W.LastCluster);
10652         break;
10653       }
10654     }
10655   }
10656 
10657   // Compute total probability.
10658   BranchProbability DefaultProb = W.DefaultProb;
10659   BranchProbability UnhandledProbs = DefaultProb;
10660   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10661     UnhandledProbs += I->Prob;
10662 
10663   MachineBasicBlock *CurMBB = W.MBB;
10664   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10665     bool FallthroughUnreachable = false;
10666     MachineBasicBlock *Fallthrough;
10667     if (I == W.LastCluster) {
10668       // For the last cluster, fall through to the default destination.
10669       Fallthrough = DefaultMBB;
10670       FallthroughUnreachable = isa<UnreachableInst>(
10671           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10672     } else {
10673       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10674       CurMF->insert(BBI, Fallthrough);
10675       // Put Cond in a virtual register to make it available from the new blocks.
10676       ExportFromCurrentBlock(Cond);
10677     }
10678     UnhandledProbs -= I->Prob;
10679 
10680     switch (I->Kind) {
10681       case CC_JumpTable: {
10682         // FIXME: Optimize away range check based on pivot comparisons.
10683         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10684         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10685 
10686         // The jump block hasn't been inserted yet; insert it here.
10687         MachineBasicBlock *JumpMBB = JT->MBB;
10688         CurMF->insert(BBI, JumpMBB);
10689 
10690         auto JumpProb = I->Prob;
10691         auto FallthroughProb = UnhandledProbs;
10692 
10693         // If the default statement is a target of the jump table, we evenly
10694         // distribute the default probability to successors of CurMBB. Also
10695         // update the probability on the edge from JumpMBB to Fallthrough.
10696         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10697                                               SE = JumpMBB->succ_end();
10698              SI != SE; ++SI) {
10699           if (*SI == DefaultMBB) {
10700             JumpProb += DefaultProb / 2;
10701             FallthroughProb -= DefaultProb / 2;
10702             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10703             JumpMBB->normalizeSuccProbs();
10704             break;
10705           }
10706         }
10707 
10708         if (FallthroughUnreachable) {
10709           // Skip the range check if the fallthrough block is unreachable.
10710           JTH->OmitRangeCheck = true;
10711         }
10712 
10713         if (!JTH->OmitRangeCheck)
10714           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10715         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10716         CurMBB->normalizeSuccProbs();
10717 
10718         // The jump table header will be inserted in our current block, do the
10719         // range check, and fall through to our fallthrough block.
10720         JTH->HeaderBB = CurMBB;
10721         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10722 
10723         // If we're in the right place, emit the jump table header right now.
10724         if (CurMBB == SwitchMBB) {
10725           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10726           JTH->Emitted = true;
10727         }
10728         break;
10729       }
10730       case CC_BitTests: {
10731         // FIXME: Optimize away range check based on pivot comparisons.
10732         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10733 
10734         // The bit test blocks haven't been inserted yet; insert them here.
10735         for (BitTestCase &BTC : BTB->Cases)
10736           CurMF->insert(BBI, BTC.ThisBB);
10737 
10738         // Fill in fields of the BitTestBlock.
10739         BTB->Parent = CurMBB;
10740         BTB->Default = Fallthrough;
10741 
10742         BTB->DefaultProb = UnhandledProbs;
10743         // If the cases in bit test don't form a contiguous range, we evenly
10744         // distribute the probability on the edge to Fallthrough to two
10745         // successors of CurMBB.
10746         if (!BTB->ContiguousRange) {
10747           BTB->Prob += DefaultProb / 2;
10748           BTB->DefaultProb -= DefaultProb / 2;
10749         }
10750 
10751         if (FallthroughUnreachable) {
10752           // Skip the range check if the fallthrough block is unreachable.
10753           BTB->OmitRangeCheck = true;
10754         }
10755 
10756         // If we're in the right place, emit the bit test header right now.
10757         if (CurMBB == SwitchMBB) {
10758           visitBitTestHeader(*BTB, SwitchMBB);
10759           BTB->Emitted = true;
10760         }
10761         break;
10762       }
10763       case CC_Range: {
10764         const Value *RHS, *LHS, *MHS;
10765         ISD::CondCode CC;
10766         if (I->Low == I->High) {
10767           // Check Cond == I->Low.
10768           CC = ISD::SETEQ;
10769           LHS = Cond;
10770           RHS=I->Low;
10771           MHS = nullptr;
10772         } else {
10773           // Check I->Low <= Cond <= I->High.
10774           CC = ISD::SETLE;
10775           LHS = I->Low;
10776           MHS = Cond;
10777           RHS = I->High;
10778         }
10779 
10780         // If Fallthrough is unreachable, fold away the comparison.
10781         if (FallthroughUnreachable)
10782           CC = ISD::SETTRUE;
10783 
10784         // The false probability is the sum of all unhandled cases.
10785         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10786                      getCurSDLoc(), I->Prob, UnhandledProbs);
10787 
10788         if (CurMBB == SwitchMBB)
10789           visitSwitchCase(CB, SwitchMBB);
10790         else
10791           SL->SwitchCases.push_back(CB);
10792 
10793         break;
10794       }
10795     }
10796     CurMBB = Fallthrough;
10797   }
10798 }
10799 
10800 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10801                                               CaseClusterIt First,
10802                                               CaseClusterIt Last) {
10803   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10804     if (X.Prob != CC.Prob)
10805       return X.Prob > CC.Prob;
10806 
10807     // Ties are broken by comparing the case value.
10808     return X.Low->getValue().slt(CC.Low->getValue());
10809   });
10810 }
10811 
10812 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10813                                         const SwitchWorkListItem &W,
10814                                         Value *Cond,
10815                                         MachineBasicBlock *SwitchMBB) {
10816   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10817          "Clusters not sorted?");
10818 
10819   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10820 
10821   // Balance the tree based on branch probabilities to create a near-optimal (in
10822   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10823   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10824   CaseClusterIt LastLeft = W.FirstCluster;
10825   CaseClusterIt FirstRight = W.LastCluster;
10826   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10827   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10828 
10829   // Move LastLeft and FirstRight towards each other from opposite directions to
10830   // find a partitioning of the clusters which balances the probability on both
10831   // sides. If LeftProb and RightProb are equal, alternate which side is
10832   // taken to ensure 0-probability nodes are distributed evenly.
10833   unsigned I = 0;
10834   while (LastLeft + 1 < FirstRight) {
10835     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10836       LeftProb += (++LastLeft)->Prob;
10837     else
10838       RightProb += (--FirstRight)->Prob;
10839     I++;
10840   }
10841 
10842   while (true) {
10843     // Our binary search tree differs from a typical BST in that ours can have up
10844     // to three values in each leaf. The pivot selection above doesn't take that
10845     // into account, which means the tree might require more nodes and be less
10846     // efficient. We compensate for this here.
10847 
10848     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10849     unsigned NumRight = W.LastCluster - FirstRight + 1;
10850 
10851     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10852       // If one side has less than 3 clusters, and the other has more than 3,
10853       // consider taking a cluster from the other side.
10854 
10855       if (NumLeft < NumRight) {
10856         // Consider moving the first cluster on the right to the left side.
10857         CaseCluster &CC = *FirstRight;
10858         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10859         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10860         if (LeftSideRank <= RightSideRank) {
10861           // Moving the cluster to the left does not demote it.
10862           ++LastLeft;
10863           ++FirstRight;
10864           continue;
10865         }
10866       } else {
10867         assert(NumRight < NumLeft);
10868         // Consider moving the last element on the left to the right side.
10869         CaseCluster &CC = *LastLeft;
10870         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10871         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10872         if (RightSideRank <= LeftSideRank) {
10873           // Moving the cluster to the right does not demot it.
10874           --LastLeft;
10875           --FirstRight;
10876           continue;
10877         }
10878       }
10879     }
10880     break;
10881   }
10882 
10883   assert(LastLeft + 1 == FirstRight);
10884   assert(LastLeft >= W.FirstCluster);
10885   assert(FirstRight <= W.LastCluster);
10886 
10887   // Use the first element on the right as pivot since we will make less-than
10888   // comparisons against it.
10889   CaseClusterIt PivotCluster = FirstRight;
10890   assert(PivotCluster > W.FirstCluster);
10891   assert(PivotCluster <= W.LastCluster);
10892 
10893   CaseClusterIt FirstLeft = W.FirstCluster;
10894   CaseClusterIt LastRight = W.LastCluster;
10895 
10896   const ConstantInt *Pivot = PivotCluster->Low;
10897 
10898   // New blocks will be inserted immediately after the current one.
10899   MachineFunction::iterator BBI(W.MBB);
10900   ++BBI;
10901 
10902   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10903   // we can branch to its destination directly if it's squeezed exactly in
10904   // between the known lower bound and Pivot - 1.
10905   MachineBasicBlock *LeftMBB;
10906   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10907       FirstLeft->Low == W.GE &&
10908       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10909     LeftMBB = FirstLeft->MBB;
10910   } else {
10911     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10912     FuncInfo.MF->insert(BBI, LeftMBB);
10913     WorkList.push_back(
10914         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10915     // Put Cond in a virtual register to make it available from the new blocks.
10916     ExportFromCurrentBlock(Cond);
10917   }
10918 
10919   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10920   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10921   // directly if RHS.High equals the current upper bound.
10922   MachineBasicBlock *RightMBB;
10923   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10924       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10925     RightMBB = FirstRight->MBB;
10926   } else {
10927     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10928     FuncInfo.MF->insert(BBI, RightMBB);
10929     WorkList.push_back(
10930         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10931     // Put Cond in a virtual register to make it available from the new blocks.
10932     ExportFromCurrentBlock(Cond);
10933   }
10934 
10935   // Create the CaseBlock record that will be used to lower the branch.
10936   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10937                getCurSDLoc(), LeftProb, RightProb);
10938 
10939   if (W.MBB == SwitchMBB)
10940     visitSwitchCase(CB, SwitchMBB);
10941   else
10942     SL->SwitchCases.push_back(CB);
10943 }
10944 
10945 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10946 // from the swith statement.
10947 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10948                                             BranchProbability PeeledCaseProb) {
10949   if (PeeledCaseProb == BranchProbability::getOne())
10950     return BranchProbability::getZero();
10951   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10952 
10953   uint32_t Numerator = CaseProb.getNumerator();
10954   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10955   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10956 }
10957 
10958 // Try to peel the top probability case if it exceeds the threshold.
10959 // Return current MachineBasicBlock for the switch statement if the peeling
10960 // does not occur.
10961 // If the peeling is performed, return the newly created MachineBasicBlock
10962 // for the peeled switch statement. Also update Clusters to remove the peeled
10963 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10964 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10965     const SwitchInst &SI, CaseClusterVector &Clusters,
10966     BranchProbability &PeeledCaseProb) {
10967   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10968   // Don't perform if there is only one cluster or optimizing for size.
10969   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10970       TM.getOptLevel() == CodeGenOpt::None ||
10971       SwitchMBB->getParent()->getFunction().hasMinSize())
10972     return SwitchMBB;
10973 
10974   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10975   unsigned PeeledCaseIndex = 0;
10976   bool SwitchPeeled = false;
10977   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10978     CaseCluster &CC = Clusters[Index];
10979     if (CC.Prob < TopCaseProb)
10980       continue;
10981     TopCaseProb = CC.Prob;
10982     PeeledCaseIndex = Index;
10983     SwitchPeeled = true;
10984   }
10985   if (!SwitchPeeled)
10986     return SwitchMBB;
10987 
10988   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10989                     << TopCaseProb << "\n");
10990 
10991   // Record the MBB for the peeled switch statement.
10992   MachineFunction::iterator BBI(SwitchMBB);
10993   ++BBI;
10994   MachineBasicBlock *PeeledSwitchMBB =
10995       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10996   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10997 
10998   ExportFromCurrentBlock(SI.getCondition());
10999   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11000   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11001                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11002   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11003 
11004   Clusters.erase(PeeledCaseIt);
11005   for (CaseCluster &CC : Clusters) {
11006     LLVM_DEBUG(
11007         dbgs() << "Scale the probablity for one cluster, before scaling: "
11008                << CC.Prob << "\n");
11009     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11010     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11011   }
11012   PeeledCaseProb = TopCaseProb;
11013   return PeeledSwitchMBB;
11014 }
11015 
11016 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11017   // Extract cases from the switch.
11018   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11019   CaseClusterVector Clusters;
11020   Clusters.reserve(SI.getNumCases());
11021   for (auto I : SI.cases()) {
11022     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11023     const ConstantInt *CaseVal = I.getCaseValue();
11024     BranchProbability Prob =
11025         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11026             : BranchProbability(1, SI.getNumCases() + 1);
11027     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11028   }
11029 
11030   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11031 
11032   // Cluster adjacent cases with the same destination. We do this at all
11033   // optimization levels because it's cheap to do and will make codegen faster
11034   // if there are many clusters.
11035   sortAndRangeify(Clusters);
11036 
11037   // The branch probablity of the peeled case.
11038   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11039   MachineBasicBlock *PeeledSwitchMBB =
11040       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11041 
11042   // If there is only the default destination, jump there directly.
11043   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11044   if (Clusters.empty()) {
11045     assert(PeeledSwitchMBB == SwitchMBB);
11046     SwitchMBB->addSuccessor(DefaultMBB);
11047     if (DefaultMBB != NextBlock(SwitchMBB)) {
11048       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11049                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11050     }
11051     return;
11052   }
11053 
11054   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11055   SL->findBitTestClusters(Clusters, &SI);
11056 
11057   LLVM_DEBUG({
11058     dbgs() << "Case clusters: ";
11059     for (const CaseCluster &C : Clusters) {
11060       if (C.Kind == CC_JumpTable)
11061         dbgs() << "JT:";
11062       if (C.Kind == CC_BitTests)
11063         dbgs() << "BT:";
11064 
11065       C.Low->getValue().print(dbgs(), true);
11066       if (C.Low != C.High) {
11067         dbgs() << '-';
11068         C.High->getValue().print(dbgs(), true);
11069       }
11070       dbgs() << ' ';
11071     }
11072     dbgs() << '\n';
11073   });
11074 
11075   assert(!Clusters.empty());
11076   SwitchWorkList WorkList;
11077   CaseClusterIt First = Clusters.begin();
11078   CaseClusterIt Last = Clusters.end() - 1;
11079   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11080   // Scale the branchprobability for DefaultMBB if the peel occurs and
11081   // DefaultMBB is not replaced.
11082   if (PeeledCaseProb != BranchProbability::getZero() &&
11083       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11084     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11085   WorkList.push_back(
11086       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11087 
11088   while (!WorkList.empty()) {
11089     SwitchWorkListItem W = WorkList.pop_back_val();
11090     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11091 
11092     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11093         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11094       // For optimized builds, lower large range as a balanced binary tree.
11095       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11096       continue;
11097     }
11098 
11099     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11100   }
11101 }
11102 
11103 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11104   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11105   auto DL = getCurSDLoc();
11106   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11107   setValue(&I, DAG.getStepVector(DL, ResultVT));
11108 }
11109 
11110 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11111   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11112   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11113 
11114   SDLoc DL = getCurSDLoc();
11115   SDValue V = getValue(I.getOperand(0));
11116   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11117 
11118   if (VT.isScalableVector()) {
11119     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11120     return;
11121   }
11122 
11123   // Use VECTOR_SHUFFLE for the fixed-length vector
11124   // to maintain existing behavior.
11125   SmallVector<int, 8> Mask;
11126   unsigned NumElts = VT.getVectorMinNumElements();
11127   for (unsigned i = 0; i != NumElts; ++i)
11128     Mask.push_back(NumElts - 1 - i);
11129 
11130   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11131 }
11132 
11133 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11134   SmallVector<EVT, 4> ValueVTs;
11135   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11136                   ValueVTs);
11137   unsigned NumValues = ValueVTs.size();
11138   if (NumValues == 0) return;
11139 
11140   SmallVector<SDValue, 4> Values(NumValues);
11141   SDValue Op = getValue(I.getOperand(0));
11142 
11143   for (unsigned i = 0; i != NumValues; ++i)
11144     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11145                             SDValue(Op.getNode(), Op.getResNo() + i));
11146 
11147   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11148                            DAG.getVTList(ValueVTs), Values));
11149 }
11150 
11151 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11152   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11153   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11154 
11155   SDLoc DL = getCurSDLoc();
11156   SDValue V1 = getValue(I.getOperand(0));
11157   SDValue V2 = getValue(I.getOperand(1));
11158   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11159 
11160   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11161   if (VT.isScalableVector()) {
11162     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11163     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11164                              DAG.getConstant(Imm, DL, IdxVT)));
11165     return;
11166   }
11167 
11168   unsigned NumElts = VT.getVectorNumElements();
11169 
11170   if ((-Imm > NumElts) || (Imm >= NumElts)) {
11171     // Result is undefined if immediate is out-of-bounds.
11172     setValue(&I, DAG.getUNDEF(VT));
11173     return;
11174   }
11175 
11176   uint64_t Idx = (NumElts + Imm) % NumElts;
11177 
11178   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11179   SmallVector<int, 8> Mask;
11180   for (unsigned i = 0; i < NumElts; ++i)
11181     Mask.push_back(Idx + i);
11182   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11183 }
11184