xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 0312fe2901122b6c7de8c301e069795abb88a778)
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/DiagnosticInfo.h"
73 #include "llvm/IR/Function.h"
74 #include "llvm/IR/GetElementPtrTypeIterator.h"
75 #include "llvm/IR/InlineAsm.h"
76 #include "llvm/IR/InstrTypes.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/Intrinsics.h"
80 #include "llvm/IR/IntrinsicsAArch64.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Module.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Statepoint.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/MC/MCContext.h"
92 #include "llvm/MC/MCSymbol.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/MathExtras.h"
99 #include "llvm/Support/raw_ostream.h"
100 #include "llvm/Target/TargetIntrinsicInfo.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetOptions.h"
103 #include "llvm/Transforms/Utils/Local.h"
104 #include <cstddef>
105 #include <cstring>
106 #include <iterator>
107 #include <limits>
108 #include <numeric>
109 #include <tuple>
110 
111 using namespace llvm;
112 using namespace PatternMatch;
113 using namespace SwitchCG;
114 
115 #define DEBUG_TYPE "isel"
116 
117 /// LimitFloatPrecision - Generate low-precision inline sequences for
118 /// some float libcalls (6, 8 or 12 bits).
119 static unsigned LimitFloatPrecision;
120 
121 static cl::opt<bool>
122     InsertAssertAlign("insert-assert-align", cl::init(true),
123                       cl::desc("Insert the experimental `assertalign` node."),
124                       cl::ReallyHidden);
125 
126 static cl::opt<unsigned, true>
127     LimitFPPrecision("limit-float-precision",
128                      cl::desc("Generate low-precision inline sequences "
129                               "for some float libcalls"),
130                      cl::location(LimitFloatPrecision), cl::Hidden,
131                      cl::init(0));
132 
133 static cl::opt<unsigned> SwitchPeelThreshold(
134     "switch-peel-threshold", cl::Hidden, cl::init(66),
135     cl::desc("Set the case probability threshold for peeling the case from a "
136              "switch statement. A value greater than 100 will void this "
137              "optimization"));
138 
139 // Limit the width of DAG chains. This is important in general to prevent
140 // DAG-based analysis from blowing up. For example, alias analysis and
141 // load clustering may not complete in reasonable time. It is difficult to
142 // recognize and avoid this situation within each individual analysis, and
143 // future analyses are likely to have the same behavior. Limiting DAG width is
144 // the safe approach and will be especially important with global DAGs.
145 //
146 // MaxParallelChains default is arbitrarily high to avoid affecting
147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
148 // sequence over this should have been converted to llvm.memcpy by the
149 // frontend. It is easy to induce this behavior with .ll code such as:
150 // %buffer = alloca [4096 x i8]
151 // %data = load [4096 x i8]* %argPtr
152 // store [4096 x i8] %data, [4096 x i8]* %buffer
153 static const unsigned MaxParallelChains = 64;
154 
155 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
156                                       const SDValue *Parts, unsigned NumParts,
157                                       MVT PartVT, EVT ValueVT, const Value *V,
158                                       Optional<CallingConv::ID> CC);
159 
160 /// getCopyFromParts - Create a value that contains the specified legal parts
161 /// combined into the value they represent.  If the parts combine to a type
162 /// larger than ValueVT then AssertOp can be used to specify whether the extra
163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164 /// (ISD::AssertSext).
165 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
166                                 const SDValue *Parts, unsigned NumParts,
167                                 MVT PartVT, EVT ValueVT, const Value *V,
168                                 Optional<CallingConv::ID> CC = None,
169                                 Optional<ISD::NodeType> AssertOp = None) {
170   // Let the target assemble the parts if it wants to
171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
172   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
173                                                    PartVT, ValueVT, CC))
174     return Val;
175 
176   if (ValueVT.isVector())
177     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
178                                   CC);
179 
180   assert(NumParts > 0 && "No parts to assemble!");
181   SDValue Val = Parts[0];
182 
183   if (NumParts > 1) {
184     // Assemble the value from multiple parts.
185     if (ValueVT.isInteger()) {
186       unsigned PartBits = PartVT.getSizeInBits();
187       unsigned ValueBits = ValueVT.getSizeInBits();
188 
189       // Assemble the power of 2 part.
190       unsigned RoundParts =
191           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
192       unsigned RoundBits = PartBits * RoundParts;
193       EVT RoundVT = RoundBits == ValueBits ?
194         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195       SDValue Lo, Hi;
196 
197       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
198 
199       if (RoundParts > 2) {
200         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
201                               PartVT, HalfVT, V);
202         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
203                               RoundParts / 2, PartVT, HalfVT, V);
204       } else {
205         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
206         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
207       }
208 
209       if (DAG.getDataLayout().isBigEndian())
210         std::swap(Lo, Hi);
211 
212       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
213 
214       if (RoundParts < NumParts) {
215         // Assemble the trailing non-power-of-2 part.
216         unsigned OddParts = NumParts - RoundParts;
217         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
218         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
219                               OddVT, V, CC);
220 
221         // Combine the round and odd parts.
222         Lo = Val;
223         if (DAG.getDataLayout().isBigEndian())
224           std::swap(Lo, Hi);
225         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
226         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
227         Hi =
228             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
229                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
230                                         TLI.getPointerTy(DAG.getDataLayout())));
231         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
232         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
233       }
234     } else if (PartVT.isFloatingPoint()) {
235       // FP split into multiple FP parts (for ppcf128)
236       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
237              "Unexpected split");
238       SDValue Lo, Hi;
239       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
240       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
241       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
242         std::swap(Lo, Hi);
243       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
244     } else {
245       // FP split into integer parts (soft fp)
246       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
247              !PartVT.isVector() && "Unexpected split");
248       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
249       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
250     }
251   }
252 
253   // There is now one part, held in Val.  Correct it to match ValueVT.
254   // PartEVT is the type of the register class that holds the value.
255   // ValueVT is the type of the inline asm operation.
256   EVT PartEVT = Val.getValueType();
257 
258   if (PartEVT == ValueVT)
259     return Val;
260 
261   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262       ValueVT.bitsLT(PartEVT)) {
263     // For an FP value in an integer part, we need to truncate to the right
264     // width first.
265     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
266     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
267   }
268 
269   // Handle types that have the same size.
270   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
272 
273   // Handle types with different sizes.
274   if (PartEVT.isInteger() && ValueVT.isInteger()) {
275     if (ValueVT.bitsLT(PartEVT)) {
276       // For a truncate, see if we have any information to
277       // indicate whether the truncated bits will always be
278       // zero or sign-extension.
279       if (AssertOp.hasValue())
280         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
281                           DAG.getValueType(ValueVT));
282       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
283     }
284     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
285   }
286 
287   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288     // FP_ROUND's are always exact here.
289     if (ValueVT.bitsLT(Val.getValueType()))
290       return DAG.getNode(
291           ISD::FP_ROUND, DL, ValueVT, Val,
292           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
293 
294     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
295   }
296 
297   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
298   // then truncating.
299   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
300       ValueVT.bitsLT(PartEVT)) {
301     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
302     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
303   }
304 
305   report_fatal_error("Unknown mismatch in getCopyFromParts!");
306 }
307 
308 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
309                                               const Twine &ErrMsg) {
310   const Instruction *I = dyn_cast_or_null<Instruction>(V);
311   if (!V)
312     return Ctx.emitError(ErrMsg);
313 
314   const char *AsmError = ", possible invalid constraint for vector type";
315   if (const CallInst *CI = dyn_cast<CallInst>(I))
316     if (CI->isInlineAsm())
317       return Ctx.emitError(I, ErrMsg + AsmError);
318 
319   return Ctx.emitError(I, ErrMsg);
320 }
321 
322 /// getCopyFromPartsVector - Create a value that contains the specified legal
323 /// parts combined into the value they represent.  If the parts combine to a
324 /// type larger than ValueVT then AssertOp can be used to specify whether the
325 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
326 /// ValueVT (ISD::AssertSext).
327 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
328                                       const SDValue *Parts, unsigned NumParts,
329                                       MVT PartVT, EVT ValueVT, const Value *V,
330                                       Optional<CallingConv::ID> CallConv) {
331   assert(ValueVT.isVector() && "Not a vector value");
332   assert(NumParts > 0 && "No parts to assemble!");
333   const bool IsABIRegCopy = CallConv.hasValue();
334 
335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
336   SDValue Val = Parts[0];
337 
338   // Handle a multi-element vector.
339   if (NumParts > 1) {
340     EVT IntermediateVT;
341     MVT RegisterVT;
342     unsigned NumIntermediates;
343     unsigned NumRegs;
344 
345     if (IsABIRegCopy) {
346       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
347           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
348           NumIntermediates, RegisterVT);
349     } else {
350       NumRegs =
351           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
352                                      NumIntermediates, RegisterVT);
353     }
354 
355     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
356     NumParts = NumRegs; // Silence a compiler warning.
357     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
358     assert(RegisterVT.getSizeInBits() ==
359            Parts[0].getSimpleValueType().getSizeInBits() &&
360            "Part type sizes don't match!");
361 
362     // Assemble the parts into intermediate operands.
363     SmallVector<SDValue, 8> Ops(NumIntermediates);
364     if (NumIntermediates == NumParts) {
365       // If the register was not expanded, truncate or copy the value,
366       // as appropriate.
367       for (unsigned i = 0; i != NumParts; ++i)
368         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
369                                   PartVT, IntermediateVT, V, CallConv);
370     } else if (NumParts > 0) {
371       // If the intermediate type was expanded, build the intermediate
372       // operands from the parts.
373       assert(NumParts % NumIntermediates == 0 &&
374              "Must expand into a divisible number of parts!");
375       unsigned Factor = NumParts / NumIntermediates;
376       for (unsigned i = 0; i != NumIntermediates; ++i)
377         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
378                                   PartVT, IntermediateVT, V, CallConv);
379     }
380 
381     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
382     // intermediate operands.
383     EVT BuiltVectorTy =
384         IntermediateVT.isVector()
385             ? EVT::getVectorVT(
386                   *DAG.getContext(), IntermediateVT.getScalarType(),
387                   IntermediateVT.getVectorElementCount() * NumParts)
388             : EVT::getVectorVT(*DAG.getContext(),
389                                IntermediateVT.getScalarType(),
390                                NumIntermediates);
391     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
392                                                 : ISD::BUILD_VECTOR,
393                       DL, BuiltVectorTy, Ops);
394   }
395 
396   // There is now one part, held in Val.  Correct it to match ValueVT.
397   EVT PartEVT = Val.getValueType();
398 
399   if (PartEVT == ValueVT)
400     return Val;
401 
402   if (PartEVT.isVector()) {
403     // Vector/Vector bitcast.
404     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
405       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
406 
407     // If the element type of the source/dest vectors are the same, but the
408     // parts vector has more elements than the value vector, then we have a
409     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
410     // elements we want.
411     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
412       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
413               ValueVT.getVectorElementCount().getKnownMinValue()) &&
414              (PartEVT.getVectorElementCount().isScalable() ==
415               ValueVT.getVectorElementCount().isScalable()) &&
416              "Cannot narrow, it would be a lossy transformation");
417       PartEVT =
418           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
419                            ValueVT.getVectorElementCount());
420       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
421                         DAG.getVectorIdxConstant(0, DL));
422       if (PartEVT == ValueVT)
423         return Val;
424     }
425 
426     // Promoted vector extract
427     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
428   }
429 
430   // Trivial bitcast if the types are the same size and the destination
431   // vector type is legal.
432   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
433       TLI.isTypeLegal(ValueVT))
434     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435 
436   if (ValueVT.getVectorNumElements() != 1) {
437      // Certain ABIs require that vectors are passed as integers. For vectors
438      // are the same size, this is an obvious bitcast.
439      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
440        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
441      } else if (ValueVT.bitsLT(PartEVT)) {
442        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
443        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
444        // Drop the extra bits.
445        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
446        return DAG.getBitcast(ValueVT, Val);
447      }
448 
449      diagnosePossiblyInvalidConstraint(
450          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
451      return DAG.getUNDEF(ValueVT);
452   }
453 
454   // Handle cases such as i8 -> <1 x i1>
455   EVT ValueSVT = ValueVT.getVectorElementType();
456   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
457     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
458       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
459     else
460       Val = ValueVT.isFloatingPoint()
461                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
462                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
463   }
464 
465   return DAG.getBuildVector(ValueVT, DL, Val);
466 }
467 
468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
469                                  SDValue Val, SDValue *Parts, unsigned NumParts,
470                                  MVT PartVT, const Value *V,
471                                  Optional<CallingConv::ID> CallConv);
472 
473 /// getCopyToParts - Create a series of nodes that contain the specified value
474 /// split into legal parts.  If the parts contain more bits than Val, then, for
475 /// integers, ExtendKind can be used to specify how to generate the extra bits.
476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
477                            SDValue *Parts, unsigned NumParts, MVT PartVT,
478                            const Value *V,
479                            Optional<CallingConv::ID> CallConv = None,
480                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
481   // Let the target split the parts if it wants to
482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
483   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
484                                       CallConv))
485     return;
486   EVT ValueVT = Val.getValueType();
487 
488   // Handle the vector case separately.
489   if (ValueVT.isVector())
490     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
491                                 CallConv);
492 
493   unsigned PartBits = PartVT.getSizeInBits();
494   unsigned OrigNumParts = NumParts;
495   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
496          "Copying to an illegal type!");
497 
498   if (NumParts == 0)
499     return;
500 
501   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
502   EVT PartEVT = PartVT;
503   if (PartEVT == ValueVT) {
504     assert(NumParts == 1 && "No-op copy with multiple parts!");
505     Parts[0] = Val;
506     return;
507   }
508 
509   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
510     // If the parts cover more bits than the value has, promote the value.
511     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
512       assert(NumParts == 1 && "Do not know what to promote to!");
513       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
514     } else {
515       if (ValueVT.isFloatingPoint()) {
516         // FP values need to be bitcast, then extended if they are being put
517         // into a larger container.
518         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
519         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
520       }
521       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
522              ValueVT.isInteger() &&
523              "Unknown mismatch!");
524       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
525       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
526       if (PartVT == MVT::x86mmx)
527         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
528     }
529   } else if (PartBits == ValueVT.getSizeInBits()) {
530     // Different types of the same size.
531     assert(NumParts == 1 && PartEVT != ValueVT);
532     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
534     // If the parts cover less bits than value has, truncate the value.
535     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
536            ValueVT.isInteger() &&
537            "Unknown mismatch!");
538     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
539     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
540     if (PartVT == MVT::x86mmx)
541       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
542   }
543 
544   // The value may have changed - recompute ValueVT.
545   ValueVT = Val.getValueType();
546   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
547          "Failed to tile the value with PartVT!");
548 
549   if (NumParts == 1) {
550     if (PartEVT != ValueVT) {
551       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
552                                         "scalar-to-vector conversion failed");
553       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554     }
555 
556     Parts[0] = Val;
557     return;
558   }
559 
560   // Expand the value into multiple parts.
561   if (NumParts & (NumParts - 1)) {
562     // The number of parts is not a power of 2.  Split off and copy the tail.
563     assert(PartVT.isInteger() && ValueVT.isInteger() &&
564            "Do not know what to expand to!");
565     unsigned RoundParts = 1 << Log2_32(NumParts);
566     unsigned RoundBits = RoundParts * PartBits;
567     unsigned OddParts = NumParts - RoundParts;
568     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
569       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
570 
571     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
572                    CallConv);
573 
574     if (DAG.getDataLayout().isBigEndian())
575       // The odd parts were reversed by getCopyToParts - unreverse them.
576       std::reverse(Parts + RoundParts, Parts + NumParts);
577 
578     NumParts = RoundParts;
579     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
580     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
581   }
582 
583   // The number of parts is a power of 2.  Repeatedly bisect the value using
584   // EXTRACT_ELEMENT.
585   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
586                          EVT::getIntegerVT(*DAG.getContext(),
587                                            ValueVT.getSizeInBits()),
588                          Val);
589 
590   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
591     for (unsigned i = 0; i < NumParts; i += StepSize) {
592       unsigned ThisBits = StepSize * PartBits / 2;
593       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
594       SDValue &Part0 = Parts[i];
595       SDValue &Part1 = Parts[i+StepSize/2];
596 
597       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
598                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
599       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
600                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
601 
602       if (ThisBits == PartBits && ThisVT != PartVT) {
603         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
604         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
605       }
606     }
607   }
608 
609   if (DAG.getDataLayout().isBigEndian())
610     std::reverse(Parts, Parts + OrigNumParts);
611 }
612 
613 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
614                                      const SDLoc &DL, EVT PartVT) {
615   if (!PartVT.isVector())
616     return SDValue();
617 
618   EVT ValueVT = Val.getValueType();
619   ElementCount PartNumElts = PartVT.getVectorElementCount();
620   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
621 
622   // We only support widening vectors with equivalent element types and
623   // fixed/scalable properties. If a target needs to widen a fixed-length type
624   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
625   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
626       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
627       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
628     return SDValue();
629 
630   // Widening a scalable vector to another scalable vector is done by inserting
631   // the vector into a larger undef one.
632   if (PartNumElts.isScalable())
633     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
634                        Val, DAG.getVectorIdxConstant(0, DL));
635 
636   EVT ElementVT = PartVT.getVectorElementType();
637   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
638   // undef elements.
639   SmallVector<SDValue, 16> Ops;
640   DAG.ExtractVectorElements(Val, Ops);
641   SDValue EltUndef = DAG.getUNDEF(ElementVT);
642   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
643 
644   // FIXME: Use CONCAT for 2x -> 4x.
645   return DAG.getBuildVector(PartVT, DL, Ops);
646 }
647 
648 /// getCopyToPartsVector - Create a series of nodes that contain the specified
649 /// value split into legal parts.
650 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
651                                  SDValue Val, SDValue *Parts, unsigned NumParts,
652                                  MVT PartVT, const Value *V,
653                                  Optional<CallingConv::ID> CallConv) {
654   EVT ValueVT = Val.getValueType();
655   assert(ValueVT.isVector() && "Not a vector");
656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
657   const bool IsABIRegCopy = CallConv.hasValue();
658 
659   if (NumParts == 1) {
660     EVT PartEVT = PartVT;
661     if (PartEVT == ValueVT) {
662       // Nothing to do.
663     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
664       // Bitconvert vector->vector case.
665       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
666     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
667       Val = Widened;
668     } else if (PartVT.isVector() &&
669                PartEVT.getVectorElementType().bitsGE(
670                    ValueVT.getVectorElementType()) &&
671                PartEVT.getVectorElementCount() ==
672                    ValueVT.getVectorElementCount()) {
673 
674       // Promoted vector extract
675       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
676     } else if (PartEVT.isVector() &&
677                PartEVT.getVectorElementType() !=
678                    ValueVT.getVectorElementType() &&
679                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
680                    TargetLowering::TypeWidenVector) {
681       // Combination of widening and promotion.
682       EVT WidenVT =
683           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
684                            PartVT.getVectorElementCount());
685       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
686       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
687     } else {
688       if (ValueVT.getVectorElementCount().isScalar()) {
689         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
690                           DAG.getVectorIdxConstant(0, DL));
691       } else {
692         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
693         assert(PartVT.getFixedSizeInBits() > ValueSize &&
694                "lossy conversion of vector to scalar type");
695         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
696         Val = DAG.getBitcast(IntermediateType, Val);
697         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
698       }
699     }
700 
701     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
702     Parts[0] = Val;
703     return;
704   }
705 
706   // Handle a multi-element vector.
707   EVT IntermediateVT;
708   MVT RegisterVT;
709   unsigned NumIntermediates;
710   unsigned NumRegs;
711   if (IsABIRegCopy) {
712     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
713         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
714         NumIntermediates, RegisterVT);
715   } else {
716     NumRegs =
717         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
718                                    NumIntermediates, RegisterVT);
719   }
720 
721   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
722   NumParts = NumRegs; // Silence a compiler warning.
723   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
724 
725   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
726          "Mixing scalable and fixed vectors when copying in parts");
727 
728   Optional<ElementCount> DestEltCnt;
729 
730   if (IntermediateVT.isVector())
731     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
732   else
733     DestEltCnt = ElementCount::getFixed(NumIntermediates);
734 
735   EVT BuiltVectorTy = EVT::getVectorVT(
736       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
737 
738   if (ValueVT == BuiltVectorTy) {
739     // Nothing to do.
740   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
741     // Bitconvert vector->vector case.
742     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
743   } else {
744     if (BuiltVectorTy.getVectorElementType().bitsGT(
745             ValueVT.getVectorElementType())) {
746       // Integer promotion.
747       ValueVT = EVT::getVectorVT(*DAG.getContext(),
748                                  BuiltVectorTy.getVectorElementType(),
749                                  ValueVT.getVectorElementCount());
750       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
751     }
752 
753     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
754       Val = Widened;
755     }
756   }
757 
758   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
759 
760   // Split the vector into intermediate operands.
761   SmallVector<SDValue, 8> Ops(NumIntermediates);
762   for (unsigned i = 0; i != NumIntermediates; ++i) {
763     if (IntermediateVT.isVector()) {
764       // This does something sensible for scalable vectors - see the
765       // definition of EXTRACT_SUBVECTOR for further details.
766       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
767       Ops[i] =
768           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
769                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
770     } else {
771       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
772                            DAG.getVectorIdxConstant(i, DL));
773     }
774   }
775 
776   // Split the intermediate operands into legal parts.
777   if (NumParts == NumIntermediates) {
778     // If the register was not expanded, promote or copy the value,
779     // as appropriate.
780     for (unsigned i = 0; i != NumParts; ++i)
781       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
782   } else if (NumParts > 0) {
783     // If the intermediate type was expanded, split each the value into
784     // legal parts.
785     assert(NumIntermediates != 0 && "division by zero");
786     assert(NumParts % NumIntermediates == 0 &&
787            "Must expand into a divisible number of parts!");
788     unsigned Factor = NumParts / NumIntermediates;
789     for (unsigned i = 0; i != NumIntermediates; ++i)
790       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
791                      CallConv);
792   }
793 }
794 
795 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
796                            EVT valuevt, Optional<CallingConv::ID> CC)
797     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
798       RegCount(1, regs.size()), CallConv(CC) {}
799 
800 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
801                            const DataLayout &DL, unsigned Reg, Type *Ty,
802                            Optional<CallingConv::ID> CC) {
803   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
804 
805   CallConv = CC;
806 
807   for (EVT ValueVT : ValueVTs) {
808     unsigned NumRegs =
809         isABIMangled()
810             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
811             : TLI.getNumRegisters(Context, ValueVT);
812     MVT RegisterVT =
813         isABIMangled()
814             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
815             : TLI.getRegisterType(Context, ValueVT);
816     for (unsigned i = 0; i != NumRegs; ++i)
817       Regs.push_back(Reg + i);
818     RegVTs.push_back(RegisterVT);
819     RegCount.push_back(NumRegs);
820     Reg += NumRegs;
821   }
822 }
823 
824 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
825                                       FunctionLoweringInfo &FuncInfo,
826                                       const SDLoc &dl, SDValue &Chain,
827                                       SDValue *Flag, const Value *V) const {
828   // A Value with type {} or [0 x %t] needs no registers.
829   if (ValueVTs.empty())
830     return SDValue();
831 
832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
833 
834   // Assemble the legal parts into the final values.
835   SmallVector<SDValue, 4> Values(ValueVTs.size());
836   SmallVector<SDValue, 8> Parts;
837   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
838     // Copy the legal parts from the registers.
839     EVT ValueVT = ValueVTs[Value];
840     unsigned NumRegs = RegCount[Value];
841     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
842                                           *DAG.getContext(),
843                                           CallConv.getValue(), RegVTs[Value])
844                                     : RegVTs[Value];
845 
846     Parts.resize(NumRegs);
847     for (unsigned i = 0; i != NumRegs; ++i) {
848       SDValue P;
849       if (!Flag) {
850         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
851       } else {
852         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
853         *Flag = P.getValue(2);
854       }
855 
856       Chain = P.getValue(1);
857       Parts[i] = P;
858 
859       // If the source register was virtual and if we know something about it,
860       // add an assert node.
861       if (!Register::isVirtualRegister(Regs[Part + i]) ||
862           !RegisterVT.isInteger())
863         continue;
864 
865       const FunctionLoweringInfo::LiveOutInfo *LOI =
866         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
867       if (!LOI)
868         continue;
869 
870       unsigned RegSize = RegisterVT.getScalarSizeInBits();
871       unsigned NumSignBits = LOI->NumSignBits;
872       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
873 
874       if (NumZeroBits == RegSize) {
875         // The current value is a zero.
876         // Explicitly express that as it would be easier for
877         // optimizations to kick in.
878         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
879         continue;
880       }
881 
882       // FIXME: We capture more information than the dag can represent.  For
883       // now, just use the tightest assertzext/assertsext possible.
884       bool isSExt;
885       EVT FromVT(MVT::Other);
886       if (NumZeroBits) {
887         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
888         isSExt = false;
889       } else if (NumSignBits > 1) {
890         FromVT =
891             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
892         isSExt = true;
893       } else {
894         continue;
895       }
896       // Add an assertion node.
897       assert(FromVT != MVT::Other);
898       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
899                              RegisterVT, P, DAG.getValueType(FromVT));
900     }
901 
902     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
903                                      RegisterVT, ValueVT, V, CallConv);
904     Part += NumRegs;
905     Parts.clear();
906   }
907 
908   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
909 }
910 
911 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
912                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
913                                  const Value *V,
914                                  ISD::NodeType PreferredExtendType) const {
915   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
916   ISD::NodeType ExtendKind = PreferredExtendType;
917 
918   // Get the list of the values's legal parts.
919   unsigned NumRegs = Regs.size();
920   SmallVector<SDValue, 8> Parts(NumRegs);
921   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
922     unsigned NumParts = RegCount[Value];
923 
924     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
925                                           *DAG.getContext(),
926                                           CallConv.getValue(), RegVTs[Value])
927                                     : RegVTs[Value];
928 
929     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
930       ExtendKind = ISD::ZERO_EXTEND;
931 
932     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
933                    NumParts, RegisterVT, V, CallConv, ExtendKind);
934     Part += NumParts;
935   }
936 
937   // Copy the parts into the registers.
938   SmallVector<SDValue, 8> Chains(NumRegs);
939   for (unsigned i = 0; i != NumRegs; ++i) {
940     SDValue Part;
941     if (!Flag) {
942       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
943     } else {
944       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
945       *Flag = Part.getValue(1);
946     }
947 
948     Chains[i] = Part.getValue(0);
949   }
950 
951   if (NumRegs == 1 || Flag)
952     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
953     // flagged to it. That is the CopyToReg nodes and the user are considered
954     // a single scheduling unit. If we create a TokenFactor and return it as
955     // chain, then the TokenFactor is both a predecessor (operand) of the
956     // user as well as a successor (the TF operands are flagged to the user).
957     // c1, f1 = CopyToReg
958     // c2, f2 = CopyToReg
959     // c3     = TokenFactor c1, c2
960     // ...
961     //        = op c3, ..., f2
962     Chain = Chains[NumRegs-1];
963   else
964     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
965 }
966 
967 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
968                                         unsigned MatchingIdx, const SDLoc &dl,
969                                         SelectionDAG &DAG,
970                                         std::vector<SDValue> &Ops) const {
971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
972 
973   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
974   if (HasMatching)
975     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
976   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
977     // Put the register class of the virtual registers in the flag word.  That
978     // way, later passes can recompute register class constraints for inline
979     // assembly as well as normal instructions.
980     // Don't do this for tied operands that can use the regclass information
981     // from the def.
982     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
983     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
984     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
985   }
986 
987   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
988   Ops.push_back(Res);
989 
990   if (Code == InlineAsm::Kind_Clobber) {
991     // Clobbers should always have a 1:1 mapping with registers, and may
992     // reference registers that have illegal (e.g. vector) types. Hence, we
993     // shouldn't try to apply any sort of splitting logic to them.
994     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
995            "No 1:1 mapping from clobbers to regs?");
996     Register SP = TLI.getStackPointerRegisterToSaveRestore();
997     (void)SP;
998     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
999       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1000       assert(
1001           (Regs[I] != SP ||
1002            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1003           "If we clobbered the stack pointer, MFI should know about it.");
1004     }
1005     return;
1006   }
1007 
1008   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1009     MVT RegisterVT = RegVTs[Value];
1010     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1011                                            RegisterVT);
1012     for (unsigned i = 0; i != NumRegs; ++i) {
1013       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1014       unsigned TheReg = Regs[Reg++];
1015       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1016     }
1017   }
1018 }
1019 
1020 SmallVector<std::pair<unsigned, TypeSize>, 4>
1021 RegsForValue::getRegsAndSizes() const {
1022   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1023   unsigned I = 0;
1024   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1025     unsigned RegCount = std::get<0>(CountAndVT);
1026     MVT RegisterVT = std::get<1>(CountAndVT);
1027     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1028     for (unsigned E = I + RegCount; I != E; ++I)
1029       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1030   }
1031   return OutVec;
1032 }
1033 
1034 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1035                                const TargetLibraryInfo *li) {
1036   AA = aa;
1037   GFI = gfi;
1038   LibInfo = li;
1039   Context = DAG.getContext();
1040   LPadToCallSiteMap.clear();
1041   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1042 }
1043 
1044 void SelectionDAGBuilder::clear() {
1045   NodeMap.clear();
1046   UnusedArgNodeMap.clear();
1047   PendingLoads.clear();
1048   PendingExports.clear();
1049   PendingConstrainedFP.clear();
1050   PendingConstrainedFPStrict.clear();
1051   CurInst = nullptr;
1052   HasTailCall = false;
1053   SDNodeOrder = LowestSDNodeOrder;
1054   StatepointLowering.clear();
1055 }
1056 
1057 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1058   DanglingDebugInfoMap.clear();
1059 }
1060 
1061 // Update DAG root to include dependencies on Pending chains.
1062 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1063   SDValue Root = DAG.getRoot();
1064 
1065   if (Pending.empty())
1066     return Root;
1067 
1068   // Add current root to PendingChains, unless we already indirectly
1069   // depend on it.
1070   if (Root.getOpcode() != ISD::EntryToken) {
1071     unsigned i = 0, e = Pending.size();
1072     for (; i != e; ++i) {
1073       assert(Pending[i].getNode()->getNumOperands() > 1);
1074       if (Pending[i].getNode()->getOperand(0) == Root)
1075         break;  // Don't add the root if we already indirectly depend on it.
1076     }
1077 
1078     if (i == e)
1079       Pending.push_back(Root);
1080   }
1081 
1082   if (Pending.size() == 1)
1083     Root = Pending[0];
1084   else
1085     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1086 
1087   DAG.setRoot(Root);
1088   Pending.clear();
1089   return Root;
1090 }
1091 
1092 SDValue SelectionDAGBuilder::getMemoryRoot() {
1093   return updateRoot(PendingLoads);
1094 }
1095 
1096 SDValue SelectionDAGBuilder::getRoot() {
1097   // Chain up all pending constrained intrinsics together with all
1098   // pending loads, by simply appending them to PendingLoads and
1099   // then calling getMemoryRoot().
1100   PendingLoads.reserve(PendingLoads.size() +
1101                        PendingConstrainedFP.size() +
1102                        PendingConstrainedFPStrict.size());
1103   PendingLoads.append(PendingConstrainedFP.begin(),
1104                       PendingConstrainedFP.end());
1105   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1106                       PendingConstrainedFPStrict.end());
1107   PendingConstrainedFP.clear();
1108   PendingConstrainedFPStrict.clear();
1109   return getMemoryRoot();
1110 }
1111 
1112 SDValue SelectionDAGBuilder::getControlRoot() {
1113   // We need to emit pending fpexcept.strict constrained intrinsics,
1114   // so append them to the PendingExports list.
1115   PendingExports.append(PendingConstrainedFPStrict.begin(),
1116                         PendingConstrainedFPStrict.end());
1117   PendingConstrainedFPStrict.clear();
1118   return updateRoot(PendingExports);
1119 }
1120 
1121 void SelectionDAGBuilder::visit(const Instruction &I) {
1122   // Set up outgoing PHI node register values before emitting the terminator.
1123   if (I.isTerminator()) {
1124     HandlePHINodesInSuccessorBlocks(I.getParent());
1125   }
1126 
1127   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1128   if (!isa<DbgInfoIntrinsic>(I))
1129     ++SDNodeOrder;
1130 
1131   CurInst = &I;
1132 
1133   visit(I.getOpcode(), I);
1134 
1135   if (!I.isTerminator() && !HasTailCall &&
1136       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1137     CopyToExportRegsIfNeeded(&I);
1138 
1139   CurInst = nullptr;
1140 }
1141 
1142 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1143   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1144 }
1145 
1146 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1147   // Note: this doesn't use InstVisitor, because it has to work with
1148   // ConstantExpr's in addition to instructions.
1149   switch (Opcode) {
1150   default: llvm_unreachable("Unknown instruction type encountered!");
1151     // Build the switch statement using the Instruction.def file.
1152 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1153     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1154 #include "llvm/IR/Instruction.def"
1155   }
1156 }
1157 
1158 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1159                                                DebugLoc DL, unsigned Order) {
1160   // We treat variadic dbg_values differently at this stage.
1161   if (DI->hasArgList()) {
1162     // For variadic dbg_values we will now insert an undef.
1163     // FIXME: We can potentially recover these!
1164     SmallVector<SDDbgOperand, 2> Locs;
1165     for (const Value *V : DI->getValues()) {
1166       auto Undef = UndefValue::get(V->getType());
1167       Locs.push_back(SDDbgOperand::fromConst(Undef));
1168     }
1169     SDDbgValue *SDV = DAG.getDbgValueList(
1170         DI->getVariable(), DI->getExpression(), Locs, {},
1171         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1172     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1173   } else {
1174     // TODO: Dangling debug info will eventually either be resolved or produce
1175     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1176     // between the original dbg.value location and its resolved DBG_VALUE,
1177     // which we should ideally fill with an extra Undef DBG_VALUE.
1178     assert(DI->getNumVariableLocationOps() == 1 &&
1179            "DbgValueInst without an ArgList should have a single location "
1180            "operand.");
1181     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1182   }
1183 }
1184 
1185 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1186                                                 const DIExpression *Expr) {
1187   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1188     const DbgValueInst *DI = DDI.getDI();
1189     DIVariable *DanglingVariable = DI->getVariable();
1190     DIExpression *DanglingExpr = DI->getExpression();
1191     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1192       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1193       return true;
1194     }
1195     return false;
1196   };
1197 
1198   for (auto &DDIMI : DanglingDebugInfoMap) {
1199     DanglingDebugInfoVector &DDIV = DDIMI.second;
1200 
1201     // If debug info is to be dropped, run it through final checks to see
1202     // whether it can be salvaged.
1203     for (auto &DDI : DDIV)
1204       if (isMatchingDbgValue(DDI))
1205         salvageUnresolvedDbgValue(DDI);
1206 
1207     erase_if(DDIV, isMatchingDbgValue);
1208   }
1209 }
1210 
1211 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1212 // generate the debug data structures now that we've seen its definition.
1213 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1214                                                    SDValue Val) {
1215   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1216   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1217     return;
1218 
1219   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1220   for (auto &DDI : DDIV) {
1221     const DbgValueInst *DI = DDI.getDI();
1222     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1223     assert(DI && "Ill-formed DanglingDebugInfo");
1224     DebugLoc dl = DDI.getdl();
1225     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1226     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1227     DILocalVariable *Variable = DI->getVariable();
1228     DIExpression *Expr = DI->getExpression();
1229     assert(Variable->isValidLocationForIntrinsic(dl) &&
1230            "Expected inlined-at fields to agree");
1231     SDDbgValue *SDV;
1232     if (Val.getNode()) {
1233       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1234       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1235       // we couldn't resolve it directly when examining the DbgValue intrinsic
1236       // in the first place we should not be more successful here). Unless we
1237       // have some test case that prove this to be correct we should avoid
1238       // calling EmitFuncArgumentDbgValue here.
1239       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1240         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1241                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1242         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1243         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1244         // inserted after the definition of Val when emitting the instructions
1245         // after ISel. An alternative could be to teach
1246         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1247         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1248                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1249                    << ValSDNodeOrder << "\n");
1250         SDV = getDbgValue(Val, Variable, Expr, dl,
1251                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1252         DAG.AddDbgValue(SDV, false);
1253       } else
1254         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1255                           << "in EmitFuncArgumentDbgValue\n");
1256     } else {
1257       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1258       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1259       auto SDV =
1260           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1261       DAG.AddDbgValue(SDV, false);
1262     }
1263   }
1264   DDIV.clear();
1265 }
1266 
1267 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1268   // TODO: For the variadic implementation, instead of only checking the fail
1269   // state of `handleDebugValue`, we need know specifically which values were
1270   // invalid, so that we attempt to salvage only those values when processing
1271   // a DIArgList.
1272   assert(!DDI.getDI()->hasArgList() &&
1273          "Not implemented for variadic dbg_values");
1274   Value *V = DDI.getDI()->getValue(0);
1275   DILocalVariable *Var = DDI.getDI()->getVariable();
1276   DIExpression *Expr = DDI.getDI()->getExpression();
1277   DebugLoc DL = DDI.getdl();
1278   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1279   unsigned SDOrder = DDI.getSDNodeOrder();
1280   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1281   // that DW_OP_stack_value is desired.
1282   assert(isa<DbgValueInst>(DDI.getDI()));
1283   bool StackValue = true;
1284 
1285   // Can this Value can be encoded without any further work?
1286   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1287     return;
1288 
1289   // Attempt to salvage back through as many instructions as possible. Bail if
1290   // a non-instruction is seen, such as a constant expression or global
1291   // variable. FIXME: Further work could recover those too.
1292   while (isa<Instruction>(V)) {
1293     Instruction &VAsInst = *cast<Instruction>(V);
1294     // Temporary "0", awaiting real implementation.
1295     SmallVector<uint64_t, 16> Ops;
1296     SmallVector<Value *, 4> AdditionalValues;
1297     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1298                              AdditionalValues);
1299     // If we cannot salvage any further, and haven't yet found a suitable debug
1300     // expression, bail out.
1301     if (!V)
1302       break;
1303 
1304     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1305     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1306     // here for variadic dbg_values, remove that condition.
1307     if (!AdditionalValues.empty())
1308       break;
1309 
1310     // New value and expr now represent this debuginfo.
1311     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1312 
1313     // Some kind of simplification occurred: check whether the operand of the
1314     // salvaged debug expression can be encoded in this DAG.
1315     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1316                          /*IsVariadic=*/false)) {
1317       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1318                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1319       return;
1320     }
1321   }
1322 
1323   // This was the final opportunity to salvage this debug information, and it
1324   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1325   // any earlier variable location.
1326   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1327   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1328   DAG.AddDbgValue(SDV, false);
1329 
1330   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1331                     << "\n");
1332   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1333                     << "\n");
1334 }
1335 
1336 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1337                                            DILocalVariable *Var,
1338                                            DIExpression *Expr, DebugLoc dl,
1339                                            DebugLoc InstDL, unsigned Order,
1340                                            bool IsVariadic) {
1341   if (Values.empty())
1342     return true;
1343   SmallVector<SDDbgOperand> LocationOps;
1344   SmallVector<SDNode *> Dependencies;
1345   for (const Value *V : Values) {
1346     // Constant value.
1347     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1348         isa<ConstantPointerNull>(V)) {
1349       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1350       continue;
1351     }
1352 
1353     // If the Value is a frame index, we can create a FrameIndex debug value
1354     // without relying on the DAG at all.
1355     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1356       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1357       if (SI != FuncInfo.StaticAllocaMap.end()) {
1358         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1359         continue;
1360       }
1361     }
1362 
1363     // Do not use getValue() in here; we don't want to generate code at
1364     // this point if it hasn't been done yet.
1365     SDValue N = NodeMap[V];
1366     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1367       N = UnusedArgNodeMap[V];
1368     if (N.getNode()) {
1369       // Only emit func arg dbg value for non-variadic dbg.values for now.
1370       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1371         return true;
1372       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1373         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1374         // describe stack slot locations.
1375         //
1376         // Consider "int x = 0; int *px = &x;". There are two kinds of
1377         // interesting debug values here after optimization:
1378         //
1379         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1380         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1381         //
1382         // Both describe the direct values of their associated variables.
1383         Dependencies.push_back(N.getNode());
1384         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1385         continue;
1386       }
1387       LocationOps.emplace_back(
1388           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1389       continue;
1390     }
1391 
1392     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1393     // Special rules apply for the first dbg.values of parameter variables in a
1394     // function. Identify them by the fact they reference Argument Values, that
1395     // they're parameters, and they are parameters of the current function. We
1396     // need to let them dangle until they get an SDNode.
1397     bool IsParamOfFunc =
1398         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1399     if (IsParamOfFunc)
1400       return false;
1401 
1402     // The value is not used in this block yet (or it would have an SDNode).
1403     // We still want the value to appear for the user if possible -- if it has
1404     // an associated VReg, we can refer to that instead.
1405     auto VMI = FuncInfo.ValueMap.find(V);
1406     if (VMI != FuncInfo.ValueMap.end()) {
1407       unsigned Reg = VMI->second;
1408       // If this is a PHI node, it may be split up into several MI PHI nodes
1409       // (in FunctionLoweringInfo::set).
1410       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1411                        V->getType(), None);
1412       if (RFV.occupiesMultipleRegs()) {
1413         // FIXME: We could potentially support variadic dbg_values here.
1414         if (IsVariadic)
1415           return false;
1416         unsigned Offset = 0;
1417         unsigned BitsToDescribe = 0;
1418         if (auto VarSize = Var->getSizeInBits())
1419           BitsToDescribe = *VarSize;
1420         if (auto Fragment = Expr->getFragmentInfo())
1421           BitsToDescribe = Fragment->SizeInBits;
1422         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1423           // Bail out if all bits are described already.
1424           if (Offset >= BitsToDescribe)
1425             break;
1426           // TODO: handle scalable vectors.
1427           unsigned RegisterSize = RegAndSize.second;
1428           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1429                                       ? BitsToDescribe - Offset
1430                                       : RegisterSize;
1431           auto FragmentExpr = DIExpression::createFragmentExpression(
1432               Expr, Offset, FragmentSize);
1433           if (!FragmentExpr)
1434             continue;
1435           SDDbgValue *SDV = DAG.getVRegDbgValue(
1436               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1437           DAG.AddDbgValue(SDV, false);
1438           Offset += RegisterSize;
1439         }
1440         return true;
1441       }
1442       // We can use simple vreg locations for variadic dbg_values as well.
1443       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1444       continue;
1445     }
1446     // We failed to create a SDDbgOperand for V.
1447     return false;
1448   }
1449 
1450   // We have created a SDDbgOperand for each Value in Values.
1451   // Should use Order instead of SDNodeOrder?
1452   assert(!LocationOps.empty());
1453   SDDbgValue *SDV =
1454       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1455                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1456   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1457   return true;
1458 }
1459 
1460 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1461   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1462   for (auto &Pair : DanglingDebugInfoMap)
1463     for (auto &DDI : Pair.second)
1464       salvageUnresolvedDbgValue(DDI);
1465   clearDanglingDebugInfo();
1466 }
1467 
1468 /// getCopyFromRegs - If there was virtual register allocated for the value V
1469 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1470 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1471   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1472   SDValue Result;
1473 
1474   if (It != FuncInfo.ValueMap.end()) {
1475     Register InReg = It->second;
1476 
1477     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1478                      DAG.getDataLayout(), InReg, Ty,
1479                      None); // This is not an ABI copy.
1480     SDValue Chain = DAG.getEntryNode();
1481     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1482                                  V);
1483     resolveDanglingDebugInfo(V, Result);
1484   }
1485 
1486   return Result;
1487 }
1488 
1489 /// getValue - Return an SDValue for the given Value.
1490 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1491   // If we already have an SDValue for this value, use it. It's important
1492   // to do this first, so that we don't create a CopyFromReg if we already
1493   // have a regular SDValue.
1494   SDValue &N = NodeMap[V];
1495   if (N.getNode()) return N;
1496 
1497   // If there's a virtual register allocated and initialized for this
1498   // value, use it.
1499   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1500     return copyFromReg;
1501 
1502   // Otherwise create a new SDValue and remember it.
1503   SDValue Val = getValueImpl(V);
1504   NodeMap[V] = Val;
1505   resolveDanglingDebugInfo(V, Val);
1506   return Val;
1507 }
1508 
1509 /// getNonRegisterValue - Return an SDValue for the given Value, but
1510 /// don't look in FuncInfo.ValueMap for a virtual register.
1511 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1512   // If we already have an SDValue for this value, use it.
1513   SDValue &N = NodeMap[V];
1514   if (N.getNode()) {
1515     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1516       // Remove the debug location from the node as the node is about to be used
1517       // in a location which may differ from the original debug location.  This
1518       // is relevant to Constant and ConstantFP nodes because they can appear
1519       // as constant expressions inside PHI nodes.
1520       N->setDebugLoc(DebugLoc());
1521     }
1522     return N;
1523   }
1524 
1525   // Otherwise create a new SDValue and remember it.
1526   SDValue Val = getValueImpl(V);
1527   NodeMap[V] = Val;
1528   resolveDanglingDebugInfo(V, Val);
1529   return Val;
1530 }
1531 
1532 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1533 /// Create an SDValue for the given value.
1534 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1536 
1537   if (const Constant *C = dyn_cast<Constant>(V)) {
1538     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1539 
1540     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1541       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1542 
1543     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1544       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1545 
1546     if (isa<ConstantPointerNull>(C)) {
1547       unsigned AS = V->getType()->getPointerAddressSpace();
1548       return DAG.getConstant(0, getCurSDLoc(),
1549                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1550     }
1551 
1552     if (match(C, m_VScale(DAG.getDataLayout())))
1553       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1554 
1555     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1556       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1557 
1558     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1559       return DAG.getUNDEF(VT);
1560 
1561     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1562       visit(CE->getOpcode(), *CE);
1563       SDValue N1 = NodeMap[V];
1564       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1565       return N1;
1566     }
1567 
1568     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1569       SmallVector<SDValue, 4> Constants;
1570       for (const Use &U : C->operands()) {
1571         SDNode *Val = getValue(U).getNode();
1572         // If the operand is an empty aggregate, there are no values.
1573         if (!Val) continue;
1574         // Add each leaf value from the operand to the Constants list
1575         // to form a flattened list of all the values.
1576         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1577           Constants.push_back(SDValue(Val, i));
1578       }
1579 
1580       return DAG.getMergeValues(Constants, getCurSDLoc());
1581     }
1582 
1583     if (const ConstantDataSequential *CDS =
1584           dyn_cast<ConstantDataSequential>(C)) {
1585       SmallVector<SDValue, 4> Ops;
1586       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1587         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1588         // Add each leaf value from the operand to the Constants list
1589         // to form a flattened list of all the values.
1590         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1591           Ops.push_back(SDValue(Val, i));
1592       }
1593 
1594       if (isa<ArrayType>(CDS->getType()))
1595         return DAG.getMergeValues(Ops, getCurSDLoc());
1596       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1597     }
1598 
1599     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1600       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1601              "Unknown struct or array constant!");
1602 
1603       SmallVector<EVT, 4> ValueVTs;
1604       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1605       unsigned NumElts = ValueVTs.size();
1606       if (NumElts == 0)
1607         return SDValue(); // empty struct
1608       SmallVector<SDValue, 4> Constants(NumElts);
1609       for (unsigned i = 0; i != NumElts; ++i) {
1610         EVT EltVT = ValueVTs[i];
1611         if (isa<UndefValue>(C))
1612           Constants[i] = DAG.getUNDEF(EltVT);
1613         else if (EltVT.isFloatingPoint())
1614           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1615         else
1616           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1617       }
1618 
1619       return DAG.getMergeValues(Constants, getCurSDLoc());
1620     }
1621 
1622     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1623       return DAG.getBlockAddress(BA, VT);
1624 
1625     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1626       return getValue(Equiv->getGlobalValue());
1627 
1628     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1629       return getValue(NC->getGlobalValue());
1630 
1631     VectorType *VecTy = cast<VectorType>(V->getType());
1632 
1633     // Now that we know the number and type of the elements, get that number of
1634     // elements into the Ops array based on what kind of constant it is.
1635     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1636       SmallVector<SDValue, 16> Ops;
1637       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1638       for (unsigned i = 0; i != NumElements; ++i)
1639         Ops.push_back(getValue(CV->getOperand(i)));
1640 
1641       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1642     } else if (isa<ConstantAggregateZero>(C)) {
1643       EVT EltVT =
1644           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1645 
1646       SDValue Op;
1647       if (EltVT.isFloatingPoint())
1648         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1649       else
1650         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1651 
1652       if (isa<ScalableVectorType>(VecTy))
1653         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1654       else {
1655         SmallVector<SDValue, 16> Ops;
1656         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1657         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1658       }
1659     }
1660     llvm_unreachable("Unknown vector constant");
1661   }
1662 
1663   // If this is a static alloca, generate it as the frameindex instead of
1664   // computation.
1665   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1666     DenseMap<const AllocaInst*, int>::iterator SI =
1667       FuncInfo.StaticAllocaMap.find(AI);
1668     if (SI != FuncInfo.StaticAllocaMap.end())
1669       return DAG.getFrameIndex(SI->second,
1670                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1671   }
1672 
1673   // If this is an instruction which fast-isel has deferred, select it now.
1674   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1675     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1676 
1677     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1678                      Inst->getType(), None);
1679     SDValue Chain = DAG.getEntryNode();
1680     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1681   }
1682 
1683   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1684     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1685   }
1686   llvm_unreachable("Can't get register for value!");
1687 }
1688 
1689 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1690   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1691   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1692   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1693   bool IsSEH = isAsynchronousEHPersonality(Pers);
1694   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1695   if (!IsSEH)
1696     CatchPadMBB->setIsEHScopeEntry();
1697   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1698   if (IsMSVCCXX || IsCoreCLR)
1699     CatchPadMBB->setIsEHFuncletEntry();
1700 }
1701 
1702 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1703   // Update machine-CFG edge.
1704   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1705   FuncInfo.MBB->addSuccessor(TargetMBB);
1706   TargetMBB->setIsEHCatchretTarget(true);
1707   DAG.getMachineFunction().setHasEHCatchret(true);
1708 
1709   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1710   bool IsSEH = isAsynchronousEHPersonality(Pers);
1711   if (IsSEH) {
1712     // If this is not a fall-through branch or optimizations are switched off,
1713     // emit the branch.
1714     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1715         TM.getOptLevel() == CodeGenOpt::None)
1716       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1717                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1718     return;
1719   }
1720 
1721   // Figure out the funclet membership for the catchret's successor.
1722   // This will be used by the FuncletLayout pass to determine how to order the
1723   // BB's.
1724   // A 'catchret' returns to the outer scope's color.
1725   Value *ParentPad = I.getCatchSwitchParentPad();
1726   const BasicBlock *SuccessorColor;
1727   if (isa<ConstantTokenNone>(ParentPad))
1728     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1729   else
1730     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1731   assert(SuccessorColor && "No parent funclet for catchret!");
1732   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1733   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1734 
1735   // Create the terminator node.
1736   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1737                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1738                             DAG.getBasicBlock(SuccessorColorMBB));
1739   DAG.setRoot(Ret);
1740 }
1741 
1742 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1743   // Don't emit any special code for the cleanuppad instruction. It just marks
1744   // the start of an EH scope/funclet.
1745   FuncInfo.MBB->setIsEHScopeEntry();
1746   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1747   if (Pers != EHPersonality::Wasm_CXX) {
1748     FuncInfo.MBB->setIsEHFuncletEntry();
1749     FuncInfo.MBB->setIsCleanupFuncletEntry();
1750   }
1751 }
1752 
1753 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1754 // not match, it is OK to add only the first unwind destination catchpad to the
1755 // successors, because there will be at least one invoke instruction within the
1756 // catch scope that points to the next unwind destination, if one exists, so
1757 // CFGSort cannot mess up with BB sorting order.
1758 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1759 // call within them, and catchpads only consisting of 'catch (...)' have a
1760 // '__cxa_end_catch' call within them, both of which generate invokes in case
1761 // the next unwind destination exists, i.e., the next unwind destination is not
1762 // the caller.)
1763 //
1764 // Having at most one EH pad successor is also simpler and helps later
1765 // transformations.
1766 //
1767 // For example,
1768 // current:
1769 //   invoke void @foo to ... unwind label %catch.dispatch
1770 // catch.dispatch:
1771 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1772 // catch.start:
1773 //   ...
1774 //   ... in this BB or some other child BB dominated by this BB there will be an
1775 //   invoke that points to 'next' BB as an unwind destination
1776 //
1777 // next: ; We don't need to add this to 'current' BB's successor
1778 //   ...
1779 static void findWasmUnwindDestinations(
1780     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1781     BranchProbability Prob,
1782     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1783         &UnwindDests) {
1784   while (EHPadBB) {
1785     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1786     if (isa<CleanupPadInst>(Pad)) {
1787       // Stop on cleanup pads.
1788       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1789       UnwindDests.back().first->setIsEHScopeEntry();
1790       break;
1791     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1792       // Add the catchpad handlers to the possible destinations. We don't
1793       // continue to the unwind destination of the catchswitch for wasm.
1794       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1795         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1796         UnwindDests.back().first->setIsEHScopeEntry();
1797       }
1798       break;
1799     } else {
1800       continue;
1801     }
1802   }
1803 }
1804 
1805 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1806 /// many places it could ultimately go. In the IR, we have a single unwind
1807 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1808 /// This function skips over imaginary basic blocks that hold catchswitch
1809 /// instructions, and finds all the "real" machine
1810 /// basic block destinations. As those destinations may not be successors of
1811 /// EHPadBB, here we also calculate the edge probability to those destinations.
1812 /// The passed-in Prob is the edge probability to EHPadBB.
1813 static void findUnwindDestinations(
1814     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1815     BranchProbability Prob,
1816     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1817         &UnwindDests) {
1818   EHPersonality Personality =
1819     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1820   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1821   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1822   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1823   bool IsSEH = isAsynchronousEHPersonality(Personality);
1824 
1825   if (IsWasmCXX) {
1826     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1827     assert(UnwindDests.size() <= 1 &&
1828            "There should be at most one unwind destination for wasm");
1829     return;
1830   }
1831 
1832   while (EHPadBB) {
1833     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1834     BasicBlock *NewEHPadBB = nullptr;
1835     if (isa<LandingPadInst>(Pad)) {
1836       // Stop on landingpads. They are not funclets.
1837       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1838       break;
1839     } else if (isa<CleanupPadInst>(Pad)) {
1840       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1841       // personalities.
1842       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1843       UnwindDests.back().first->setIsEHScopeEntry();
1844       UnwindDests.back().first->setIsEHFuncletEntry();
1845       break;
1846     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1847       // Add the catchpad handlers to the possible destinations.
1848       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1849         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1850         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1851         if (IsMSVCCXX || IsCoreCLR)
1852           UnwindDests.back().first->setIsEHFuncletEntry();
1853         if (!IsSEH)
1854           UnwindDests.back().first->setIsEHScopeEntry();
1855       }
1856       NewEHPadBB = CatchSwitch->getUnwindDest();
1857     } else {
1858       continue;
1859     }
1860 
1861     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1862     if (BPI && NewEHPadBB)
1863       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1864     EHPadBB = NewEHPadBB;
1865   }
1866 }
1867 
1868 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1869   // Update successor info.
1870   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1871   auto UnwindDest = I.getUnwindDest();
1872   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1873   BranchProbability UnwindDestProb =
1874       (BPI && UnwindDest)
1875           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1876           : BranchProbability::getZero();
1877   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1878   for (auto &UnwindDest : UnwindDests) {
1879     UnwindDest.first->setIsEHPad();
1880     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1881   }
1882   FuncInfo.MBB->normalizeSuccProbs();
1883 
1884   // Create the terminator node.
1885   SDValue Ret =
1886       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1887   DAG.setRoot(Ret);
1888 }
1889 
1890 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1891   report_fatal_error("visitCatchSwitch not yet implemented!");
1892 }
1893 
1894 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1896   auto &DL = DAG.getDataLayout();
1897   SDValue Chain = getControlRoot();
1898   SmallVector<ISD::OutputArg, 8> Outs;
1899   SmallVector<SDValue, 8> OutVals;
1900 
1901   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1902   // lower
1903   //
1904   //   %val = call <ty> @llvm.experimental.deoptimize()
1905   //   ret <ty> %val
1906   //
1907   // differently.
1908   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1909     LowerDeoptimizingReturn();
1910     return;
1911   }
1912 
1913   if (!FuncInfo.CanLowerReturn) {
1914     unsigned DemoteReg = FuncInfo.DemoteRegister;
1915     const Function *F = I.getParent()->getParent();
1916 
1917     // Emit a store of the return value through the virtual register.
1918     // Leave Outs empty so that LowerReturn won't try to load return
1919     // registers the usual way.
1920     SmallVector<EVT, 1> PtrValueVTs;
1921     ComputeValueVTs(TLI, DL,
1922                     F->getReturnType()->getPointerTo(
1923                         DAG.getDataLayout().getAllocaAddrSpace()),
1924                     PtrValueVTs);
1925 
1926     SDValue RetPtr =
1927         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1928     SDValue RetOp = getValue(I.getOperand(0));
1929 
1930     SmallVector<EVT, 4> ValueVTs, MemVTs;
1931     SmallVector<uint64_t, 4> Offsets;
1932     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1933                     &Offsets);
1934     unsigned NumValues = ValueVTs.size();
1935 
1936     SmallVector<SDValue, 4> Chains(NumValues);
1937     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1938     for (unsigned i = 0; i != NumValues; ++i) {
1939       // An aggregate return value cannot wrap around the address space, so
1940       // offsets to its parts don't wrap either.
1941       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1942                                            TypeSize::Fixed(Offsets[i]));
1943 
1944       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1945       if (MemVTs[i] != ValueVTs[i])
1946         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1947       Chains[i] = DAG.getStore(
1948           Chain, getCurSDLoc(), Val,
1949           // FIXME: better loc info would be nice.
1950           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1951           commonAlignment(BaseAlign, Offsets[i]));
1952     }
1953 
1954     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1955                         MVT::Other, Chains);
1956   } else if (I.getNumOperands() != 0) {
1957     SmallVector<EVT, 4> ValueVTs;
1958     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1959     unsigned NumValues = ValueVTs.size();
1960     if (NumValues) {
1961       SDValue RetOp = getValue(I.getOperand(0));
1962 
1963       const Function *F = I.getParent()->getParent();
1964 
1965       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1966           I.getOperand(0)->getType(), F->getCallingConv(),
1967           /*IsVarArg*/ false, DL);
1968 
1969       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1970       if (F->getAttributes().hasRetAttr(Attribute::SExt))
1971         ExtendKind = ISD::SIGN_EXTEND;
1972       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
1973         ExtendKind = ISD::ZERO_EXTEND;
1974 
1975       LLVMContext &Context = F->getContext();
1976       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
1977 
1978       for (unsigned j = 0; j != NumValues; ++j) {
1979         EVT VT = ValueVTs[j];
1980 
1981         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1982           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1983 
1984         CallingConv::ID CC = F->getCallingConv();
1985 
1986         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1987         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1988         SmallVector<SDValue, 4> Parts(NumParts);
1989         getCopyToParts(DAG, getCurSDLoc(),
1990                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1991                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1992 
1993         // 'inreg' on function refers to return value
1994         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1995         if (RetInReg)
1996           Flags.setInReg();
1997 
1998         if (I.getOperand(0)->getType()->isPointerTy()) {
1999           Flags.setPointer();
2000           Flags.setPointerAddrSpace(
2001               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2002         }
2003 
2004         if (NeedsRegBlock) {
2005           Flags.setInConsecutiveRegs();
2006           if (j == NumValues - 1)
2007             Flags.setInConsecutiveRegsLast();
2008         }
2009 
2010         // Propagate extension type if any
2011         if (ExtendKind == ISD::SIGN_EXTEND)
2012           Flags.setSExt();
2013         else if (ExtendKind == ISD::ZERO_EXTEND)
2014           Flags.setZExt();
2015 
2016         for (unsigned i = 0; i < NumParts; ++i) {
2017           Outs.push_back(ISD::OutputArg(Flags,
2018                                         Parts[i].getValueType().getSimpleVT(),
2019                                         VT, /*isfixed=*/true, 0, 0));
2020           OutVals.push_back(Parts[i]);
2021         }
2022       }
2023     }
2024   }
2025 
2026   // Push in swifterror virtual register as the last element of Outs. This makes
2027   // sure swifterror virtual register will be returned in the swifterror
2028   // physical register.
2029   const Function *F = I.getParent()->getParent();
2030   if (TLI.supportSwiftError() &&
2031       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2032     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2033     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2034     Flags.setSwiftError();
2035     Outs.push_back(ISD::OutputArg(
2036         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2037         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2038     // Create SDNode for the swifterror virtual register.
2039     OutVals.push_back(
2040         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2041                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2042                         EVT(TLI.getPointerTy(DL))));
2043   }
2044 
2045   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2046   CallingConv::ID CallConv =
2047     DAG.getMachineFunction().getFunction().getCallingConv();
2048   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2049       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2050 
2051   // Verify that the target's LowerReturn behaved as expected.
2052   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2053          "LowerReturn didn't return a valid chain!");
2054 
2055   // Update the DAG with the new chain value resulting from return lowering.
2056   DAG.setRoot(Chain);
2057 }
2058 
2059 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2060 /// created for it, emit nodes to copy the value into the virtual
2061 /// registers.
2062 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2063   // Skip empty types
2064   if (V->getType()->isEmptyTy())
2065     return;
2066 
2067   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2068   if (VMI != FuncInfo.ValueMap.end()) {
2069     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2070     CopyValueToVirtualRegister(V, VMI->second);
2071   }
2072 }
2073 
2074 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2075 /// the current basic block, add it to ValueMap now so that we'll get a
2076 /// CopyTo/FromReg.
2077 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2078   // No need to export constants.
2079   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2080 
2081   // Already exported?
2082   if (FuncInfo.isExportedInst(V)) return;
2083 
2084   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2085   CopyValueToVirtualRegister(V, Reg);
2086 }
2087 
2088 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2089                                                      const BasicBlock *FromBB) {
2090   // The operands of the setcc have to be in this block.  We don't know
2091   // how to export them from some other block.
2092   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2093     // Can export from current BB.
2094     if (VI->getParent() == FromBB)
2095       return true;
2096 
2097     // Is already exported, noop.
2098     return FuncInfo.isExportedInst(V);
2099   }
2100 
2101   // If this is an argument, we can export it if the BB is the entry block or
2102   // if it is already exported.
2103   if (isa<Argument>(V)) {
2104     if (FromBB->isEntryBlock())
2105       return true;
2106 
2107     // Otherwise, can only export this if it is already exported.
2108     return FuncInfo.isExportedInst(V);
2109   }
2110 
2111   // Otherwise, constants can always be exported.
2112   return true;
2113 }
2114 
2115 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2116 BranchProbability
2117 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2118                                         const MachineBasicBlock *Dst) const {
2119   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2120   const BasicBlock *SrcBB = Src->getBasicBlock();
2121   const BasicBlock *DstBB = Dst->getBasicBlock();
2122   if (!BPI) {
2123     // If BPI is not available, set the default probability as 1 / N, where N is
2124     // the number of successors.
2125     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2126     return BranchProbability(1, SuccSize);
2127   }
2128   return BPI->getEdgeProbability(SrcBB, DstBB);
2129 }
2130 
2131 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2132                                                MachineBasicBlock *Dst,
2133                                                BranchProbability Prob) {
2134   if (!FuncInfo.BPI)
2135     Src->addSuccessorWithoutProb(Dst);
2136   else {
2137     if (Prob.isUnknown())
2138       Prob = getEdgeProbability(Src, Dst);
2139     Src->addSuccessor(Dst, Prob);
2140   }
2141 }
2142 
2143 static bool InBlock(const Value *V, const BasicBlock *BB) {
2144   if (const Instruction *I = dyn_cast<Instruction>(V))
2145     return I->getParent() == BB;
2146   return true;
2147 }
2148 
2149 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2150 /// This function emits a branch and is used at the leaves of an OR or an
2151 /// AND operator tree.
2152 void
2153 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2154                                                   MachineBasicBlock *TBB,
2155                                                   MachineBasicBlock *FBB,
2156                                                   MachineBasicBlock *CurBB,
2157                                                   MachineBasicBlock *SwitchBB,
2158                                                   BranchProbability TProb,
2159                                                   BranchProbability FProb,
2160                                                   bool InvertCond) {
2161   const BasicBlock *BB = CurBB->getBasicBlock();
2162 
2163   // If the leaf of the tree is a comparison, merge the condition into
2164   // the caseblock.
2165   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2166     // The operands of the cmp have to be in this block.  We don't know
2167     // how to export them from some other block.  If this is the first block
2168     // of the sequence, no exporting is needed.
2169     if (CurBB == SwitchBB ||
2170         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2171          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2172       ISD::CondCode Condition;
2173       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2174         ICmpInst::Predicate Pred =
2175             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2176         Condition = getICmpCondCode(Pred);
2177       } else {
2178         const FCmpInst *FC = cast<FCmpInst>(Cond);
2179         FCmpInst::Predicate Pred =
2180             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2181         Condition = getFCmpCondCode(Pred);
2182         if (TM.Options.NoNaNsFPMath)
2183           Condition = getFCmpCodeWithoutNaN(Condition);
2184       }
2185 
2186       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2187                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2188       SL->SwitchCases.push_back(CB);
2189       return;
2190     }
2191   }
2192 
2193   // Create a CaseBlock record representing this branch.
2194   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2195   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2196                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2197   SL->SwitchCases.push_back(CB);
2198 }
2199 
2200 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2201                                                MachineBasicBlock *TBB,
2202                                                MachineBasicBlock *FBB,
2203                                                MachineBasicBlock *CurBB,
2204                                                MachineBasicBlock *SwitchBB,
2205                                                Instruction::BinaryOps Opc,
2206                                                BranchProbability TProb,
2207                                                BranchProbability FProb,
2208                                                bool InvertCond) {
2209   // Skip over not part of the tree and remember to invert op and operands at
2210   // next level.
2211   Value *NotCond;
2212   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2213       InBlock(NotCond, CurBB->getBasicBlock())) {
2214     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2215                          !InvertCond);
2216     return;
2217   }
2218 
2219   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2220   const Value *BOpOp0, *BOpOp1;
2221   // Compute the effective opcode for Cond, taking into account whether it needs
2222   // to be inverted, e.g.
2223   //   and (not (or A, B)), C
2224   // gets lowered as
2225   //   and (and (not A, not B), C)
2226   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2227   if (BOp) {
2228     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2229                ? Instruction::And
2230                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2231                       ? Instruction::Or
2232                       : (Instruction::BinaryOps)0);
2233     if (InvertCond) {
2234       if (BOpc == Instruction::And)
2235         BOpc = Instruction::Or;
2236       else if (BOpc == Instruction::Or)
2237         BOpc = Instruction::And;
2238     }
2239   }
2240 
2241   // If this node is not part of the or/and tree, emit it as a branch.
2242   // Note that all nodes in the tree should have same opcode.
2243   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2244   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2245       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2246       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2247     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2248                                  TProb, FProb, InvertCond);
2249     return;
2250   }
2251 
2252   //  Create TmpBB after CurBB.
2253   MachineFunction::iterator BBI(CurBB);
2254   MachineFunction &MF = DAG.getMachineFunction();
2255   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2256   CurBB->getParent()->insert(++BBI, TmpBB);
2257 
2258   if (Opc == Instruction::Or) {
2259     // Codegen X | Y as:
2260     // BB1:
2261     //   jmp_if_X TBB
2262     //   jmp TmpBB
2263     // TmpBB:
2264     //   jmp_if_Y TBB
2265     //   jmp FBB
2266     //
2267 
2268     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2269     // The requirement is that
2270     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2271     //     = TrueProb for original BB.
2272     // Assuming the original probabilities are A and B, one choice is to set
2273     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2274     // A/(1+B) and 2B/(1+B). This choice assumes that
2275     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2276     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2277     // TmpBB, but the math is more complicated.
2278 
2279     auto NewTrueProb = TProb / 2;
2280     auto NewFalseProb = TProb / 2 + FProb;
2281     // Emit the LHS condition.
2282     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2283                          NewFalseProb, InvertCond);
2284 
2285     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2286     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2287     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2288     // Emit the RHS condition into TmpBB.
2289     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2290                          Probs[1], InvertCond);
2291   } else {
2292     assert(Opc == Instruction::And && "Unknown merge op!");
2293     // Codegen X & Y as:
2294     // BB1:
2295     //   jmp_if_X TmpBB
2296     //   jmp FBB
2297     // TmpBB:
2298     //   jmp_if_Y TBB
2299     //   jmp FBB
2300     //
2301     //  This requires creation of TmpBB after CurBB.
2302 
2303     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2304     // The requirement is that
2305     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2306     //     = FalseProb for original BB.
2307     // Assuming the original probabilities are A and B, one choice is to set
2308     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2309     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2310     // TrueProb for BB1 * FalseProb for TmpBB.
2311 
2312     auto NewTrueProb = TProb + FProb / 2;
2313     auto NewFalseProb = FProb / 2;
2314     // Emit the LHS condition.
2315     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2316                          NewFalseProb, InvertCond);
2317 
2318     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2319     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2320     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2321     // Emit the RHS condition into TmpBB.
2322     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2323                          Probs[1], InvertCond);
2324   }
2325 }
2326 
2327 /// If the set of cases should be emitted as a series of branches, return true.
2328 /// If we should emit this as a bunch of and/or'd together conditions, return
2329 /// false.
2330 bool
2331 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2332   if (Cases.size() != 2) return true;
2333 
2334   // If this is two comparisons of the same values or'd or and'd together, they
2335   // will get folded into a single comparison, so don't emit two blocks.
2336   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2337        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2338       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2339        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2340     return false;
2341   }
2342 
2343   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2344   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2345   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2346       Cases[0].CC == Cases[1].CC &&
2347       isa<Constant>(Cases[0].CmpRHS) &&
2348       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2349     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2350       return false;
2351     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2352       return false;
2353   }
2354 
2355   return true;
2356 }
2357 
2358 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2359   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2360 
2361   // Update machine-CFG edges.
2362   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2363 
2364   if (I.isUnconditional()) {
2365     // Update machine-CFG edges.
2366     BrMBB->addSuccessor(Succ0MBB);
2367 
2368     // If this is not a fall-through branch or optimizations are switched off,
2369     // emit the branch.
2370     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2371       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2372                               MVT::Other, getControlRoot(),
2373                               DAG.getBasicBlock(Succ0MBB)));
2374 
2375     return;
2376   }
2377 
2378   // If this condition is one of the special cases we handle, do special stuff
2379   // now.
2380   const Value *CondVal = I.getCondition();
2381   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2382 
2383   // If this is a series of conditions that are or'd or and'd together, emit
2384   // this as a sequence of branches instead of setcc's with and/or operations.
2385   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2386   // unpredictable branches, and vector extracts because those jumps are likely
2387   // expensive for any target), this should improve performance.
2388   // For example, instead of something like:
2389   //     cmp A, B
2390   //     C = seteq
2391   //     cmp D, E
2392   //     F = setle
2393   //     or C, F
2394   //     jnz foo
2395   // Emit:
2396   //     cmp A, B
2397   //     je foo
2398   //     cmp D, E
2399   //     jle foo
2400   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2401   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2402       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2403     Value *Vec;
2404     const Value *BOp0, *BOp1;
2405     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2406     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2407       Opcode = Instruction::And;
2408     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2409       Opcode = Instruction::Or;
2410 
2411     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2412                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2413       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2414                            getEdgeProbability(BrMBB, Succ0MBB),
2415                            getEdgeProbability(BrMBB, Succ1MBB),
2416                            /*InvertCond=*/false);
2417       // If the compares in later blocks need to use values not currently
2418       // exported from this block, export them now.  This block should always
2419       // be the first entry.
2420       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2421 
2422       // Allow some cases to be rejected.
2423       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2424         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2425           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2426           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2427         }
2428 
2429         // Emit the branch for this block.
2430         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2431         SL->SwitchCases.erase(SL->SwitchCases.begin());
2432         return;
2433       }
2434 
2435       // Okay, we decided not to do this, remove any inserted MBB's and clear
2436       // SwitchCases.
2437       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2438         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2439 
2440       SL->SwitchCases.clear();
2441     }
2442   }
2443 
2444   // Create a CaseBlock record representing this branch.
2445   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2446                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2447 
2448   // Use visitSwitchCase to actually insert the fast branch sequence for this
2449   // cond branch.
2450   visitSwitchCase(CB, BrMBB);
2451 }
2452 
2453 /// visitSwitchCase - Emits the necessary code to represent a single node in
2454 /// the binary search tree resulting from lowering a switch instruction.
2455 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2456                                           MachineBasicBlock *SwitchBB) {
2457   SDValue Cond;
2458   SDValue CondLHS = getValue(CB.CmpLHS);
2459   SDLoc dl = CB.DL;
2460 
2461   if (CB.CC == ISD::SETTRUE) {
2462     // Branch or fall through to TrueBB.
2463     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2464     SwitchBB->normalizeSuccProbs();
2465     if (CB.TrueBB != NextBlock(SwitchBB)) {
2466       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2467                               DAG.getBasicBlock(CB.TrueBB)));
2468     }
2469     return;
2470   }
2471 
2472   auto &TLI = DAG.getTargetLoweringInfo();
2473   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2474 
2475   // Build the setcc now.
2476   if (!CB.CmpMHS) {
2477     // Fold "(X == true)" to X and "(X == false)" to !X to
2478     // handle common cases produced by branch lowering.
2479     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2480         CB.CC == ISD::SETEQ)
2481       Cond = CondLHS;
2482     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2483              CB.CC == ISD::SETEQ) {
2484       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2485       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2486     } else {
2487       SDValue CondRHS = getValue(CB.CmpRHS);
2488 
2489       // If a pointer's DAG type is larger than its memory type then the DAG
2490       // values are zero-extended. This breaks signed comparisons so truncate
2491       // back to the underlying type before doing the compare.
2492       if (CondLHS.getValueType() != MemVT) {
2493         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2494         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2495       }
2496       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2497     }
2498   } else {
2499     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2500 
2501     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2502     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2503 
2504     SDValue CmpOp = getValue(CB.CmpMHS);
2505     EVT VT = CmpOp.getValueType();
2506 
2507     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2508       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2509                           ISD::SETLE);
2510     } else {
2511       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2512                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2513       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2514                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2515     }
2516   }
2517 
2518   // Update successor info
2519   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2520   // TrueBB and FalseBB are always different unless the incoming IR is
2521   // degenerate. This only happens when running llc on weird IR.
2522   if (CB.TrueBB != CB.FalseBB)
2523     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2524   SwitchBB->normalizeSuccProbs();
2525 
2526   // If the lhs block is the next block, invert the condition so that we can
2527   // fall through to the lhs instead of the rhs block.
2528   if (CB.TrueBB == NextBlock(SwitchBB)) {
2529     std::swap(CB.TrueBB, CB.FalseBB);
2530     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2531     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2532   }
2533 
2534   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2535                                MVT::Other, getControlRoot(), Cond,
2536                                DAG.getBasicBlock(CB.TrueBB));
2537 
2538   // Insert the false branch. Do this even if it's a fall through branch,
2539   // this makes it easier to do DAG optimizations which require inverting
2540   // the branch condition.
2541   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2542                        DAG.getBasicBlock(CB.FalseBB));
2543 
2544   DAG.setRoot(BrCond);
2545 }
2546 
2547 /// visitJumpTable - Emit JumpTable node in the current MBB
2548 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2549   // Emit the code for the jump table
2550   assert(JT.Reg != -1U && "Should lower JT Header first!");
2551   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2552   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2553                                      JT.Reg, PTy);
2554   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2555   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2556                                     MVT::Other, Index.getValue(1),
2557                                     Table, Index);
2558   DAG.setRoot(BrJumpTable);
2559 }
2560 
2561 /// visitJumpTableHeader - This function emits necessary code to produce index
2562 /// in the JumpTable from switch case.
2563 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2564                                                JumpTableHeader &JTH,
2565                                                MachineBasicBlock *SwitchBB) {
2566   SDLoc dl = getCurSDLoc();
2567 
2568   // Subtract the lowest switch case value from the value being switched on.
2569   SDValue SwitchOp = getValue(JTH.SValue);
2570   EVT VT = SwitchOp.getValueType();
2571   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2572                             DAG.getConstant(JTH.First, dl, VT));
2573 
2574   // The SDNode we just created, which holds the value being switched on minus
2575   // the smallest case value, needs to be copied to a virtual register so it
2576   // can be used as an index into the jump table in a subsequent basic block.
2577   // This value may be smaller or larger than the target's pointer type, and
2578   // therefore require extension or truncating.
2579   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2580   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2581 
2582   unsigned JumpTableReg =
2583       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2584   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2585                                     JumpTableReg, SwitchOp);
2586   JT.Reg = JumpTableReg;
2587 
2588   if (!JTH.FallthroughUnreachable) {
2589     // Emit the range check for the jump table, and branch to the default block
2590     // for the switch statement if the value being switched on exceeds the
2591     // largest case in the switch.
2592     SDValue CMP = DAG.getSetCC(
2593         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2594                                    Sub.getValueType()),
2595         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2596 
2597     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2598                                  MVT::Other, CopyTo, CMP,
2599                                  DAG.getBasicBlock(JT.Default));
2600 
2601     // Avoid emitting unnecessary branches to the next block.
2602     if (JT.MBB != NextBlock(SwitchBB))
2603       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2604                            DAG.getBasicBlock(JT.MBB));
2605 
2606     DAG.setRoot(BrCond);
2607   } else {
2608     // Avoid emitting unnecessary branches to the next block.
2609     if (JT.MBB != NextBlock(SwitchBB))
2610       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2611                               DAG.getBasicBlock(JT.MBB)));
2612     else
2613       DAG.setRoot(CopyTo);
2614   }
2615 }
2616 
2617 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2618 /// variable if there exists one.
2619 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2620                                  SDValue &Chain) {
2621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2622   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2623   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2624   MachineFunction &MF = DAG.getMachineFunction();
2625   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2626   MachineSDNode *Node =
2627       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2628   if (Global) {
2629     MachinePointerInfo MPInfo(Global);
2630     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2631                  MachineMemOperand::MODereferenceable;
2632     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2633         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2634     DAG.setNodeMemRefs(Node, {MemRef});
2635   }
2636   if (PtrTy != PtrMemTy)
2637     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2638   return SDValue(Node, 0);
2639 }
2640 
2641 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2642 /// tail spliced into a stack protector check success bb.
2643 ///
2644 /// For a high level explanation of how this fits into the stack protector
2645 /// generation see the comment on the declaration of class
2646 /// StackProtectorDescriptor.
2647 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2648                                                   MachineBasicBlock *ParentBB) {
2649 
2650   // First create the loads to the guard/stack slot for the comparison.
2651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2652   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2653   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2654 
2655   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2656   int FI = MFI.getStackProtectorIndex();
2657 
2658   SDValue Guard;
2659   SDLoc dl = getCurSDLoc();
2660   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2661   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2662   Align Align =
2663       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2664 
2665   // Generate code to load the content of the guard slot.
2666   SDValue GuardVal = DAG.getLoad(
2667       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2668       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2669       MachineMemOperand::MOVolatile);
2670 
2671   if (TLI.useStackGuardXorFP())
2672     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2673 
2674   // Retrieve guard check function, nullptr if instrumentation is inlined.
2675   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2676     // The target provides a guard check function to validate the guard value.
2677     // Generate a call to that function with the content of the guard slot as
2678     // argument.
2679     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2680     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2681 
2682     TargetLowering::ArgListTy Args;
2683     TargetLowering::ArgListEntry Entry;
2684     Entry.Node = GuardVal;
2685     Entry.Ty = FnTy->getParamType(0);
2686     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2687       Entry.IsInReg = true;
2688     Args.push_back(Entry);
2689 
2690     TargetLowering::CallLoweringInfo CLI(DAG);
2691     CLI.setDebugLoc(getCurSDLoc())
2692         .setChain(DAG.getEntryNode())
2693         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2694                    getValue(GuardCheckFn), std::move(Args));
2695 
2696     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2697     DAG.setRoot(Result.second);
2698     return;
2699   }
2700 
2701   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2702   // Otherwise, emit a volatile load to retrieve the stack guard value.
2703   SDValue Chain = DAG.getEntryNode();
2704   if (TLI.useLoadStackGuardNode()) {
2705     Guard = getLoadStackGuard(DAG, dl, Chain);
2706   } else {
2707     const Value *IRGuard = TLI.getSDagStackGuard(M);
2708     SDValue GuardPtr = getValue(IRGuard);
2709 
2710     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2711                         MachinePointerInfo(IRGuard, 0), Align,
2712                         MachineMemOperand::MOVolatile);
2713   }
2714 
2715   // Perform the comparison via a getsetcc.
2716   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2717                                                         *DAG.getContext(),
2718                                                         Guard.getValueType()),
2719                              Guard, GuardVal, ISD::SETNE);
2720 
2721   // If the guard/stackslot do not equal, branch to failure MBB.
2722   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2723                                MVT::Other, GuardVal.getOperand(0),
2724                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2725   // Otherwise branch to success MBB.
2726   SDValue Br = DAG.getNode(ISD::BR, dl,
2727                            MVT::Other, BrCond,
2728                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2729 
2730   DAG.setRoot(Br);
2731 }
2732 
2733 /// Codegen the failure basic block for a stack protector check.
2734 ///
2735 /// A failure stack protector machine basic block consists simply of a call to
2736 /// __stack_chk_fail().
2737 ///
2738 /// For a high level explanation of how this fits into the stack protector
2739 /// generation see the comment on the declaration of class
2740 /// StackProtectorDescriptor.
2741 void
2742 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2743   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2744   TargetLowering::MakeLibCallOptions CallOptions;
2745   CallOptions.setDiscardResult(true);
2746   SDValue Chain =
2747       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2748                       None, CallOptions, getCurSDLoc()).second;
2749   // On PS4, the "return address" must still be within the calling function,
2750   // even if it's at the very end, so emit an explicit TRAP here.
2751   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2752   if (TM.getTargetTriple().isPS4CPU())
2753     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2754   // WebAssembly needs an unreachable instruction after a non-returning call,
2755   // because the function return type can be different from __stack_chk_fail's
2756   // return type (void).
2757   if (TM.getTargetTriple().isWasm())
2758     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2759 
2760   DAG.setRoot(Chain);
2761 }
2762 
2763 /// visitBitTestHeader - This function emits necessary code to produce value
2764 /// suitable for "bit tests"
2765 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2766                                              MachineBasicBlock *SwitchBB) {
2767   SDLoc dl = getCurSDLoc();
2768 
2769   // Subtract the minimum value.
2770   SDValue SwitchOp = getValue(B.SValue);
2771   EVT VT = SwitchOp.getValueType();
2772   SDValue RangeSub =
2773       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2774 
2775   // Determine the type of the test operands.
2776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2777   bool UsePtrType = false;
2778   if (!TLI.isTypeLegal(VT)) {
2779     UsePtrType = true;
2780   } else {
2781     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2782       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2783         // Switch table case range are encoded into series of masks.
2784         // Just use pointer type, it's guaranteed to fit.
2785         UsePtrType = true;
2786         break;
2787       }
2788   }
2789   SDValue Sub = RangeSub;
2790   if (UsePtrType) {
2791     VT = TLI.getPointerTy(DAG.getDataLayout());
2792     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2793   }
2794 
2795   B.RegVT = VT.getSimpleVT();
2796   B.Reg = FuncInfo.CreateReg(B.RegVT);
2797   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2798 
2799   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2800 
2801   if (!B.FallthroughUnreachable)
2802     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2803   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2804   SwitchBB->normalizeSuccProbs();
2805 
2806   SDValue Root = CopyTo;
2807   if (!B.FallthroughUnreachable) {
2808     // Conditional branch to the default block.
2809     SDValue RangeCmp = DAG.getSetCC(dl,
2810         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2811                                RangeSub.getValueType()),
2812         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2813         ISD::SETUGT);
2814 
2815     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2816                        DAG.getBasicBlock(B.Default));
2817   }
2818 
2819   // Avoid emitting unnecessary branches to the next block.
2820   if (MBB != NextBlock(SwitchBB))
2821     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2822 
2823   DAG.setRoot(Root);
2824 }
2825 
2826 /// visitBitTestCase - this function produces one "bit test"
2827 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2828                                            MachineBasicBlock* NextMBB,
2829                                            BranchProbability BranchProbToNext,
2830                                            unsigned Reg,
2831                                            BitTestCase &B,
2832                                            MachineBasicBlock *SwitchBB) {
2833   SDLoc dl = getCurSDLoc();
2834   MVT VT = BB.RegVT;
2835   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2836   SDValue Cmp;
2837   unsigned PopCount = countPopulation(B.Mask);
2838   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2839   if (PopCount == 1) {
2840     // Testing for a single bit; just compare the shift count with what it
2841     // would need to be to shift a 1 bit in that position.
2842     Cmp = DAG.getSetCC(
2843         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2844         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2845         ISD::SETEQ);
2846   } else if (PopCount == BB.Range) {
2847     // There is only one zero bit in the range, test for it directly.
2848     Cmp = DAG.getSetCC(
2849         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2850         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2851         ISD::SETNE);
2852   } else {
2853     // Make desired shift
2854     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2855                                     DAG.getConstant(1, dl, VT), ShiftOp);
2856 
2857     // Emit bit tests and jumps
2858     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2859                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2860     Cmp = DAG.getSetCC(
2861         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2862         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2863   }
2864 
2865   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2866   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2867   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2868   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2869   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2870   // one as they are relative probabilities (and thus work more like weights),
2871   // and hence we need to normalize them to let the sum of them become one.
2872   SwitchBB->normalizeSuccProbs();
2873 
2874   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2875                               MVT::Other, getControlRoot(),
2876                               Cmp, DAG.getBasicBlock(B.TargetBB));
2877 
2878   // Avoid emitting unnecessary branches to the next block.
2879   if (NextMBB != NextBlock(SwitchBB))
2880     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2881                         DAG.getBasicBlock(NextMBB));
2882 
2883   DAG.setRoot(BrAnd);
2884 }
2885 
2886 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2887   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2888 
2889   // Retrieve successors. Look through artificial IR level blocks like
2890   // catchswitch for successors.
2891   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2892   const BasicBlock *EHPadBB = I.getSuccessor(1);
2893 
2894   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2895   // have to do anything here to lower funclet bundles.
2896   assert(!I.hasOperandBundlesOtherThan(
2897              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2898               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2899               LLVMContext::OB_cfguardtarget,
2900               LLVMContext::OB_clang_arc_attachedcall}) &&
2901          "Cannot lower invokes with arbitrary operand bundles yet!");
2902 
2903   const Value *Callee(I.getCalledOperand());
2904   const Function *Fn = dyn_cast<Function>(Callee);
2905   if (isa<InlineAsm>(Callee))
2906     visitInlineAsm(I, EHPadBB);
2907   else if (Fn && Fn->isIntrinsic()) {
2908     switch (Fn->getIntrinsicID()) {
2909     default:
2910       llvm_unreachable("Cannot invoke this intrinsic");
2911     case Intrinsic::donothing:
2912       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2913     case Intrinsic::seh_try_begin:
2914     case Intrinsic::seh_scope_begin:
2915     case Intrinsic::seh_try_end:
2916     case Intrinsic::seh_scope_end:
2917       break;
2918     case Intrinsic::experimental_patchpoint_void:
2919     case Intrinsic::experimental_patchpoint_i64:
2920       visitPatchpoint(I, EHPadBB);
2921       break;
2922     case Intrinsic::experimental_gc_statepoint:
2923       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2924       break;
2925     case Intrinsic::wasm_rethrow: {
2926       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2927       // special because it can be invoked, so we manually lower it to a DAG
2928       // node here.
2929       SmallVector<SDValue, 8> Ops;
2930       Ops.push_back(getRoot()); // inchain
2931       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2932       Ops.push_back(
2933           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2934                                 TLI.getPointerTy(DAG.getDataLayout())));
2935       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2936       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2937       break;
2938     }
2939     }
2940   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2941     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2942     // Eventually we will support lowering the @llvm.experimental.deoptimize
2943     // intrinsic, and right now there are no plans to support other intrinsics
2944     // with deopt state.
2945     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2946   } else {
2947     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2948   }
2949 
2950   // If the value of the invoke is used outside of its defining block, make it
2951   // available as a virtual register.
2952   // We already took care of the exported value for the statepoint instruction
2953   // during call to the LowerStatepoint.
2954   if (!isa<GCStatepointInst>(I)) {
2955     CopyToExportRegsIfNeeded(&I);
2956   }
2957 
2958   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2959   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2960   BranchProbability EHPadBBProb =
2961       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2962           : BranchProbability::getZero();
2963   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2964 
2965   // Update successor info.
2966   addSuccessorWithProb(InvokeMBB, Return);
2967   for (auto &UnwindDest : UnwindDests) {
2968     UnwindDest.first->setIsEHPad();
2969     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2970   }
2971   InvokeMBB->normalizeSuccProbs();
2972 
2973   // Drop into normal successor.
2974   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2975                           DAG.getBasicBlock(Return)));
2976 }
2977 
2978 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2979   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2980 
2981   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2982   // have to do anything here to lower funclet bundles.
2983   assert(!I.hasOperandBundlesOtherThan(
2984              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2985          "Cannot lower callbrs with arbitrary operand bundles yet!");
2986 
2987   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2988   visitInlineAsm(I);
2989   CopyToExportRegsIfNeeded(&I);
2990 
2991   // Retrieve successors.
2992   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2993 
2994   // Update successor info.
2995   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2996   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2997     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2998     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2999     Target->setIsInlineAsmBrIndirectTarget();
3000   }
3001   CallBrMBB->normalizeSuccProbs();
3002 
3003   // Drop into default successor.
3004   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3005                           MVT::Other, getControlRoot(),
3006                           DAG.getBasicBlock(Return)));
3007 }
3008 
3009 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3010   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3011 }
3012 
3013 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3014   assert(FuncInfo.MBB->isEHPad() &&
3015          "Call to landingpad not in landing pad!");
3016 
3017   // If there aren't registers to copy the values into (e.g., during SjLj
3018   // exceptions), then don't bother to create these DAG nodes.
3019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3020   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3021   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3022       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3023     return;
3024 
3025   // If landingpad's return type is token type, we don't create DAG nodes
3026   // for its exception pointer and selector value. The extraction of exception
3027   // pointer or selector value from token type landingpads is not currently
3028   // supported.
3029   if (LP.getType()->isTokenTy())
3030     return;
3031 
3032   SmallVector<EVT, 2> ValueVTs;
3033   SDLoc dl = getCurSDLoc();
3034   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3035   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3036 
3037   // Get the two live-in registers as SDValues. The physregs have already been
3038   // copied into virtual registers.
3039   SDValue Ops[2];
3040   if (FuncInfo.ExceptionPointerVirtReg) {
3041     Ops[0] = DAG.getZExtOrTrunc(
3042         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3043                            FuncInfo.ExceptionPointerVirtReg,
3044                            TLI.getPointerTy(DAG.getDataLayout())),
3045         dl, ValueVTs[0]);
3046   } else {
3047     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3048   }
3049   Ops[1] = DAG.getZExtOrTrunc(
3050       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3051                          FuncInfo.ExceptionSelectorVirtReg,
3052                          TLI.getPointerTy(DAG.getDataLayout())),
3053       dl, ValueVTs[1]);
3054 
3055   // Merge into one.
3056   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3057                             DAG.getVTList(ValueVTs), Ops);
3058   setValue(&LP, Res);
3059 }
3060 
3061 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3062                                            MachineBasicBlock *Last) {
3063   // Update JTCases.
3064   for (JumpTableBlock &JTB : SL->JTCases)
3065     if (JTB.first.HeaderBB == First)
3066       JTB.first.HeaderBB = Last;
3067 
3068   // Update BitTestCases.
3069   for (BitTestBlock &BTB : SL->BitTestCases)
3070     if (BTB.Parent == First)
3071       BTB.Parent = Last;
3072 }
3073 
3074 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3075   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3076 
3077   // Update machine-CFG edges with unique successors.
3078   SmallSet<BasicBlock*, 32> Done;
3079   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3080     BasicBlock *BB = I.getSuccessor(i);
3081     bool Inserted = Done.insert(BB).second;
3082     if (!Inserted)
3083         continue;
3084 
3085     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3086     addSuccessorWithProb(IndirectBrMBB, Succ);
3087   }
3088   IndirectBrMBB->normalizeSuccProbs();
3089 
3090   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3091                           MVT::Other, getControlRoot(),
3092                           getValue(I.getAddress())));
3093 }
3094 
3095 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3096   if (!DAG.getTarget().Options.TrapUnreachable)
3097     return;
3098 
3099   // We may be able to ignore unreachable behind a noreturn call.
3100   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3101     const BasicBlock &BB = *I.getParent();
3102     if (&I != &BB.front()) {
3103       BasicBlock::const_iterator PredI =
3104         std::prev(BasicBlock::const_iterator(&I));
3105       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3106         if (Call->doesNotReturn())
3107           return;
3108       }
3109     }
3110   }
3111 
3112   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3113 }
3114 
3115 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3116   SDNodeFlags Flags;
3117   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3118     Flags.copyFMF(*FPOp);
3119 
3120   SDValue Op = getValue(I.getOperand(0));
3121   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3122                                     Op, Flags);
3123   setValue(&I, UnNodeValue);
3124 }
3125 
3126 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3127   SDNodeFlags Flags;
3128   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3129     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3130     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3131   }
3132   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3133     Flags.setExact(ExactOp->isExact());
3134   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3135     Flags.copyFMF(*FPOp);
3136 
3137   SDValue Op1 = getValue(I.getOperand(0));
3138   SDValue Op2 = getValue(I.getOperand(1));
3139   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3140                                      Op1, Op2, Flags);
3141   setValue(&I, BinNodeValue);
3142 }
3143 
3144 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3145   SDValue Op1 = getValue(I.getOperand(0));
3146   SDValue Op2 = getValue(I.getOperand(1));
3147 
3148   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3149       Op1.getValueType(), DAG.getDataLayout());
3150 
3151   // Coerce the shift amount to the right type if we can.
3152   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3153     unsigned ShiftSize = ShiftTy.getSizeInBits();
3154     unsigned Op2Size = Op2.getValueSizeInBits();
3155     SDLoc DL = getCurSDLoc();
3156 
3157     // If the operand is smaller than the shift count type, promote it.
3158     if (ShiftSize > Op2Size)
3159       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3160 
3161     // If the operand is larger than the shift count type but the shift
3162     // count type has enough bits to represent any shift value, truncate
3163     // it now. This is a common case and it exposes the truncate to
3164     // optimization early.
3165     else if (ShiftSize >= Log2_32_Ceil(Op1.getValueSizeInBits()))
3166       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3167     // Otherwise we'll need to temporarily settle for some other convenient
3168     // type.  Type legalization will make adjustments once the shiftee is split.
3169     else
3170       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3171   }
3172 
3173   bool nuw = false;
3174   bool nsw = false;
3175   bool exact = false;
3176 
3177   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3178 
3179     if (const OverflowingBinaryOperator *OFBinOp =
3180             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3181       nuw = OFBinOp->hasNoUnsignedWrap();
3182       nsw = OFBinOp->hasNoSignedWrap();
3183     }
3184     if (const PossiblyExactOperator *ExactOp =
3185             dyn_cast<const PossiblyExactOperator>(&I))
3186       exact = ExactOp->isExact();
3187   }
3188   SDNodeFlags Flags;
3189   Flags.setExact(exact);
3190   Flags.setNoSignedWrap(nsw);
3191   Flags.setNoUnsignedWrap(nuw);
3192   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3193                             Flags);
3194   setValue(&I, Res);
3195 }
3196 
3197 void SelectionDAGBuilder::visitSDiv(const User &I) {
3198   SDValue Op1 = getValue(I.getOperand(0));
3199   SDValue Op2 = getValue(I.getOperand(1));
3200 
3201   SDNodeFlags Flags;
3202   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3203                  cast<PossiblyExactOperator>(&I)->isExact());
3204   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3205                            Op2, Flags));
3206 }
3207 
3208 void SelectionDAGBuilder::visitICmp(const User &I) {
3209   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3210   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3211     predicate = IC->getPredicate();
3212   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3213     predicate = ICmpInst::Predicate(IC->getPredicate());
3214   SDValue Op1 = getValue(I.getOperand(0));
3215   SDValue Op2 = getValue(I.getOperand(1));
3216   ISD::CondCode Opcode = getICmpCondCode(predicate);
3217 
3218   auto &TLI = DAG.getTargetLoweringInfo();
3219   EVT MemVT =
3220       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3221 
3222   // If a pointer's DAG type is larger than its memory type then the DAG values
3223   // are zero-extended. This breaks signed comparisons so truncate back to the
3224   // underlying type before doing the compare.
3225   if (Op1.getValueType() != MemVT) {
3226     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3227     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3228   }
3229 
3230   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3231                                                         I.getType());
3232   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3233 }
3234 
3235 void SelectionDAGBuilder::visitFCmp(const User &I) {
3236   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3237   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3238     predicate = FC->getPredicate();
3239   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3240     predicate = FCmpInst::Predicate(FC->getPredicate());
3241   SDValue Op1 = getValue(I.getOperand(0));
3242   SDValue Op2 = getValue(I.getOperand(1));
3243 
3244   ISD::CondCode Condition = getFCmpCondCode(predicate);
3245   auto *FPMO = cast<FPMathOperator>(&I);
3246   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3247     Condition = getFCmpCodeWithoutNaN(Condition);
3248 
3249   SDNodeFlags Flags;
3250   Flags.copyFMF(*FPMO);
3251   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3252 
3253   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3254                                                         I.getType());
3255   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3256 }
3257 
3258 // Check if the condition of the select has one use or two users that are both
3259 // selects with the same condition.
3260 static bool hasOnlySelectUsers(const Value *Cond) {
3261   return llvm::all_of(Cond->users(), [](const Value *V) {
3262     return isa<SelectInst>(V);
3263   });
3264 }
3265 
3266 void SelectionDAGBuilder::visitSelect(const User &I) {
3267   SmallVector<EVT, 4> ValueVTs;
3268   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3269                   ValueVTs);
3270   unsigned NumValues = ValueVTs.size();
3271   if (NumValues == 0) return;
3272 
3273   SmallVector<SDValue, 4> Values(NumValues);
3274   SDValue Cond     = getValue(I.getOperand(0));
3275   SDValue LHSVal   = getValue(I.getOperand(1));
3276   SDValue RHSVal   = getValue(I.getOperand(2));
3277   SmallVector<SDValue, 1> BaseOps(1, Cond);
3278   ISD::NodeType OpCode =
3279       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3280 
3281   bool IsUnaryAbs = false;
3282   bool Negate = false;
3283 
3284   SDNodeFlags Flags;
3285   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3286     Flags.copyFMF(*FPOp);
3287 
3288   // Min/max matching is only viable if all output VTs are the same.
3289   if (is_splat(ValueVTs)) {
3290     EVT VT = ValueVTs[0];
3291     LLVMContext &Ctx = *DAG.getContext();
3292     auto &TLI = DAG.getTargetLoweringInfo();
3293 
3294     // We care about the legality of the operation after it has been type
3295     // legalized.
3296     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3297       VT = TLI.getTypeToTransformTo(Ctx, VT);
3298 
3299     // If the vselect is legal, assume we want to leave this as a vector setcc +
3300     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3301     // min/max is legal on the scalar type.
3302     bool UseScalarMinMax = VT.isVector() &&
3303       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3304 
3305     Value *LHS, *RHS;
3306     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3307     ISD::NodeType Opc = ISD::DELETED_NODE;
3308     switch (SPR.Flavor) {
3309     case SPF_UMAX:    Opc = ISD::UMAX; break;
3310     case SPF_UMIN:    Opc = ISD::UMIN; break;
3311     case SPF_SMAX:    Opc = ISD::SMAX; break;
3312     case SPF_SMIN:    Opc = ISD::SMIN; break;
3313     case SPF_FMINNUM:
3314       switch (SPR.NaNBehavior) {
3315       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3316       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3317       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3318       case SPNB_RETURNS_ANY: {
3319         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3320           Opc = ISD::FMINNUM;
3321         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3322           Opc = ISD::FMINIMUM;
3323         else if (UseScalarMinMax)
3324           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3325             ISD::FMINNUM : ISD::FMINIMUM;
3326         break;
3327       }
3328       }
3329       break;
3330     case SPF_FMAXNUM:
3331       switch (SPR.NaNBehavior) {
3332       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3333       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3334       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3335       case SPNB_RETURNS_ANY:
3336 
3337         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3338           Opc = ISD::FMAXNUM;
3339         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3340           Opc = ISD::FMAXIMUM;
3341         else if (UseScalarMinMax)
3342           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3343             ISD::FMAXNUM : ISD::FMAXIMUM;
3344         break;
3345       }
3346       break;
3347     case SPF_NABS:
3348       Negate = true;
3349       LLVM_FALLTHROUGH;
3350     case SPF_ABS:
3351       IsUnaryAbs = true;
3352       Opc = ISD::ABS;
3353       break;
3354     default: break;
3355     }
3356 
3357     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3358         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3359          (UseScalarMinMax &&
3360           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3361         // If the underlying comparison instruction is used by any other
3362         // instruction, the consumed instructions won't be destroyed, so it is
3363         // not profitable to convert to a min/max.
3364         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3365       OpCode = Opc;
3366       LHSVal = getValue(LHS);
3367       RHSVal = getValue(RHS);
3368       BaseOps.clear();
3369     }
3370 
3371     if (IsUnaryAbs) {
3372       OpCode = Opc;
3373       LHSVal = getValue(LHS);
3374       BaseOps.clear();
3375     }
3376   }
3377 
3378   if (IsUnaryAbs) {
3379     for (unsigned i = 0; i != NumValues; ++i) {
3380       SDLoc dl = getCurSDLoc();
3381       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3382       Values[i] =
3383           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3384       if (Negate)
3385         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3386                                 Values[i]);
3387     }
3388   } else {
3389     for (unsigned i = 0; i != NumValues; ++i) {
3390       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3391       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3392       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3393       Values[i] = DAG.getNode(
3394           OpCode, getCurSDLoc(),
3395           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3396     }
3397   }
3398 
3399   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3400                            DAG.getVTList(ValueVTs), Values));
3401 }
3402 
3403 void SelectionDAGBuilder::visitTrunc(const User &I) {
3404   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3405   SDValue N = getValue(I.getOperand(0));
3406   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3407                                                         I.getType());
3408   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3409 }
3410 
3411 void SelectionDAGBuilder::visitZExt(const User &I) {
3412   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3413   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3414   SDValue N = getValue(I.getOperand(0));
3415   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3416                                                         I.getType());
3417   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3418 }
3419 
3420 void SelectionDAGBuilder::visitSExt(const User &I) {
3421   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3422   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3423   SDValue N = getValue(I.getOperand(0));
3424   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3425                                                         I.getType());
3426   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3427 }
3428 
3429 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3430   // FPTrunc is never a no-op cast, no need to check
3431   SDValue N = getValue(I.getOperand(0));
3432   SDLoc dl = getCurSDLoc();
3433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3434   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3435   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3436                            DAG.getTargetConstant(
3437                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3438 }
3439 
3440 void SelectionDAGBuilder::visitFPExt(const User &I) {
3441   // FPExt 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_EXTEND, getCurSDLoc(), DestVT, N));
3446 }
3447 
3448 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3449   // FPToUI 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::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3454 }
3455 
3456 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3457   // FPToSI 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::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3462 }
3463 
3464 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3465   // UIToFP is never a no-op cast, no need to check
3466   SDValue N = getValue(I.getOperand(0));
3467   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3468                                                         I.getType());
3469   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3470 }
3471 
3472 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3473   // SIToFP is never a no-op cast, no need to check
3474   SDValue N = getValue(I.getOperand(0));
3475   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3476                                                         I.getType());
3477   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3478 }
3479 
3480 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3481   // What to do depends on the size of the integer and the size of the pointer.
3482   // We can either truncate, zero extend, or no-op, accordingly.
3483   SDValue N = getValue(I.getOperand(0));
3484   auto &TLI = DAG.getTargetLoweringInfo();
3485   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3486                                                         I.getType());
3487   EVT PtrMemVT =
3488       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3489   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3490   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3491   setValue(&I, N);
3492 }
3493 
3494 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3495   // What to do depends on the size of the integer and the size of the pointer.
3496   // We can either truncate, zero extend, or no-op, accordingly.
3497   SDValue N = getValue(I.getOperand(0));
3498   auto &TLI = DAG.getTargetLoweringInfo();
3499   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3500   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3501   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3502   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3503   setValue(&I, N);
3504 }
3505 
3506 void SelectionDAGBuilder::visitBitCast(const User &I) {
3507   SDValue N = getValue(I.getOperand(0));
3508   SDLoc dl = getCurSDLoc();
3509   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3510                                                         I.getType());
3511 
3512   // BitCast assures us that source and destination are the same size so this is
3513   // either a BITCAST or a no-op.
3514   if (DestVT != N.getValueType())
3515     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3516                              DestVT, N)); // convert types.
3517   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3518   // might fold any kind of constant expression to an integer constant and that
3519   // is not what we are looking for. Only recognize a bitcast of a genuine
3520   // constant integer as an opaque constant.
3521   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3522     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3523                                  /*isOpaque*/true));
3524   else
3525     setValue(&I, N);            // noop cast.
3526 }
3527 
3528 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3530   const Value *SV = I.getOperand(0);
3531   SDValue N = getValue(SV);
3532   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3533 
3534   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3535   unsigned DestAS = I.getType()->getPointerAddressSpace();
3536 
3537   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3538     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3539 
3540   setValue(&I, N);
3541 }
3542 
3543 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3545   SDValue InVec = getValue(I.getOperand(0));
3546   SDValue InVal = getValue(I.getOperand(1));
3547   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3548                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3549   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3550                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3551                            InVec, InVal, InIdx));
3552 }
3553 
3554 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3556   SDValue InVec = getValue(I.getOperand(0));
3557   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3558                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3559   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3560                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3561                            InVec, InIdx));
3562 }
3563 
3564 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3565   SDValue Src1 = getValue(I.getOperand(0));
3566   SDValue Src2 = getValue(I.getOperand(1));
3567   ArrayRef<int> Mask;
3568   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3569     Mask = SVI->getShuffleMask();
3570   else
3571     Mask = cast<ConstantExpr>(I).getShuffleMask();
3572   SDLoc DL = getCurSDLoc();
3573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3574   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3575   EVT SrcVT = Src1.getValueType();
3576 
3577   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3578       VT.isScalableVector()) {
3579     // Canonical splat form of first element of first input vector.
3580     SDValue FirstElt =
3581         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3582                     DAG.getVectorIdxConstant(0, DL));
3583     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3584     return;
3585   }
3586 
3587   // For now, we only handle splats for scalable vectors.
3588   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3589   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3590   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3591 
3592   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3593   unsigned MaskNumElts = Mask.size();
3594 
3595   if (SrcNumElts == MaskNumElts) {
3596     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3597     return;
3598   }
3599 
3600   // Normalize the shuffle vector since mask and vector length don't match.
3601   if (SrcNumElts < MaskNumElts) {
3602     // Mask is longer than the source vectors. We can use concatenate vector to
3603     // make the mask and vectors lengths match.
3604 
3605     if (MaskNumElts % SrcNumElts == 0) {
3606       // Mask length is a multiple of the source vector length.
3607       // Check if the shuffle is some kind of concatenation of the input
3608       // vectors.
3609       unsigned NumConcat = MaskNumElts / SrcNumElts;
3610       bool IsConcat = true;
3611       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3612       for (unsigned i = 0; i != MaskNumElts; ++i) {
3613         int Idx = Mask[i];
3614         if (Idx < 0)
3615           continue;
3616         // Ensure the indices in each SrcVT sized piece are sequential and that
3617         // the same source is used for the whole piece.
3618         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3619             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3620              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3621           IsConcat = false;
3622           break;
3623         }
3624         // Remember which source this index came from.
3625         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3626       }
3627 
3628       // The shuffle is concatenating multiple vectors together. Just emit
3629       // a CONCAT_VECTORS operation.
3630       if (IsConcat) {
3631         SmallVector<SDValue, 8> ConcatOps;
3632         for (auto Src : ConcatSrcs) {
3633           if (Src < 0)
3634             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3635           else if (Src == 0)
3636             ConcatOps.push_back(Src1);
3637           else
3638             ConcatOps.push_back(Src2);
3639         }
3640         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3641         return;
3642       }
3643     }
3644 
3645     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3646     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3647     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3648                                     PaddedMaskNumElts);
3649 
3650     // Pad both vectors with undefs to make them the same length as the mask.
3651     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3652 
3653     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3654     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3655     MOps1[0] = Src1;
3656     MOps2[0] = Src2;
3657 
3658     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3659     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3660 
3661     // Readjust mask for new input vector length.
3662     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3663     for (unsigned i = 0; i != MaskNumElts; ++i) {
3664       int Idx = Mask[i];
3665       if (Idx >= (int)SrcNumElts)
3666         Idx -= SrcNumElts - PaddedMaskNumElts;
3667       MappedOps[i] = Idx;
3668     }
3669 
3670     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3671 
3672     // If the concatenated vector was padded, extract a subvector with the
3673     // correct number of elements.
3674     if (MaskNumElts != PaddedMaskNumElts)
3675       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3676                            DAG.getVectorIdxConstant(0, DL));
3677 
3678     setValue(&I, Result);
3679     return;
3680   }
3681 
3682   if (SrcNumElts > MaskNumElts) {
3683     // Analyze the access pattern of the vector to see if we can extract
3684     // two subvectors and do the shuffle.
3685     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3686     bool CanExtract = true;
3687     for (int Idx : Mask) {
3688       unsigned Input = 0;
3689       if (Idx < 0)
3690         continue;
3691 
3692       if (Idx >= (int)SrcNumElts) {
3693         Input = 1;
3694         Idx -= SrcNumElts;
3695       }
3696 
3697       // If all the indices come from the same MaskNumElts sized portion of
3698       // the sources we can use extract. Also make sure the extract wouldn't
3699       // extract past the end of the source.
3700       int NewStartIdx = alignDown(Idx, MaskNumElts);
3701       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3702           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3703         CanExtract = false;
3704       // Make sure we always update StartIdx as we use it to track if all
3705       // elements are undef.
3706       StartIdx[Input] = NewStartIdx;
3707     }
3708 
3709     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3710       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3711       return;
3712     }
3713     if (CanExtract) {
3714       // Extract appropriate subvector and generate a vector shuffle
3715       for (unsigned Input = 0; Input < 2; ++Input) {
3716         SDValue &Src = Input == 0 ? Src1 : Src2;
3717         if (StartIdx[Input] < 0)
3718           Src = DAG.getUNDEF(VT);
3719         else {
3720           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3721                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3722         }
3723       }
3724 
3725       // Calculate new mask.
3726       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3727       for (int &Idx : MappedOps) {
3728         if (Idx >= (int)SrcNumElts)
3729           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3730         else if (Idx >= 0)
3731           Idx -= StartIdx[0];
3732       }
3733 
3734       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3735       return;
3736     }
3737   }
3738 
3739   // We can't use either concat vectors or extract subvectors so fall back to
3740   // replacing the shuffle with extract and build vector.
3741   // to insert and build vector.
3742   EVT EltVT = VT.getVectorElementType();
3743   SmallVector<SDValue,8> Ops;
3744   for (int Idx : Mask) {
3745     SDValue Res;
3746 
3747     if (Idx < 0) {
3748       Res = DAG.getUNDEF(EltVT);
3749     } else {
3750       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3751       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3752 
3753       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3754                         DAG.getVectorIdxConstant(Idx, DL));
3755     }
3756 
3757     Ops.push_back(Res);
3758   }
3759 
3760   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3761 }
3762 
3763 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3764   ArrayRef<unsigned> Indices;
3765   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3766     Indices = IV->getIndices();
3767   else
3768     Indices = cast<ConstantExpr>(&I)->getIndices();
3769 
3770   const Value *Op0 = I.getOperand(0);
3771   const Value *Op1 = I.getOperand(1);
3772   Type *AggTy = I.getType();
3773   Type *ValTy = Op1->getType();
3774   bool IntoUndef = isa<UndefValue>(Op0);
3775   bool FromUndef = isa<UndefValue>(Op1);
3776 
3777   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3778 
3779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3780   SmallVector<EVT, 4> AggValueVTs;
3781   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3782   SmallVector<EVT, 4> ValValueVTs;
3783   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3784 
3785   unsigned NumAggValues = AggValueVTs.size();
3786   unsigned NumValValues = ValValueVTs.size();
3787   SmallVector<SDValue, 4> Values(NumAggValues);
3788 
3789   // Ignore an insertvalue that produces an empty object
3790   if (!NumAggValues) {
3791     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3792     return;
3793   }
3794 
3795   SDValue Agg = getValue(Op0);
3796   unsigned i = 0;
3797   // Copy the beginning value(s) from the original aggregate.
3798   for (; i != LinearIndex; ++i)
3799     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3800                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3801   // Copy values from the inserted value(s).
3802   if (NumValValues) {
3803     SDValue Val = getValue(Op1);
3804     for (; i != LinearIndex + NumValValues; ++i)
3805       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3806                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3807   }
3808   // Copy remaining value(s) from the original aggregate.
3809   for (; i != NumAggValues; ++i)
3810     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3811                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3812 
3813   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3814                            DAG.getVTList(AggValueVTs), Values));
3815 }
3816 
3817 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3818   ArrayRef<unsigned> Indices;
3819   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3820     Indices = EV->getIndices();
3821   else
3822     Indices = cast<ConstantExpr>(&I)->getIndices();
3823 
3824   const Value *Op0 = I.getOperand(0);
3825   Type *AggTy = Op0->getType();
3826   Type *ValTy = I.getType();
3827   bool OutOfUndef = isa<UndefValue>(Op0);
3828 
3829   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3830 
3831   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3832   SmallVector<EVT, 4> ValValueVTs;
3833   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3834 
3835   unsigned NumValValues = ValValueVTs.size();
3836 
3837   // Ignore a extractvalue that produces an empty object
3838   if (!NumValValues) {
3839     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3840     return;
3841   }
3842 
3843   SmallVector<SDValue, 4> Values(NumValValues);
3844 
3845   SDValue Agg = getValue(Op0);
3846   // Copy out the selected value(s).
3847   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3848     Values[i - LinearIndex] =
3849       OutOfUndef ?
3850         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3851         SDValue(Agg.getNode(), Agg.getResNo() + i);
3852 
3853   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3854                            DAG.getVTList(ValValueVTs), Values));
3855 }
3856 
3857 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3858   Value *Op0 = I.getOperand(0);
3859   // Note that the pointer operand may be a vector of pointers. Take the scalar
3860   // element which holds a pointer.
3861   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3862   SDValue N = getValue(Op0);
3863   SDLoc dl = getCurSDLoc();
3864   auto &TLI = DAG.getTargetLoweringInfo();
3865 
3866   // Normalize Vector GEP - all scalar operands should be converted to the
3867   // splat vector.
3868   bool IsVectorGEP = I.getType()->isVectorTy();
3869   ElementCount VectorElementCount =
3870       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3871                   : ElementCount::getFixed(0);
3872 
3873   if (IsVectorGEP && !N.getValueType().isVector()) {
3874     LLVMContext &Context = *DAG.getContext();
3875     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3876     if (VectorElementCount.isScalable())
3877       N = DAG.getSplatVector(VT, dl, N);
3878     else
3879       N = DAG.getSplatBuildVector(VT, dl, N);
3880   }
3881 
3882   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3883        GTI != E; ++GTI) {
3884     const Value *Idx = GTI.getOperand();
3885     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3886       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3887       if (Field) {
3888         // N = N + Offset
3889         uint64_t Offset =
3890             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3891 
3892         // In an inbounds GEP with an offset that is nonnegative even when
3893         // interpreted as signed, assume there is no unsigned overflow.
3894         SDNodeFlags Flags;
3895         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3896           Flags.setNoUnsignedWrap(true);
3897 
3898         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3899                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3900       }
3901     } else {
3902       // IdxSize is the width of the arithmetic according to IR semantics.
3903       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3904       // (and fix up the result later).
3905       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3906       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3907       TypeSize ElementSize =
3908           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3909       // We intentionally mask away the high bits here; ElementSize may not
3910       // fit in IdxTy.
3911       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3912       bool ElementScalable = ElementSize.isScalable();
3913 
3914       // If this is a scalar constant or a splat vector of constants,
3915       // handle it quickly.
3916       const auto *C = dyn_cast<Constant>(Idx);
3917       if (C && isa<VectorType>(C->getType()))
3918         C = C->getSplatValue();
3919 
3920       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3921       if (CI && CI->isZero())
3922         continue;
3923       if (CI && !ElementScalable) {
3924         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3925         LLVMContext &Context = *DAG.getContext();
3926         SDValue OffsVal;
3927         if (IsVectorGEP)
3928           OffsVal = DAG.getConstant(
3929               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3930         else
3931           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3932 
3933         // In an inbounds GEP with an offset that is nonnegative even when
3934         // interpreted as signed, assume there is no unsigned overflow.
3935         SDNodeFlags Flags;
3936         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3937           Flags.setNoUnsignedWrap(true);
3938 
3939         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3940 
3941         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3942         continue;
3943       }
3944 
3945       // N = N + Idx * ElementMul;
3946       SDValue IdxN = getValue(Idx);
3947 
3948       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3949         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3950                                   VectorElementCount);
3951         if (VectorElementCount.isScalable())
3952           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3953         else
3954           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3955       }
3956 
3957       // If the index is smaller or larger than intptr_t, truncate or extend
3958       // it.
3959       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3960 
3961       if (ElementScalable) {
3962         EVT VScaleTy = N.getValueType().getScalarType();
3963         SDValue VScale = DAG.getNode(
3964             ISD::VSCALE, dl, VScaleTy,
3965             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3966         if (IsVectorGEP)
3967           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3968         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3969       } else {
3970         // If this is a multiply by a power of two, turn it into a shl
3971         // immediately.  This is a very common case.
3972         if (ElementMul != 1) {
3973           if (ElementMul.isPowerOf2()) {
3974             unsigned Amt = ElementMul.logBase2();
3975             IdxN = DAG.getNode(ISD::SHL, dl,
3976                                N.getValueType(), IdxN,
3977                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3978           } else {
3979             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3980                                             IdxN.getValueType());
3981             IdxN = DAG.getNode(ISD::MUL, dl,
3982                                N.getValueType(), IdxN, Scale);
3983           }
3984         }
3985       }
3986 
3987       N = DAG.getNode(ISD::ADD, dl,
3988                       N.getValueType(), N, IdxN);
3989     }
3990   }
3991 
3992   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3993   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3994   if (IsVectorGEP) {
3995     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3996     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3997   }
3998 
3999   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4000     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4001 
4002   setValue(&I, N);
4003 }
4004 
4005 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4006   // If this is a fixed sized alloca in the entry block of the function,
4007   // allocate it statically on the stack.
4008   if (FuncInfo.StaticAllocaMap.count(&I))
4009     return;   // getValue will auto-populate this.
4010 
4011   SDLoc dl = getCurSDLoc();
4012   Type *Ty = I.getAllocatedType();
4013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4014   auto &DL = DAG.getDataLayout();
4015   uint64_t TySize = DL.getTypeAllocSize(Ty);
4016   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4017 
4018   SDValue AllocSize = getValue(I.getArraySize());
4019 
4020   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4021   if (AllocSize.getValueType() != IntPtr)
4022     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4023 
4024   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4025                           AllocSize,
4026                           DAG.getConstant(TySize, dl, IntPtr));
4027 
4028   // Handle alignment.  If the requested alignment is less than or equal to
4029   // the stack alignment, ignore it.  If the size is greater than or equal to
4030   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4031   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4032   if (*Alignment <= StackAlign)
4033     Alignment = None;
4034 
4035   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4036   // Round the size of the allocation up to the stack alignment size
4037   // by add SA-1 to the size. This doesn't overflow because we're computing
4038   // an address inside an alloca.
4039   SDNodeFlags Flags;
4040   Flags.setNoUnsignedWrap(true);
4041   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4042                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4043 
4044   // Mask out the low bits for alignment purposes.
4045   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4046                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4047 
4048   SDValue Ops[] = {
4049       getRoot(), AllocSize,
4050       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4051   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4052   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4053   setValue(&I, DSA);
4054   DAG.setRoot(DSA.getValue(1));
4055 
4056   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4057 }
4058 
4059 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4060   if (I.isAtomic())
4061     return visitAtomicLoad(I);
4062 
4063   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4064   const Value *SV = I.getOperand(0);
4065   if (TLI.supportSwiftError()) {
4066     // Swifterror values can come from either a function parameter with
4067     // swifterror attribute or an alloca with swifterror attribute.
4068     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4069       if (Arg->hasSwiftErrorAttr())
4070         return visitLoadFromSwiftError(I);
4071     }
4072 
4073     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4074       if (Alloca->isSwiftError())
4075         return visitLoadFromSwiftError(I);
4076     }
4077   }
4078 
4079   SDValue Ptr = getValue(SV);
4080 
4081   Type *Ty = I.getType();
4082   Align Alignment = I.getAlign();
4083 
4084   AAMDNodes AAInfo = I.getAAMetadata();
4085   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4086 
4087   SmallVector<EVT, 4> ValueVTs, MemVTs;
4088   SmallVector<uint64_t, 4> Offsets;
4089   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4090   unsigned NumValues = ValueVTs.size();
4091   if (NumValues == 0)
4092     return;
4093 
4094   bool isVolatile = I.isVolatile();
4095 
4096   SDValue Root;
4097   bool ConstantMemory = false;
4098   if (isVolatile)
4099     // Serialize volatile loads with other side effects.
4100     Root = getRoot();
4101   else if (NumValues > MaxParallelChains)
4102     Root = getMemoryRoot();
4103   else if (AA &&
4104            AA->pointsToConstantMemory(MemoryLocation(
4105                SV,
4106                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4107                AAInfo))) {
4108     // Do not serialize (non-volatile) loads of constant memory with anything.
4109     Root = DAG.getEntryNode();
4110     ConstantMemory = true;
4111   } else {
4112     // Do not serialize non-volatile loads against each other.
4113     Root = DAG.getRoot();
4114   }
4115 
4116   SDLoc dl = getCurSDLoc();
4117 
4118   if (isVolatile)
4119     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4120 
4121   // An aggregate load cannot wrap around the address space, so offsets to its
4122   // parts don't wrap either.
4123   SDNodeFlags Flags;
4124   Flags.setNoUnsignedWrap(true);
4125 
4126   SmallVector<SDValue, 4> Values(NumValues);
4127   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4128   EVT PtrVT = Ptr.getValueType();
4129 
4130   MachineMemOperand::Flags MMOFlags
4131     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4132 
4133   unsigned ChainI = 0;
4134   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4135     // Serializing loads here may result in excessive register pressure, and
4136     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4137     // could recover a bit by hoisting nodes upward in the chain by recognizing
4138     // they are side-effect free or do not alias. The optimizer should really
4139     // avoid this case by converting large object/array copies to llvm.memcpy
4140     // (MaxParallelChains should always remain as failsafe).
4141     if (ChainI == MaxParallelChains) {
4142       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4143       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4144                                   makeArrayRef(Chains.data(), ChainI));
4145       Root = Chain;
4146       ChainI = 0;
4147     }
4148     SDValue A = DAG.getNode(ISD::ADD, dl,
4149                             PtrVT, Ptr,
4150                             DAG.getConstant(Offsets[i], dl, PtrVT),
4151                             Flags);
4152 
4153     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4154                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4155                             MMOFlags, AAInfo, Ranges);
4156     Chains[ChainI] = L.getValue(1);
4157 
4158     if (MemVTs[i] != ValueVTs[i])
4159       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4160 
4161     Values[i] = L;
4162   }
4163 
4164   if (!ConstantMemory) {
4165     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4166                                 makeArrayRef(Chains.data(), ChainI));
4167     if (isVolatile)
4168       DAG.setRoot(Chain);
4169     else
4170       PendingLoads.push_back(Chain);
4171   }
4172 
4173   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4174                            DAG.getVTList(ValueVTs), Values));
4175 }
4176 
4177 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4178   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4179          "call visitStoreToSwiftError when backend supports swifterror");
4180 
4181   SmallVector<EVT, 4> ValueVTs;
4182   SmallVector<uint64_t, 4> Offsets;
4183   const Value *SrcV = I.getOperand(0);
4184   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4185                   SrcV->getType(), ValueVTs, &Offsets);
4186   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4187          "expect a single EVT for swifterror");
4188 
4189   SDValue Src = getValue(SrcV);
4190   // Create a virtual register, then update the virtual register.
4191   Register VReg =
4192       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4193   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4194   // Chain can be getRoot or getControlRoot.
4195   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4196                                       SDValue(Src.getNode(), Src.getResNo()));
4197   DAG.setRoot(CopyNode);
4198 }
4199 
4200 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4201   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4202          "call visitLoadFromSwiftError when backend supports swifterror");
4203 
4204   assert(!I.isVolatile() &&
4205          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4206          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4207          "Support volatile, non temporal, invariant for load_from_swift_error");
4208 
4209   const Value *SV = I.getOperand(0);
4210   Type *Ty = I.getType();
4211   assert(
4212       (!AA ||
4213        !AA->pointsToConstantMemory(MemoryLocation(
4214            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4215            I.getAAMetadata()))) &&
4216       "load_from_swift_error should not be constant memory");
4217 
4218   SmallVector<EVT, 4> ValueVTs;
4219   SmallVector<uint64_t, 4> Offsets;
4220   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4221                   ValueVTs, &Offsets);
4222   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4223          "expect a single EVT for swifterror");
4224 
4225   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4226   SDValue L = DAG.getCopyFromReg(
4227       getRoot(), getCurSDLoc(),
4228       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4229 
4230   setValue(&I, L);
4231 }
4232 
4233 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4234   if (I.isAtomic())
4235     return visitAtomicStore(I);
4236 
4237   const Value *SrcV = I.getOperand(0);
4238   const Value *PtrV = I.getOperand(1);
4239 
4240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4241   if (TLI.supportSwiftError()) {
4242     // Swifterror values can come from either a function parameter with
4243     // swifterror attribute or an alloca with swifterror attribute.
4244     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4245       if (Arg->hasSwiftErrorAttr())
4246         return visitStoreToSwiftError(I);
4247     }
4248 
4249     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4250       if (Alloca->isSwiftError())
4251         return visitStoreToSwiftError(I);
4252     }
4253   }
4254 
4255   SmallVector<EVT, 4> ValueVTs, MemVTs;
4256   SmallVector<uint64_t, 4> Offsets;
4257   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4258                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4259   unsigned NumValues = ValueVTs.size();
4260   if (NumValues == 0)
4261     return;
4262 
4263   // Get the lowered operands. Note that we do this after
4264   // checking if NumResults is zero, because with zero results
4265   // the operands won't have values in the map.
4266   SDValue Src = getValue(SrcV);
4267   SDValue Ptr = getValue(PtrV);
4268 
4269   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4270   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4271   SDLoc dl = getCurSDLoc();
4272   Align Alignment = I.getAlign();
4273   AAMDNodes AAInfo = I.getAAMetadata();
4274 
4275   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4276 
4277   // An aggregate load cannot wrap around the address space, so offsets to its
4278   // parts don't wrap either.
4279   SDNodeFlags Flags;
4280   Flags.setNoUnsignedWrap(true);
4281 
4282   unsigned ChainI = 0;
4283   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4284     // See visitLoad comments.
4285     if (ChainI == MaxParallelChains) {
4286       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4287                                   makeArrayRef(Chains.data(), ChainI));
4288       Root = Chain;
4289       ChainI = 0;
4290     }
4291     SDValue Add =
4292         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4293     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4294     if (MemVTs[i] != ValueVTs[i])
4295       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4296     SDValue St =
4297         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4298                      Alignment, MMOFlags, AAInfo);
4299     Chains[ChainI] = St;
4300   }
4301 
4302   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4303                                   makeArrayRef(Chains.data(), ChainI));
4304   DAG.setRoot(StoreNode);
4305 }
4306 
4307 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4308                                            bool IsCompressing) {
4309   SDLoc sdl = getCurSDLoc();
4310 
4311   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4312                                MaybeAlign &Alignment) {
4313     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4314     Src0 = I.getArgOperand(0);
4315     Ptr = I.getArgOperand(1);
4316     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4317     Mask = I.getArgOperand(3);
4318   };
4319   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4320                                     MaybeAlign &Alignment) {
4321     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4322     Src0 = I.getArgOperand(0);
4323     Ptr = I.getArgOperand(1);
4324     Mask = I.getArgOperand(2);
4325     Alignment = None;
4326   };
4327 
4328   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4329   MaybeAlign Alignment;
4330   if (IsCompressing)
4331     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4332   else
4333     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4334 
4335   SDValue Ptr = getValue(PtrOperand);
4336   SDValue Src0 = getValue(Src0Operand);
4337   SDValue Mask = getValue(MaskOperand);
4338   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4339 
4340   EVT VT = Src0.getValueType();
4341   if (!Alignment)
4342     Alignment = DAG.getEVTAlign(VT);
4343 
4344   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4345       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4346       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4347   SDValue StoreNode =
4348       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4349                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4350   DAG.setRoot(StoreNode);
4351   setValue(&I, StoreNode);
4352 }
4353 
4354 // Get a uniform base for the Gather/Scatter intrinsic.
4355 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4356 // We try to represent it as a base pointer + vector of indices.
4357 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4358 // The first operand of the GEP may be a single pointer or a vector of pointers
4359 // Example:
4360 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4361 //  or
4362 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4363 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4364 //
4365 // When the first GEP operand is a single pointer - it is the uniform base we
4366 // are looking for. If first operand of the GEP is a splat vector - we
4367 // extract the splat value and use it as a uniform base.
4368 // In all other cases the function returns 'false'.
4369 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4370                            ISD::MemIndexType &IndexType, SDValue &Scale,
4371                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4372   SelectionDAG& DAG = SDB->DAG;
4373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4374   const DataLayout &DL = DAG.getDataLayout();
4375 
4376   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4377 
4378   // Handle splat constant pointer.
4379   if (auto *C = dyn_cast<Constant>(Ptr)) {
4380     C = C->getSplatValue();
4381     if (!C)
4382       return false;
4383 
4384     Base = SDB->getValue(C);
4385 
4386     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4387     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4388     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4389     IndexType = ISD::SIGNED_SCALED;
4390     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4391     return true;
4392   }
4393 
4394   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4395   if (!GEP || GEP->getParent() != CurBB)
4396     return false;
4397 
4398   if (GEP->getNumOperands() != 2)
4399     return false;
4400 
4401   const Value *BasePtr = GEP->getPointerOperand();
4402   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4403 
4404   // Make sure the base is scalar and the index is a vector.
4405   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4406     return false;
4407 
4408   Base = SDB->getValue(BasePtr);
4409   Index = SDB->getValue(IndexVal);
4410   IndexType = ISD::SIGNED_SCALED;
4411   Scale = DAG.getTargetConstant(
4412               DL.getTypeAllocSize(GEP->getResultElementType()),
4413               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4414   return true;
4415 }
4416 
4417 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4418   SDLoc sdl = getCurSDLoc();
4419 
4420   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4421   const Value *Ptr = I.getArgOperand(1);
4422   SDValue Src0 = getValue(I.getArgOperand(0));
4423   SDValue Mask = getValue(I.getArgOperand(3));
4424   EVT VT = Src0.getValueType();
4425   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4426                         ->getMaybeAlignValue()
4427                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4429 
4430   SDValue Base;
4431   SDValue Index;
4432   ISD::MemIndexType IndexType;
4433   SDValue Scale;
4434   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4435                                     I.getParent());
4436 
4437   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4438   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4439       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4440       // TODO: Make MachineMemOperands aware of scalable
4441       // vectors.
4442       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4443   if (!UniformBase) {
4444     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4445     Index = getValue(Ptr);
4446     IndexType = ISD::SIGNED_UNSCALED;
4447     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4448   }
4449 
4450   EVT IdxVT = Index.getValueType();
4451   EVT EltTy = IdxVT.getVectorElementType();
4452   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4453     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4454     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4455   }
4456 
4457   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4458   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4459                                          Ops, MMO, IndexType, false);
4460   DAG.setRoot(Scatter);
4461   setValue(&I, Scatter);
4462 }
4463 
4464 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4465   SDLoc sdl = getCurSDLoc();
4466 
4467   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4468                               MaybeAlign &Alignment) {
4469     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4470     Ptr = I.getArgOperand(0);
4471     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4472     Mask = I.getArgOperand(2);
4473     Src0 = I.getArgOperand(3);
4474   };
4475   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4476                                  MaybeAlign &Alignment) {
4477     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4478     Ptr = I.getArgOperand(0);
4479     Alignment = None;
4480     Mask = I.getArgOperand(1);
4481     Src0 = I.getArgOperand(2);
4482   };
4483 
4484   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4485   MaybeAlign Alignment;
4486   if (IsExpanding)
4487     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4488   else
4489     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4490 
4491   SDValue Ptr = getValue(PtrOperand);
4492   SDValue Src0 = getValue(Src0Operand);
4493   SDValue Mask = getValue(MaskOperand);
4494   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4495 
4496   EVT VT = Src0.getValueType();
4497   if (!Alignment)
4498     Alignment = DAG.getEVTAlign(VT);
4499 
4500   AAMDNodes AAInfo = I.getAAMetadata();
4501   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4502 
4503   // Do not serialize masked loads of constant memory with anything.
4504   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4505   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4506 
4507   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4508 
4509   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4510       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4511       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4512 
4513   SDValue Load =
4514       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4515                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4516   if (AddToChain)
4517     PendingLoads.push_back(Load.getValue(1));
4518   setValue(&I, Load);
4519 }
4520 
4521 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4522   SDLoc sdl = getCurSDLoc();
4523 
4524   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4525   const Value *Ptr = I.getArgOperand(0);
4526   SDValue Src0 = getValue(I.getArgOperand(3));
4527   SDValue Mask = getValue(I.getArgOperand(2));
4528 
4529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4530   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4531   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4532                         ->getMaybeAlignValue()
4533                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4534 
4535   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4536 
4537   SDValue Root = DAG.getRoot();
4538   SDValue Base;
4539   SDValue Index;
4540   ISD::MemIndexType IndexType;
4541   SDValue Scale;
4542   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4543                                     I.getParent());
4544   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4545   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4546       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4547       // TODO: Make MachineMemOperands aware of scalable
4548       // vectors.
4549       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4550 
4551   if (!UniformBase) {
4552     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4553     Index = getValue(Ptr);
4554     IndexType = ISD::SIGNED_UNSCALED;
4555     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4556   }
4557 
4558   EVT IdxVT = Index.getValueType();
4559   EVT EltTy = IdxVT.getVectorElementType();
4560   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4561     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4562     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4563   }
4564 
4565   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4566   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4567                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4568 
4569   PendingLoads.push_back(Gather.getValue(1));
4570   setValue(&I, Gather);
4571 }
4572 
4573 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4574   SDLoc dl = getCurSDLoc();
4575   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4576   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4577   SyncScope::ID SSID = I.getSyncScopeID();
4578 
4579   SDValue InChain = getRoot();
4580 
4581   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4582   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4583 
4584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4585   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4586 
4587   MachineFunction &MF = DAG.getMachineFunction();
4588   MachineMemOperand *MMO = MF.getMachineMemOperand(
4589       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4590       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4591       FailureOrdering);
4592 
4593   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4594                                    dl, MemVT, VTs, InChain,
4595                                    getValue(I.getPointerOperand()),
4596                                    getValue(I.getCompareOperand()),
4597                                    getValue(I.getNewValOperand()), MMO);
4598 
4599   SDValue OutChain = L.getValue(2);
4600 
4601   setValue(&I, L);
4602   DAG.setRoot(OutChain);
4603 }
4604 
4605 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4606   SDLoc dl = getCurSDLoc();
4607   ISD::NodeType NT;
4608   switch (I.getOperation()) {
4609   default: llvm_unreachable("Unknown atomicrmw operation");
4610   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4611   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4612   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4613   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4614   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4615   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4616   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4617   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4618   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4619   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4620   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4621   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4622   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4623   }
4624   AtomicOrdering Ordering = I.getOrdering();
4625   SyncScope::ID SSID = I.getSyncScopeID();
4626 
4627   SDValue InChain = getRoot();
4628 
4629   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4630   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4631   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4632 
4633   MachineFunction &MF = DAG.getMachineFunction();
4634   MachineMemOperand *MMO = MF.getMachineMemOperand(
4635       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4636       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4637 
4638   SDValue L =
4639     DAG.getAtomic(NT, dl, MemVT, InChain,
4640                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4641                   MMO);
4642 
4643   SDValue OutChain = L.getValue(1);
4644 
4645   setValue(&I, L);
4646   DAG.setRoot(OutChain);
4647 }
4648 
4649 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4650   SDLoc dl = getCurSDLoc();
4651   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4652   SDValue Ops[3];
4653   Ops[0] = getRoot();
4654   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4655                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4656   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4657                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4658   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4659 }
4660 
4661 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4662   SDLoc dl = getCurSDLoc();
4663   AtomicOrdering Order = I.getOrdering();
4664   SyncScope::ID SSID = I.getSyncScopeID();
4665 
4666   SDValue InChain = getRoot();
4667 
4668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4669   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4670   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4671 
4672   if (!TLI.supportsUnalignedAtomics() &&
4673       I.getAlignment() < MemVT.getSizeInBits() / 8)
4674     report_fatal_error("Cannot generate unaligned atomic load");
4675 
4676   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4677 
4678   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4679       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4680       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4681 
4682   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4683 
4684   SDValue Ptr = getValue(I.getPointerOperand());
4685 
4686   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4687     // TODO: Once this is better exercised by tests, it should be merged with
4688     // the normal path for loads to prevent future divergence.
4689     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4690     if (MemVT != VT)
4691       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4692 
4693     setValue(&I, L);
4694     SDValue OutChain = L.getValue(1);
4695     if (!I.isUnordered())
4696       DAG.setRoot(OutChain);
4697     else
4698       PendingLoads.push_back(OutChain);
4699     return;
4700   }
4701 
4702   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4703                             Ptr, MMO);
4704 
4705   SDValue OutChain = L.getValue(1);
4706   if (MemVT != VT)
4707     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4708 
4709   setValue(&I, L);
4710   DAG.setRoot(OutChain);
4711 }
4712 
4713 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4714   SDLoc dl = getCurSDLoc();
4715 
4716   AtomicOrdering Ordering = I.getOrdering();
4717   SyncScope::ID SSID = I.getSyncScopeID();
4718 
4719   SDValue InChain = getRoot();
4720 
4721   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4722   EVT MemVT =
4723       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4724 
4725   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4726     report_fatal_error("Cannot generate unaligned atomic store");
4727 
4728   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4729 
4730   MachineFunction &MF = DAG.getMachineFunction();
4731   MachineMemOperand *MMO = MF.getMachineMemOperand(
4732       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4733       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4734 
4735   SDValue Val = getValue(I.getValueOperand());
4736   if (Val.getValueType() != MemVT)
4737     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4738   SDValue Ptr = getValue(I.getPointerOperand());
4739 
4740   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4741     // TODO: Once this is better exercised by tests, it should be merged with
4742     // the normal path for stores to prevent future divergence.
4743     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4744     DAG.setRoot(S);
4745     return;
4746   }
4747   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4748                                    Ptr, Val, MMO);
4749 
4750 
4751   DAG.setRoot(OutChain);
4752 }
4753 
4754 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4755 /// node.
4756 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4757                                                unsigned Intrinsic) {
4758   // Ignore the callsite's attributes. A specific call site may be marked with
4759   // readnone, but the lowering code will expect the chain based on the
4760   // definition.
4761   const Function *F = I.getCalledFunction();
4762   bool HasChain = !F->doesNotAccessMemory();
4763   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4764 
4765   // Build the operand list.
4766   SmallVector<SDValue, 8> Ops;
4767   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4768     if (OnlyLoad) {
4769       // We don't need to serialize loads against other loads.
4770       Ops.push_back(DAG.getRoot());
4771     } else {
4772       Ops.push_back(getRoot());
4773     }
4774   }
4775 
4776   // Info is set by getTgtMemInstrinsic
4777   TargetLowering::IntrinsicInfo Info;
4778   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4779   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4780                                                DAG.getMachineFunction(),
4781                                                Intrinsic);
4782 
4783   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4784   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4785       Info.opc == ISD::INTRINSIC_W_CHAIN)
4786     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4787                                         TLI.getPointerTy(DAG.getDataLayout())));
4788 
4789   // Add all operands of the call to the operand list.
4790   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4791     const Value *Arg = I.getArgOperand(i);
4792     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4793       Ops.push_back(getValue(Arg));
4794       continue;
4795     }
4796 
4797     // Use TargetConstant instead of a regular constant for immarg.
4798     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4799     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4800       assert(CI->getBitWidth() <= 64 &&
4801              "large intrinsic immediates not handled");
4802       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4803     } else {
4804       Ops.push_back(
4805           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4806     }
4807   }
4808 
4809   SmallVector<EVT, 4> ValueVTs;
4810   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4811 
4812   if (HasChain)
4813     ValueVTs.push_back(MVT::Other);
4814 
4815   SDVTList VTs = DAG.getVTList(ValueVTs);
4816 
4817   // Propagate fast-math-flags from IR to node(s).
4818   SDNodeFlags Flags;
4819   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4820     Flags.copyFMF(*FPMO);
4821   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4822 
4823   // Create the node.
4824   SDValue Result;
4825   if (IsTgtIntrinsic) {
4826     // This is target intrinsic that touches memory
4827     Result =
4828         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4829                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4830                                 Info.align, Info.flags, Info.size,
4831                                 I.getAAMetadata());
4832   } else if (!HasChain) {
4833     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4834   } else if (!I.getType()->isVoidTy()) {
4835     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4836   } else {
4837     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4838   }
4839 
4840   if (HasChain) {
4841     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4842     if (OnlyLoad)
4843       PendingLoads.push_back(Chain);
4844     else
4845       DAG.setRoot(Chain);
4846   }
4847 
4848   if (!I.getType()->isVoidTy()) {
4849     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4850       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4851       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4852     } else
4853       Result = lowerRangeToAssertZExt(DAG, I, Result);
4854 
4855     MaybeAlign Alignment = I.getRetAlign();
4856     if (!Alignment)
4857       Alignment = F->getAttributes().getRetAlignment();
4858     // Insert `assertalign` node if there's an alignment.
4859     if (InsertAssertAlign && Alignment) {
4860       Result =
4861           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4862     }
4863 
4864     setValue(&I, Result);
4865   }
4866 }
4867 
4868 /// GetSignificand - Get the significand and build it into a floating-point
4869 /// number with exponent of 1:
4870 ///
4871 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4872 ///
4873 /// where Op is the hexadecimal representation of floating point value.
4874 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4875   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4876                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4877   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4878                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4879   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4880 }
4881 
4882 /// GetExponent - Get the exponent:
4883 ///
4884 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4885 ///
4886 /// where Op is the hexadecimal representation of floating point value.
4887 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4888                            const TargetLowering &TLI, const SDLoc &dl) {
4889   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4890                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4891   SDValue t1 = DAG.getNode(
4892       ISD::SRL, dl, MVT::i32, t0,
4893       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4894   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4895                            DAG.getConstant(127, dl, MVT::i32));
4896   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4897 }
4898 
4899 /// getF32Constant - Get 32-bit floating point constant.
4900 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4901                               const SDLoc &dl) {
4902   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4903                            MVT::f32);
4904 }
4905 
4906 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4907                                        SelectionDAG &DAG) {
4908   // TODO: What fast-math-flags should be set on the floating-point nodes?
4909 
4910   //   IntegerPartOfX = ((int32_t)(t0);
4911   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4912 
4913   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4914   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4915   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4916 
4917   //   IntegerPartOfX <<= 23;
4918   IntegerPartOfX = DAG.getNode(
4919       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4920       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4921                                   DAG.getDataLayout())));
4922 
4923   SDValue TwoToFractionalPartOfX;
4924   if (LimitFloatPrecision <= 6) {
4925     // For floating-point precision of 6:
4926     //
4927     //   TwoToFractionalPartOfX =
4928     //     0.997535578f +
4929     //       (0.735607626f + 0.252464424f * x) * x;
4930     //
4931     // error 0.0144103317, which is 6 bits
4932     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4933                              getF32Constant(DAG, 0x3e814304, dl));
4934     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4935                              getF32Constant(DAG, 0x3f3c50c8, dl));
4936     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4937     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4938                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4939   } else if (LimitFloatPrecision <= 12) {
4940     // For floating-point precision of 12:
4941     //
4942     //   TwoToFractionalPartOfX =
4943     //     0.999892986f +
4944     //       (0.696457318f +
4945     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4946     //
4947     // error 0.000107046256, which is 13 to 14 bits
4948     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4949                              getF32Constant(DAG, 0x3da235e3, dl));
4950     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4951                              getF32Constant(DAG, 0x3e65b8f3, dl));
4952     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4953     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4954                              getF32Constant(DAG, 0x3f324b07, dl));
4955     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4956     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4957                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4958   } else { // LimitFloatPrecision <= 18
4959     // For floating-point precision of 18:
4960     //
4961     //   TwoToFractionalPartOfX =
4962     //     0.999999982f +
4963     //       (0.693148872f +
4964     //         (0.240227044f +
4965     //           (0.554906021e-1f +
4966     //             (0.961591928e-2f +
4967     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4968     // error 2.47208000*10^(-7), which is better than 18 bits
4969     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4970                              getF32Constant(DAG, 0x3924b03e, dl));
4971     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4972                              getF32Constant(DAG, 0x3ab24b87, dl));
4973     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4974     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4975                              getF32Constant(DAG, 0x3c1d8c17, dl));
4976     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4977     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4978                              getF32Constant(DAG, 0x3d634a1d, dl));
4979     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4980     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4981                              getF32Constant(DAG, 0x3e75fe14, dl));
4982     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4983     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4984                               getF32Constant(DAG, 0x3f317234, dl));
4985     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4986     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4987                                          getF32Constant(DAG, 0x3f800000, dl));
4988   }
4989 
4990   // Add the exponent into the result in integer domain.
4991   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4992   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4993                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4994 }
4995 
4996 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4997 /// limited-precision mode.
4998 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4999                          const TargetLowering &TLI, SDNodeFlags Flags) {
5000   if (Op.getValueType() == MVT::f32 &&
5001       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5002 
5003     // Put the exponent in the right bit position for later addition to the
5004     // final result:
5005     //
5006     // t0 = Op * log2(e)
5007 
5008     // TODO: What fast-math-flags should be set here?
5009     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5010                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5011     return getLimitedPrecisionExp2(t0, dl, DAG);
5012   }
5013 
5014   // No special expansion.
5015   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5016 }
5017 
5018 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5019 /// limited-precision mode.
5020 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5021                          const TargetLowering &TLI, SDNodeFlags Flags) {
5022   // TODO: What fast-math-flags should be set on the floating-point nodes?
5023 
5024   if (Op.getValueType() == MVT::f32 &&
5025       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5026     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5027 
5028     // Scale the exponent by log(2).
5029     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5030     SDValue LogOfExponent =
5031         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5032                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5033 
5034     // Get the significand and build it into a floating-point number with
5035     // exponent of 1.
5036     SDValue X = GetSignificand(DAG, Op1, dl);
5037 
5038     SDValue LogOfMantissa;
5039     if (LimitFloatPrecision <= 6) {
5040       // For floating-point precision of 6:
5041       //
5042       //   LogofMantissa =
5043       //     -1.1609546f +
5044       //       (1.4034025f - 0.23903021f * x) * x;
5045       //
5046       // error 0.0034276066, which is better than 8 bits
5047       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5048                                getF32Constant(DAG, 0xbe74c456, dl));
5049       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5050                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5051       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5052       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5053                                   getF32Constant(DAG, 0x3f949a29, dl));
5054     } else if (LimitFloatPrecision <= 12) {
5055       // For floating-point precision of 12:
5056       //
5057       //   LogOfMantissa =
5058       //     -1.7417939f +
5059       //       (2.8212026f +
5060       //         (-1.4699568f +
5061       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5062       //
5063       // error 0.000061011436, which is 14 bits
5064       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5065                                getF32Constant(DAG, 0xbd67b6d6, dl));
5066       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5067                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5068       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5069       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5070                                getF32Constant(DAG, 0x3fbc278b, dl));
5071       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5072       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5073                                getF32Constant(DAG, 0x40348e95, dl));
5074       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5075       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5076                                   getF32Constant(DAG, 0x3fdef31a, dl));
5077     } else { // LimitFloatPrecision <= 18
5078       // For floating-point precision of 18:
5079       //
5080       //   LogOfMantissa =
5081       //     -2.1072184f +
5082       //       (4.2372794f +
5083       //         (-3.7029485f +
5084       //           (2.2781945f +
5085       //             (-0.87823314f +
5086       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5087       //
5088       // error 0.0000023660568, which is better than 18 bits
5089       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5090                                getF32Constant(DAG, 0xbc91e5ac, dl));
5091       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5092                                getF32Constant(DAG, 0x3e4350aa, dl));
5093       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5094       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5095                                getF32Constant(DAG, 0x3f60d3e3, dl));
5096       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5097       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5098                                getF32Constant(DAG, 0x4011cdf0, dl));
5099       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5100       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5101                                getF32Constant(DAG, 0x406cfd1c, dl));
5102       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5103       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5104                                getF32Constant(DAG, 0x408797cb, dl));
5105       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5106       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5107                                   getF32Constant(DAG, 0x4006dcab, dl));
5108     }
5109 
5110     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5111   }
5112 
5113   // No special expansion.
5114   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5115 }
5116 
5117 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5118 /// limited-precision mode.
5119 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5120                           const TargetLowering &TLI, SDNodeFlags Flags) {
5121   // TODO: What fast-math-flags should be set on the floating-point nodes?
5122 
5123   if (Op.getValueType() == MVT::f32 &&
5124       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5125     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5126 
5127     // Get the exponent.
5128     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5129 
5130     // Get the significand and build it into a floating-point number with
5131     // exponent of 1.
5132     SDValue X = GetSignificand(DAG, Op1, dl);
5133 
5134     // Different possible minimax approximations of significand in
5135     // floating-point for various degrees of accuracy over [1,2].
5136     SDValue Log2ofMantissa;
5137     if (LimitFloatPrecision <= 6) {
5138       // For floating-point precision of 6:
5139       //
5140       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5141       //
5142       // error 0.0049451742, which is more than 7 bits
5143       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5144                                getF32Constant(DAG, 0xbeb08fe0, dl));
5145       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5146                                getF32Constant(DAG, 0x40019463, dl));
5147       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5148       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5149                                    getF32Constant(DAG, 0x3fd6633d, dl));
5150     } else if (LimitFloatPrecision <= 12) {
5151       // For floating-point precision of 12:
5152       //
5153       //   Log2ofMantissa =
5154       //     -2.51285454f +
5155       //       (4.07009056f +
5156       //         (-2.12067489f +
5157       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5158       //
5159       // error 0.0000876136000, which is better than 13 bits
5160       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5161                                getF32Constant(DAG, 0xbda7262e, dl));
5162       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5163                                getF32Constant(DAG, 0x3f25280b, dl));
5164       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5165       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5166                                getF32Constant(DAG, 0x4007b923, dl));
5167       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5168       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5169                                getF32Constant(DAG, 0x40823e2f, dl));
5170       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5171       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5172                                    getF32Constant(DAG, 0x4020d29c, dl));
5173     } else { // LimitFloatPrecision <= 18
5174       // For floating-point precision of 18:
5175       //
5176       //   Log2ofMantissa =
5177       //     -3.0400495f +
5178       //       (6.1129976f +
5179       //         (-5.3420409f +
5180       //           (3.2865683f +
5181       //             (-1.2669343f +
5182       //               (0.27515199f -
5183       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5184       //
5185       // error 0.0000018516, which is better than 18 bits
5186       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5187                                getF32Constant(DAG, 0xbcd2769e, dl));
5188       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5189                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5190       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5191       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5192                                getF32Constant(DAG, 0x3fa22ae7, dl));
5193       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5194       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5195                                getF32Constant(DAG, 0x40525723, dl));
5196       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5197       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5198                                getF32Constant(DAG, 0x40aaf200, dl));
5199       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5200       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5201                                getF32Constant(DAG, 0x40c39dad, dl));
5202       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5203       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5204                                    getF32Constant(DAG, 0x4042902c, dl));
5205     }
5206 
5207     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5208   }
5209 
5210   // No special expansion.
5211   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5212 }
5213 
5214 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5215 /// limited-precision mode.
5216 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5217                            const TargetLowering &TLI, SDNodeFlags Flags) {
5218   // TODO: What fast-math-flags should be set on the floating-point nodes?
5219 
5220   if (Op.getValueType() == MVT::f32 &&
5221       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5222     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5223 
5224     // Scale the exponent by log10(2) [0.30102999f].
5225     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5226     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5227                                         getF32Constant(DAG, 0x3e9a209a, dl));
5228 
5229     // Get the significand and build it into a floating-point number with
5230     // exponent of 1.
5231     SDValue X = GetSignificand(DAG, Op1, dl);
5232 
5233     SDValue Log10ofMantissa;
5234     if (LimitFloatPrecision <= 6) {
5235       // For floating-point precision of 6:
5236       //
5237       //   Log10ofMantissa =
5238       //     -0.50419619f +
5239       //       (0.60948995f - 0.10380950f * x) * x;
5240       //
5241       // error 0.0014886165, which is 6 bits
5242       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5243                                getF32Constant(DAG, 0xbdd49a13, dl));
5244       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5245                                getF32Constant(DAG, 0x3f1c0789, dl));
5246       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5247       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5248                                     getF32Constant(DAG, 0x3f011300, dl));
5249     } else if (LimitFloatPrecision <= 12) {
5250       // For floating-point precision of 12:
5251       //
5252       //   Log10ofMantissa =
5253       //     -0.64831180f +
5254       //       (0.91751397f +
5255       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5256       //
5257       // error 0.00019228036, which is better than 12 bits
5258       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5259                                getF32Constant(DAG, 0x3d431f31, dl));
5260       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5261                                getF32Constant(DAG, 0x3ea21fb2, dl));
5262       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5263       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5264                                getF32Constant(DAG, 0x3f6ae232, dl));
5265       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5266       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5267                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5268     } else { // LimitFloatPrecision <= 18
5269       // For floating-point precision of 18:
5270       //
5271       //   Log10ofMantissa =
5272       //     -0.84299375f +
5273       //       (1.5327582f +
5274       //         (-1.0688956f +
5275       //           (0.49102474f +
5276       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5277       //
5278       // error 0.0000037995730, which is better than 18 bits
5279       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5280                                getF32Constant(DAG, 0x3c5d51ce, dl));
5281       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5282                                getF32Constant(DAG, 0x3e00685a, dl));
5283       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5284       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5285                                getF32Constant(DAG, 0x3efb6798, dl));
5286       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5287       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5288                                getF32Constant(DAG, 0x3f88d192, dl));
5289       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5290       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5291                                getF32Constant(DAG, 0x3fc4316c, dl));
5292       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5293       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5294                                     getF32Constant(DAG, 0x3f57ce70, dl));
5295     }
5296 
5297     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5298   }
5299 
5300   // No special expansion.
5301   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5302 }
5303 
5304 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5305 /// limited-precision mode.
5306 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5307                           const TargetLowering &TLI, SDNodeFlags Flags) {
5308   if (Op.getValueType() == MVT::f32 &&
5309       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5310     return getLimitedPrecisionExp2(Op, dl, DAG);
5311 
5312   // No special expansion.
5313   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5314 }
5315 
5316 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5317 /// limited-precision mode with x == 10.0f.
5318 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5319                          SelectionDAG &DAG, const TargetLowering &TLI,
5320                          SDNodeFlags Flags) {
5321   bool IsExp10 = false;
5322   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5323       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5324     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5325       APFloat Ten(10.0f);
5326       IsExp10 = LHSC->isExactlyValue(Ten);
5327     }
5328   }
5329 
5330   // TODO: What fast-math-flags should be set on the FMUL node?
5331   if (IsExp10) {
5332     // Put the exponent in the right bit position for later addition to the
5333     // final result:
5334     //
5335     //   #define LOG2OF10 3.3219281f
5336     //   t0 = Op * LOG2OF10;
5337     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5338                              getF32Constant(DAG, 0x40549a78, dl));
5339     return getLimitedPrecisionExp2(t0, dl, DAG);
5340   }
5341 
5342   // No special expansion.
5343   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5344 }
5345 
5346 /// ExpandPowI - Expand a llvm.powi intrinsic.
5347 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5348                           SelectionDAG &DAG) {
5349   // If RHS is a constant, we can expand this out to a multiplication tree,
5350   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5351   // optimizing for size, we only want to do this if the expansion would produce
5352   // a small number of multiplies, otherwise we do the full expansion.
5353   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5354     // Get the exponent as a positive value.
5355     unsigned Val = RHSC->getSExtValue();
5356     if ((int)Val < 0) Val = -Val;
5357 
5358     // powi(x, 0) -> 1.0
5359     if (Val == 0)
5360       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5361 
5362     bool OptForSize = DAG.shouldOptForSize();
5363     if (!OptForSize ||
5364         // If optimizing for size, don't insert too many multiplies.
5365         // This inserts up to 5 multiplies.
5366         countPopulation(Val) + Log2_32(Val) < 7) {
5367       // We use the simple binary decomposition method to generate the multiply
5368       // sequence.  There are more optimal ways to do this (for example,
5369       // powi(x,15) generates one more multiply than it should), but this has
5370       // the benefit of being both really simple and much better than a libcall.
5371       SDValue Res;  // Logically starts equal to 1.0
5372       SDValue CurSquare = LHS;
5373       // TODO: Intrinsics should have fast-math-flags that propagate to these
5374       // nodes.
5375       while (Val) {
5376         if (Val & 1) {
5377           if (Res.getNode())
5378             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5379           else
5380             Res = CurSquare;  // 1.0*CurSquare.
5381         }
5382 
5383         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5384                                 CurSquare, CurSquare);
5385         Val >>= 1;
5386       }
5387 
5388       // If the original was negative, invert the result, producing 1/(x*x*x).
5389       if (RHSC->getSExtValue() < 0)
5390         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5391                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5392       return Res;
5393     }
5394   }
5395 
5396   // Otherwise, expand to a libcall.
5397   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5398 }
5399 
5400 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5401                             SDValue LHS, SDValue RHS, SDValue Scale,
5402                             SelectionDAG &DAG, const TargetLowering &TLI) {
5403   EVT VT = LHS.getValueType();
5404   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5405   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5406   LLVMContext &Ctx = *DAG.getContext();
5407 
5408   // If the type is legal but the operation isn't, this node might survive all
5409   // the way to operation legalization. If we end up there and we do not have
5410   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5411   // node.
5412 
5413   // Coax the legalizer into expanding the node during type legalization instead
5414   // by bumping the size by one bit. This will force it to Promote, enabling the
5415   // early expansion and avoiding the need to expand later.
5416 
5417   // We don't have to do this if Scale is 0; that can always be expanded, unless
5418   // it's a saturating signed operation. Those can experience true integer
5419   // division overflow, a case which we must avoid.
5420 
5421   // FIXME: We wouldn't have to do this (or any of the early
5422   // expansion/promotion) if it was possible to expand a libcall of an
5423   // illegal type during operation legalization. But it's not, so things
5424   // get a bit hacky.
5425   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5426   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5427       (TLI.isTypeLegal(VT) ||
5428        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5429     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5430         Opcode, VT, ScaleInt);
5431     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5432       EVT PromVT;
5433       if (VT.isScalarInteger())
5434         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5435       else if (VT.isVector()) {
5436         PromVT = VT.getVectorElementType();
5437         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5438         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5439       } else
5440         llvm_unreachable("Wrong VT for DIVFIX?");
5441       if (Signed) {
5442         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5443         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5444       } else {
5445         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5446         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5447       }
5448       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5449       // For saturating operations, we need to shift up the LHS to get the
5450       // proper saturation width, and then shift down again afterwards.
5451       if (Saturating)
5452         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5453                           DAG.getConstant(1, DL, ShiftTy));
5454       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5455       if (Saturating)
5456         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5457                           DAG.getConstant(1, DL, ShiftTy));
5458       return DAG.getZExtOrTrunc(Res, DL, VT);
5459     }
5460   }
5461 
5462   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5463 }
5464 
5465 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5466 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5467 static void
5468 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5469                      const SDValue &N) {
5470   switch (N.getOpcode()) {
5471   case ISD::CopyFromReg: {
5472     SDValue Op = N.getOperand(1);
5473     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5474                       Op.getValueType().getSizeInBits());
5475     return;
5476   }
5477   case ISD::BITCAST:
5478   case ISD::AssertZext:
5479   case ISD::AssertSext:
5480   case ISD::TRUNCATE:
5481     getUnderlyingArgRegs(Regs, N.getOperand(0));
5482     return;
5483   case ISD::BUILD_PAIR:
5484   case ISD::BUILD_VECTOR:
5485   case ISD::CONCAT_VECTORS:
5486     for (SDValue Op : N->op_values())
5487       getUnderlyingArgRegs(Regs, Op);
5488     return;
5489   default:
5490     return;
5491   }
5492 }
5493 
5494 /// If the DbgValueInst is a dbg_value of a function argument, create the
5495 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5496 /// instruction selection, they will be inserted to the entry BB.
5497 /// We don't currently support this for variadic dbg_values, as they shouldn't
5498 /// appear for function arguments or in the prologue.
5499 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5500     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5501     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5502   const Argument *Arg = dyn_cast<Argument>(V);
5503   if (!Arg)
5504     return false;
5505 
5506   MachineFunction &MF = DAG.getMachineFunction();
5507   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5508 
5509   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5510   // we've been asked to pursue.
5511   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5512                               bool Indirect) {
5513     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5514       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5515       // pointing at the VReg, which will be patched up later.
5516       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5517       auto MIB = BuildMI(MF, DL, Inst);
5518       MIB.addReg(Reg);
5519       MIB.addImm(0);
5520       MIB.addMetadata(Variable);
5521       auto *NewDIExpr = FragExpr;
5522       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5523       // the DIExpression.
5524       if (Indirect)
5525         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5526       MIB.addMetadata(NewDIExpr);
5527       return MIB;
5528     } else {
5529       // Create a completely standard DBG_VALUE.
5530       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5531       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5532     }
5533   };
5534 
5535   if (!IsDbgDeclare) {
5536     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5537     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5538     // the entry block.
5539     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5540     if (!IsInEntryBlock)
5541       return false;
5542 
5543     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5544     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5545     // variable that also is a param.
5546     //
5547     // Although, if we are at the top of the entry block already, we can still
5548     // emit using ArgDbgValue. This might catch some situations when the
5549     // dbg.value refers to an argument that isn't used in the entry block, so
5550     // any CopyToReg node would be optimized out and the only way to express
5551     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5552     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5553     // we should only emit as ArgDbgValue if the Variable is an argument to the
5554     // current function, and the dbg.value intrinsic is found in the entry
5555     // block.
5556     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5557         !DL->getInlinedAt();
5558     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5559     if (!IsInPrologue && !VariableIsFunctionInputArg)
5560       return false;
5561 
5562     // Here we assume that a function argument on IR level only can be used to
5563     // describe one input parameter on source level. If we for example have
5564     // source code like this
5565     //
5566     //    struct A { long x, y; };
5567     //    void foo(struct A a, long b) {
5568     //      ...
5569     //      b = a.x;
5570     //      ...
5571     //    }
5572     //
5573     // and IR like this
5574     //
5575     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5576     //  entry:
5577     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5578     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5579     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5580     //    ...
5581     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5582     //    ...
5583     //
5584     // then the last dbg.value is describing a parameter "b" using a value that
5585     // is an argument. But since we already has used %a1 to describe a parameter
5586     // we should not handle that last dbg.value here (that would result in an
5587     // incorrect hoisting of the DBG_VALUE to the function entry).
5588     // Notice that we allow one dbg.value per IR level argument, to accommodate
5589     // for the situation with fragments above.
5590     if (VariableIsFunctionInputArg) {
5591       unsigned ArgNo = Arg->getArgNo();
5592       if (ArgNo >= FuncInfo.DescribedArgs.size())
5593         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5594       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5595         return false;
5596       FuncInfo.DescribedArgs.set(ArgNo);
5597     }
5598   }
5599 
5600   bool IsIndirect = false;
5601   Optional<MachineOperand> Op;
5602   // Some arguments' frame index is recorded during argument lowering.
5603   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5604   if (FI != std::numeric_limits<int>::max())
5605     Op = MachineOperand::CreateFI(FI);
5606 
5607   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5608   if (!Op && N.getNode()) {
5609     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5610     Register Reg;
5611     if (ArgRegsAndSizes.size() == 1)
5612       Reg = ArgRegsAndSizes.front().first;
5613 
5614     if (Reg && Reg.isVirtual()) {
5615       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5616       Register PR = RegInfo.getLiveInPhysReg(Reg);
5617       if (PR)
5618         Reg = PR;
5619     }
5620     if (Reg) {
5621       Op = MachineOperand::CreateReg(Reg, false);
5622       IsIndirect = IsDbgDeclare;
5623     }
5624   }
5625 
5626   if (!Op && N.getNode()) {
5627     // Check if frame index is available.
5628     SDValue LCandidate = peekThroughBitcasts(N);
5629     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5630       if (FrameIndexSDNode *FINode =
5631           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5632         Op = MachineOperand::CreateFI(FINode->getIndex());
5633   }
5634 
5635   if (!Op) {
5636     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5637     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5638                                          SplitRegs) {
5639       unsigned Offset = 0;
5640       for (const auto &RegAndSize : SplitRegs) {
5641         // If the expression is already a fragment, the current register
5642         // offset+size might extend beyond the fragment. In this case, only
5643         // the register bits that are inside the fragment are relevant.
5644         int RegFragmentSizeInBits = RegAndSize.second;
5645         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5646           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5647           // The register is entirely outside the expression fragment,
5648           // so is irrelevant for debug info.
5649           if (Offset >= ExprFragmentSizeInBits)
5650             break;
5651           // The register is partially outside the expression fragment, only
5652           // the low bits within the fragment are relevant for debug info.
5653           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5654             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5655           }
5656         }
5657 
5658         auto FragmentExpr = DIExpression::createFragmentExpression(
5659             Expr, Offset, RegFragmentSizeInBits);
5660         Offset += RegAndSize.second;
5661         // If a valid fragment expression cannot be created, the variable's
5662         // correct value cannot be determined and so it is set as Undef.
5663         if (!FragmentExpr) {
5664           SDDbgValue *SDV = DAG.getConstantDbgValue(
5665               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5666           DAG.AddDbgValue(SDV, false);
5667           continue;
5668         }
5669         MachineInstr *NewMI =
5670             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
5671         FuncInfo.ArgDbgValues.push_back(NewMI);
5672       }
5673     };
5674 
5675     // Check if ValueMap has reg number.
5676     DenseMap<const Value *, Register>::const_iterator
5677       VMI = FuncInfo.ValueMap.find(V);
5678     if (VMI != FuncInfo.ValueMap.end()) {
5679       const auto &TLI = DAG.getTargetLoweringInfo();
5680       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5681                        V->getType(), None);
5682       if (RFV.occupiesMultipleRegs()) {
5683         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5684         return true;
5685       }
5686 
5687       Op = MachineOperand::CreateReg(VMI->second, false);
5688       IsIndirect = IsDbgDeclare;
5689     } else if (ArgRegsAndSizes.size() > 1) {
5690       // This was split due to the calling convention, and no virtual register
5691       // mapping exists for the value.
5692       splitMultiRegDbgValue(ArgRegsAndSizes);
5693       return true;
5694     }
5695   }
5696 
5697   if (!Op)
5698     return false;
5699 
5700   assert(Variable->isValidLocationForIntrinsic(DL) &&
5701          "Expected inlined-at fields to agree");
5702   MachineInstr *NewMI = nullptr;
5703 
5704   if (Op->isReg())
5705     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5706   else
5707     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5708                     Variable, Expr);
5709 
5710   FuncInfo.ArgDbgValues.push_back(NewMI);
5711   return true;
5712 }
5713 
5714 /// Return the appropriate SDDbgValue based on N.
5715 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5716                                              DILocalVariable *Variable,
5717                                              DIExpression *Expr,
5718                                              const DebugLoc &dl,
5719                                              unsigned DbgSDNodeOrder) {
5720   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5721     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5722     // stack slot locations.
5723     //
5724     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5725     // debug values here after optimization:
5726     //
5727     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5728     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5729     //
5730     // Both describe the direct values of their associated variables.
5731     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5732                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5733   }
5734   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5735                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5736 }
5737 
5738 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5739   switch (Intrinsic) {
5740   case Intrinsic::smul_fix:
5741     return ISD::SMULFIX;
5742   case Intrinsic::umul_fix:
5743     return ISD::UMULFIX;
5744   case Intrinsic::smul_fix_sat:
5745     return ISD::SMULFIXSAT;
5746   case Intrinsic::umul_fix_sat:
5747     return ISD::UMULFIXSAT;
5748   case Intrinsic::sdiv_fix:
5749     return ISD::SDIVFIX;
5750   case Intrinsic::udiv_fix:
5751     return ISD::UDIVFIX;
5752   case Intrinsic::sdiv_fix_sat:
5753     return ISD::SDIVFIXSAT;
5754   case Intrinsic::udiv_fix_sat:
5755     return ISD::UDIVFIXSAT;
5756   default:
5757     llvm_unreachable("Unhandled fixed point intrinsic");
5758   }
5759 }
5760 
5761 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5762                                            const char *FunctionName) {
5763   assert(FunctionName && "FunctionName must not be nullptr");
5764   SDValue Callee = DAG.getExternalSymbol(
5765       FunctionName,
5766       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5767   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5768 }
5769 
5770 /// Given a @llvm.call.preallocated.setup, return the corresponding
5771 /// preallocated call.
5772 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5773   assert(cast<CallBase>(PreallocatedSetup)
5774                  ->getCalledFunction()
5775                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5776          "expected call_preallocated_setup Value");
5777   for (auto *U : PreallocatedSetup->users()) {
5778     auto *UseCall = cast<CallBase>(U);
5779     const Function *Fn = UseCall->getCalledFunction();
5780     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5781       return UseCall;
5782     }
5783   }
5784   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5785 }
5786 
5787 /// Lower the call to the specified intrinsic function.
5788 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5789                                              unsigned Intrinsic) {
5790   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5791   SDLoc sdl = getCurSDLoc();
5792   DebugLoc dl = getCurDebugLoc();
5793   SDValue Res;
5794 
5795   SDNodeFlags Flags;
5796   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5797     Flags.copyFMF(*FPOp);
5798 
5799   switch (Intrinsic) {
5800   default:
5801     // By default, turn this into a target intrinsic node.
5802     visitTargetIntrinsic(I, Intrinsic);
5803     return;
5804   case Intrinsic::vscale: {
5805     match(&I, m_VScale(DAG.getDataLayout()));
5806     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5807     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5808     return;
5809   }
5810   case Intrinsic::vastart:  visitVAStart(I); return;
5811   case Intrinsic::vaend:    visitVAEnd(I); return;
5812   case Intrinsic::vacopy:   visitVACopy(I); return;
5813   case Intrinsic::returnaddress:
5814     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5815                              TLI.getPointerTy(DAG.getDataLayout()),
5816                              getValue(I.getArgOperand(0))));
5817     return;
5818   case Intrinsic::addressofreturnaddress:
5819     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5820                              TLI.getPointerTy(DAG.getDataLayout())));
5821     return;
5822   case Intrinsic::sponentry:
5823     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5824                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5825     return;
5826   case Intrinsic::frameaddress:
5827     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5828                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5829                              getValue(I.getArgOperand(0))));
5830     return;
5831   case Intrinsic::read_volatile_register:
5832   case Intrinsic::read_register: {
5833     Value *Reg = I.getArgOperand(0);
5834     SDValue Chain = getRoot();
5835     SDValue RegName =
5836         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5837     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5838     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5839       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5840     setValue(&I, Res);
5841     DAG.setRoot(Res.getValue(1));
5842     return;
5843   }
5844   case Intrinsic::write_register: {
5845     Value *Reg = I.getArgOperand(0);
5846     Value *RegValue = I.getArgOperand(1);
5847     SDValue Chain = getRoot();
5848     SDValue RegName =
5849         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5850     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5851                             RegName, getValue(RegValue)));
5852     return;
5853   }
5854   case Intrinsic::memcpy: {
5855     const auto &MCI = cast<MemCpyInst>(I);
5856     SDValue Op1 = getValue(I.getArgOperand(0));
5857     SDValue Op2 = getValue(I.getArgOperand(1));
5858     SDValue Op3 = getValue(I.getArgOperand(2));
5859     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5860     Align DstAlign = MCI.getDestAlign().valueOrOne();
5861     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5862     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5863     bool isVol = MCI.isVolatile();
5864     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5865     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5866     // node.
5867     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5868     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5869                                /* AlwaysInline */ false, isTC,
5870                                MachinePointerInfo(I.getArgOperand(0)),
5871                                MachinePointerInfo(I.getArgOperand(1)),
5872                                I.getAAMetadata());
5873     updateDAGForMaybeTailCall(MC);
5874     return;
5875   }
5876   case Intrinsic::memcpy_inline: {
5877     const auto &MCI = cast<MemCpyInlineInst>(I);
5878     SDValue Dst = getValue(I.getArgOperand(0));
5879     SDValue Src = getValue(I.getArgOperand(1));
5880     SDValue Size = getValue(I.getArgOperand(2));
5881     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5882     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5883     Align DstAlign = MCI.getDestAlign().valueOrOne();
5884     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5885     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5886     bool isVol = MCI.isVolatile();
5887     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5888     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5889     // node.
5890     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5891                                /* AlwaysInline */ true, isTC,
5892                                MachinePointerInfo(I.getArgOperand(0)),
5893                                MachinePointerInfo(I.getArgOperand(1)),
5894                                I.getAAMetadata());
5895     updateDAGForMaybeTailCall(MC);
5896     return;
5897   }
5898   case Intrinsic::memset: {
5899     const auto &MSI = cast<MemSetInst>(I);
5900     SDValue Op1 = getValue(I.getArgOperand(0));
5901     SDValue Op2 = getValue(I.getArgOperand(1));
5902     SDValue Op3 = getValue(I.getArgOperand(2));
5903     // @llvm.memset defines 0 and 1 to both mean no alignment.
5904     Align Alignment = MSI.getDestAlign().valueOrOne();
5905     bool isVol = MSI.isVolatile();
5906     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5907     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5908     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5909                                MachinePointerInfo(I.getArgOperand(0)),
5910                                I.getAAMetadata());
5911     updateDAGForMaybeTailCall(MS);
5912     return;
5913   }
5914   case Intrinsic::memmove: {
5915     const auto &MMI = cast<MemMoveInst>(I);
5916     SDValue Op1 = getValue(I.getArgOperand(0));
5917     SDValue Op2 = getValue(I.getArgOperand(1));
5918     SDValue Op3 = getValue(I.getArgOperand(2));
5919     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5920     Align DstAlign = MMI.getDestAlign().valueOrOne();
5921     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5922     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5923     bool isVol = MMI.isVolatile();
5924     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5925     // FIXME: Support passing different dest/src alignments to the memmove DAG
5926     // node.
5927     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5928     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5929                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5930                                 MachinePointerInfo(I.getArgOperand(1)),
5931                                 I.getAAMetadata());
5932     updateDAGForMaybeTailCall(MM);
5933     return;
5934   }
5935   case Intrinsic::memcpy_element_unordered_atomic: {
5936     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5937     SDValue Dst = getValue(MI.getRawDest());
5938     SDValue Src = getValue(MI.getRawSource());
5939     SDValue Length = getValue(MI.getLength());
5940 
5941     unsigned DstAlign = MI.getDestAlignment();
5942     unsigned SrcAlign = MI.getSourceAlignment();
5943     Type *LengthTy = MI.getLength()->getType();
5944     unsigned ElemSz = MI.getElementSizeInBytes();
5945     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5946     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5947                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5948                                      MachinePointerInfo(MI.getRawDest()),
5949                                      MachinePointerInfo(MI.getRawSource()));
5950     updateDAGForMaybeTailCall(MC);
5951     return;
5952   }
5953   case Intrinsic::memmove_element_unordered_atomic: {
5954     auto &MI = cast<AtomicMemMoveInst>(I);
5955     SDValue Dst = getValue(MI.getRawDest());
5956     SDValue Src = getValue(MI.getRawSource());
5957     SDValue Length = getValue(MI.getLength());
5958 
5959     unsigned DstAlign = MI.getDestAlignment();
5960     unsigned SrcAlign = MI.getSourceAlignment();
5961     Type *LengthTy = MI.getLength()->getType();
5962     unsigned ElemSz = MI.getElementSizeInBytes();
5963     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5964     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5965                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5966                                       MachinePointerInfo(MI.getRawDest()),
5967                                       MachinePointerInfo(MI.getRawSource()));
5968     updateDAGForMaybeTailCall(MC);
5969     return;
5970   }
5971   case Intrinsic::memset_element_unordered_atomic: {
5972     auto &MI = cast<AtomicMemSetInst>(I);
5973     SDValue Dst = getValue(MI.getRawDest());
5974     SDValue Val = getValue(MI.getValue());
5975     SDValue Length = getValue(MI.getLength());
5976 
5977     unsigned DstAlign = MI.getDestAlignment();
5978     Type *LengthTy = MI.getLength()->getType();
5979     unsigned ElemSz = MI.getElementSizeInBytes();
5980     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5981     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5982                                      LengthTy, ElemSz, isTC,
5983                                      MachinePointerInfo(MI.getRawDest()));
5984     updateDAGForMaybeTailCall(MC);
5985     return;
5986   }
5987   case Intrinsic::call_preallocated_setup: {
5988     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5989     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5990     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5991                               getRoot(), SrcValue);
5992     setValue(&I, Res);
5993     DAG.setRoot(Res);
5994     return;
5995   }
5996   case Intrinsic::call_preallocated_arg: {
5997     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5998     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5999     SDValue Ops[3];
6000     Ops[0] = getRoot();
6001     Ops[1] = SrcValue;
6002     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6003                                    MVT::i32); // arg index
6004     SDValue Res = DAG.getNode(
6005         ISD::PREALLOCATED_ARG, sdl,
6006         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6007     setValue(&I, Res);
6008     DAG.setRoot(Res.getValue(1));
6009     return;
6010   }
6011   case Intrinsic::dbg_addr:
6012   case Intrinsic::dbg_declare: {
6013     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6014     // they are non-variadic.
6015     const auto &DI = cast<DbgVariableIntrinsic>(I);
6016     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6017     DILocalVariable *Variable = DI.getVariable();
6018     DIExpression *Expression = DI.getExpression();
6019     dropDanglingDebugInfo(Variable, Expression);
6020     assert(Variable && "Missing variable");
6021     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6022                       << "\n");
6023     // Check if address has undef value.
6024     const Value *Address = DI.getVariableLocationOp(0);
6025     if (!Address || isa<UndefValue>(Address) ||
6026         (Address->use_empty() && !isa<Argument>(Address))) {
6027       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6028                         << " (bad/undef/unused-arg address)\n");
6029       return;
6030     }
6031 
6032     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6033 
6034     // Check if this variable can be described by a frame index, typically
6035     // either as a static alloca or a byval parameter.
6036     int FI = std::numeric_limits<int>::max();
6037     if (const auto *AI =
6038             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6039       if (AI->isStaticAlloca()) {
6040         auto I = FuncInfo.StaticAllocaMap.find(AI);
6041         if (I != FuncInfo.StaticAllocaMap.end())
6042           FI = I->second;
6043       }
6044     } else if (const auto *Arg = dyn_cast<Argument>(
6045                    Address->stripInBoundsConstantOffsets())) {
6046       FI = FuncInfo.getArgumentFrameIndex(Arg);
6047     }
6048 
6049     // llvm.dbg.addr is control dependent and always generates indirect
6050     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6051     // the MachineFunction variable table.
6052     if (FI != std::numeric_limits<int>::max()) {
6053       if (Intrinsic == Intrinsic::dbg_addr) {
6054         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6055             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6056             dl, SDNodeOrder);
6057         DAG.AddDbgValue(SDV, isParameter);
6058       } else {
6059         LLVM_DEBUG(dbgs() << "Skipping " << DI
6060                           << " (variable info stashed in MF side table)\n");
6061       }
6062       return;
6063     }
6064 
6065     SDValue &N = NodeMap[Address];
6066     if (!N.getNode() && isa<Argument>(Address))
6067       // Check unused arguments map.
6068       N = UnusedArgNodeMap[Address];
6069     SDDbgValue *SDV;
6070     if (N.getNode()) {
6071       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6072         Address = BCI->getOperand(0);
6073       // Parameters are handled specially.
6074       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6075       if (isParameter && FINode) {
6076         // Byval parameter. We have a frame index at this point.
6077         SDV =
6078             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6079                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6080       } else if (isa<Argument>(Address)) {
6081         // Address is an argument, so try to emit its dbg value using
6082         // virtual register info from the FuncInfo.ValueMap.
6083         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6084         return;
6085       } else {
6086         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6087                               true, dl, SDNodeOrder);
6088       }
6089       DAG.AddDbgValue(SDV, isParameter);
6090     } else {
6091       // If Address is an argument then try to emit its dbg value using
6092       // virtual register info from the FuncInfo.ValueMap.
6093       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6094                                     N)) {
6095         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6096                           << " (could not emit func-arg dbg_value)\n");
6097       }
6098     }
6099     return;
6100   }
6101   case Intrinsic::dbg_label: {
6102     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6103     DILabel *Label = DI.getLabel();
6104     assert(Label && "Missing label");
6105 
6106     SDDbgLabel *SDV;
6107     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6108     DAG.AddDbgLabel(SDV);
6109     return;
6110   }
6111   case Intrinsic::dbg_value: {
6112     const DbgValueInst &DI = cast<DbgValueInst>(I);
6113     assert(DI.getVariable() && "Missing variable");
6114 
6115     DILocalVariable *Variable = DI.getVariable();
6116     DIExpression *Expression = DI.getExpression();
6117     dropDanglingDebugInfo(Variable, Expression);
6118     SmallVector<Value *, 4> Values(DI.getValues());
6119     if (Values.empty())
6120       return;
6121 
6122     if (llvm::is_contained(Values, nullptr))
6123       return;
6124 
6125     bool IsVariadic = DI.hasArgList();
6126     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6127                           SDNodeOrder, IsVariadic))
6128       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6129     return;
6130   }
6131 
6132   case Intrinsic::eh_typeid_for: {
6133     // Find the type id for the given typeinfo.
6134     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6135     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6136     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6137     setValue(&I, Res);
6138     return;
6139   }
6140 
6141   case Intrinsic::eh_return_i32:
6142   case Intrinsic::eh_return_i64:
6143     DAG.getMachineFunction().setCallsEHReturn(true);
6144     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6145                             MVT::Other,
6146                             getControlRoot(),
6147                             getValue(I.getArgOperand(0)),
6148                             getValue(I.getArgOperand(1))));
6149     return;
6150   case Intrinsic::eh_unwind_init:
6151     DAG.getMachineFunction().setCallsUnwindInit(true);
6152     return;
6153   case Intrinsic::eh_dwarf_cfa:
6154     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6155                              TLI.getPointerTy(DAG.getDataLayout()),
6156                              getValue(I.getArgOperand(0))));
6157     return;
6158   case Intrinsic::eh_sjlj_callsite: {
6159     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6160     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6161     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6162     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6163 
6164     MMI.setCurrentCallSite(CI->getZExtValue());
6165     return;
6166   }
6167   case Intrinsic::eh_sjlj_functioncontext: {
6168     // Get and store the index of the function context.
6169     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6170     AllocaInst *FnCtx =
6171       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6172     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6173     MFI.setFunctionContextIndex(FI);
6174     return;
6175   }
6176   case Intrinsic::eh_sjlj_setjmp: {
6177     SDValue Ops[2];
6178     Ops[0] = getRoot();
6179     Ops[1] = getValue(I.getArgOperand(0));
6180     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6181                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6182     setValue(&I, Op.getValue(0));
6183     DAG.setRoot(Op.getValue(1));
6184     return;
6185   }
6186   case Intrinsic::eh_sjlj_longjmp:
6187     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6188                             getRoot(), getValue(I.getArgOperand(0))));
6189     return;
6190   case Intrinsic::eh_sjlj_setup_dispatch:
6191     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6192                             getRoot()));
6193     return;
6194   case Intrinsic::masked_gather:
6195     visitMaskedGather(I);
6196     return;
6197   case Intrinsic::masked_load:
6198     visitMaskedLoad(I);
6199     return;
6200   case Intrinsic::masked_scatter:
6201     visitMaskedScatter(I);
6202     return;
6203   case Intrinsic::masked_store:
6204     visitMaskedStore(I);
6205     return;
6206   case Intrinsic::masked_expandload:
6207     visitMaskedLoad(I, true /* IsExpanding */);
6208     return;
6209   case Intrinsic::masked_compressstore:
6210     visitMaskedStore(I, true /* IsCompressing */);
6211     return;
6212   case Intrinsic::powi:
6213     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6214                             getValue(I.getArgOperand(1)), DAG));
6215     return;
6216   case Intrinsic::log:
6217     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6218     return;
6219   case Intrinsic::log2:
6220     setValue(&I,
6221              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6222     return;
6223   case Intrinsic::log10:
6224     setValue(&I,
6225              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6226     return;
6227   case Intrinsic::exp:
6228     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6229     return;
6230   case Intrinsic::exp2:
6231     setValue(&I,
6232              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6233     return;
6234   case Intrinsic::pow:
6235     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6236                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6237     return;
6238   case Intrinsic::sqrt:
6239   case Intrinsic::fabs:
6240   case Intrinsic::sin:
6241   case Intrinsic::cos:
6242   case Intrinsic::floor:
6243   case Intrinsic::ceil:
6244   case Intrinsic::trunc:
6245   case Intrinsic::rint:
6246   case Intrinsic::nearbyint:
6247   case Intrinsic::round:
6248   case Intrinsic::roundeven:
6249   case Intrinsic::canonicalize: {
6250     unsigned Opcode;
6251     switch (Intrinsic) {
6252     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6253     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6254     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6255     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6256     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6257     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6258     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6259     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6260     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6261     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6262     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6263     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6264     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6265     }
6266 
6267     setValue(&I, DAG.getNode(Opcode, sdl,
6268                              getValue(I.getArgOperand(0)).getValueType(),
6269                              getValue(I.getArgOperand(0)), Flags));
6270     return;
6271   }
6272   case Intrinsic::lround:
6273   case Intrinsic::llround:
6274   case Intrinsic::lrint:
6275   case Intrinsic::llrint: {
6276     unsigned Opcode;
6277     switch (Intrinsic) {
6278     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6279     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6280     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6281     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6282     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6283     }
6284 
6285     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6286     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6287                              getValue(I.getArgOperand(0))));
6288     return;
6289   }
6290   case Intrinsic::minnum:
6291     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6292                              getValue(I.getArgOperand(0)).getValueType(),
6293                              getValue(I.getArgOperand(0)),
6294                              getValue(I.getArgOperand(1)), Flags));
6295     return;
6296   case Intrinsic::maxnum:
6297     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6298                              getValue(I.getArgOperand(0)).getValueType(),
6299                              getValue(I.getArgOperand(0)),
6300                              getValue(I.getArgOperand(1)), Flags));
6301     return;
6302   case Intrinsic::minimum:
6303     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6304                              getValue(I.getArgOperand(0)).getValueType(),
6305                              getValue(I.getArgOperand(0)),
6306                              getValue(I.getArgOperand(1)), Flags));
6307     return;
6308   case Intrinsic::maximum:
6309     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6310                              getValue(I.getArgOperand(0)).getValueType(),
6311                              getValue(I.getArgOperand(0)),
6312                              getValue(I.getArgOperand(1)), Flags));
6313     return;
6314   case Intrinsic::copysign:
6315     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6316                              getValue(I.getArgOperand(0)).getValueType(),
6317                              getValue(I.getArgOperand(0)),
6318                              getValue(I.getArgOperand(1)), Flags));
6319     return;
6320   case Intrinsic::arithmetic_fence: {
6321     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6322                              getValue(I.getArgOperand(0)).getValueType(),
6323                              getValue(I.getArgOperand(0)), Flags));
6324     return;
6325   }
6326   case Intrinsic::fma:
6327     setValue(&I, DAG.getNode(
6328                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6329                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6330                      getValue(I.getArgOperand(2)), Flags));
6331     return;
6332 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6333   case Intrinsic::INTRINSIC:
6334 #include "llvm/IR/ConstrainedOps.def"
6335     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6336     return;
6337 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6338 #include "llvm/IR/VPIntrinsics.def"
6339     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6340     return;
6341   case Intrinsic::fmuladd: {
6342     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6343     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6344         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6345       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6346                                getValue(I.getArgOperand(0)).getValueType(),
6347                                getValue(I.getArgOperand(0)),
6348                                getValue(I.getArgOperand(1)),
6349                                getValue(I.getArgOperand(2)), Flags));
6350     } else {
6351       // TODO: Intrinsic calls should have fast-math-flags.
6352       SDValue Mul = DAG.getNode(
6353           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6354           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6355       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6356                                 getValue(I.getArgOperand(0)).getValueType(),
6357                                 Mul, getValue(I.getArgOperand(2)), Flags);
6358       setValue(&I, Add);
6359     }
6360     return;
6361   }
6362   case Intrinsic::convert_to_fp16:
6363     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6364                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6365                                          getValue(I.getArgOperand(0)),
6366                                          DAG.getTargetConstant(0, sdl,
6367                                                                MVT::i32))));
6368     return;
6369   case Intrinsic::convert_from_fp16:
6370     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6371                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6372                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6373                                          getValue(I.getArgOperand(0)))));
6374     return;
6375   case Intrinsic::fptosi_sat: {
6376     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6377     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6378                              getValue(I.getArgOperand(0)),
6379                              DAG.getValueType(VT.getScalarType())));
6380     return;
6381   }
6382   case Intrinsic::fptoui_sat: {
6383     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6384     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6385                              getValue(I.getArgOperand(0)),
6386                              DAG.getValueType(VT.getScalarType())));
6387     return;
6388   }
6389   case Intrinsic::set_rounding:
6390     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6391                       {getRoot(), getValue(I.getArgOperand(0))});
6392     setValue(&I, Res);
6393     DAG.setRoot(Res.getValue(0));
6394     return;
6395   case Intrinsic::pcmarker: {
6396     SDValue Tmp = getValue(I.getArgOperand(0));
6397     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6398     return;
6399   }
6400   case Intrinsic::readcyclecounter: {
6401     SDValue Op = getRoot();
6402     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6403                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6404     setValue(&I, Res);
6405     DAG.setRoot(Res.getValue(1));
6406     return;
6407   }
6408   case Intrinsic::bitreverse:
6409     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6410                              getValue(I.getArgOperand(0)).getValueType(),
6411                              getValue(I.getArgOperand(0))));
6412     return;
6413   case Intrinsic::bswap:
6414     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6415                              getValue(I.getArgOperand(0)).getValueType(),
6416                              getValue(I.getArgOperand(0))));
6417     return;
6418   case Intrinsic::cttz: {
6419     SDValue Arg = getValue(I.getArgOperand(0));
6420     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6421     EVT Ty = Arg.getValueType();
6422     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6423                              sdl, Ty, Arg));
6424     return;
6425   }
6426   case Intrinsic::ctlz: {
6427     SDValue Arg = getValue(I.getArgOperand(0));
6428     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6429     EVT Ty = Arg.getValueType();
6430     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6431                              sdl, Ty, Arg));
6432     return;
6433   }
6434   case Intrinsic::ctpop: {
6435     SDValue Arg = getValue(I.getArgOperand(0));
6436     EVT Ty = Arg.getValueType();
6437     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6438     return;
6439   }
6440   case Intrinsic::fshl:
6441   case Intrinsic::fshr: {
6442     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6443     SDValue X = getValue(I.getArgOperand(0));
6444     SDValue Y = getValue(I.getArgOperand(1));
6445     SDValue Z = getValue(I.getArgOperand(2));
6446     EVT VT = X.getValueType();
6447 
6448     if (X == Y) {
6449       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6450       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6451     } else {
6452       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6453       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6454     }
6455     return;
6456   }
6457   case Intrinsic::sadd_sat: {
6458     SDValue Op1 = getValue(I.getArgOperand(0));
6459     SDValue Op2 = getValue(I.getArgOperand(1));
6460     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6461     return;
6462   }
6463   case Intrinsic::uadd_sat: {
6464     SDValue Op1 = getValue(I.getArgOperand(0));
6465     SDValue Op2 = getValue(I.getArgOperand(1));
6466     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6467     return;
6468   }
6469   case Intrinsic::ssub_sat: {
6470     SDValue Op1 = getValue(I.getArgOperand(0));
6471     SDValue Op2 = getValue(I.getArgOperand(1));
6472     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6473     return;
6474   }
6475   case Intrinsic::usub_sat: {
6476     SDValue Op1 = getValue(I.getArgOperand(0));
6477     SDValue Op2 = getValue(I.getArgOperand(1));
6478     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6479     return;
6480   }
6481   case Intrinsic::sshl_sat: {
6482     SDValue Op1 = getValue(I.getArgOperand(0));
6483     SDValue Op2 = getValue(I.getArgOperand(1));
6484     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6485     return;
6486   }
6487   case Intrinsic::ushl_sat: {
6488     SDValue Op1 = getValue(I.getArgOperand(0));
6489     SDValue Op2 = getValue(I.getArgOperand(1));
6490     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6491     return;
6492   }
6493   case Intrinsic::smul_fix:
6494   case Intrinsic::umul_fix:
6495   case Intrinsic::smul_fix_sat:
6496   case Intrinsic::umul_fix_sat: {
6497     SDValue Op1 = getValue(I.getArgOperand(0));
6498     SDValue Op2 = getValue(I.getArgOperand(1));
6499     SDValue Op3 = getValue(I.getArgOperand(2));
6500     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6501                              Op1.getValueType(), Op1, Op2, Op3));
6502     return;
6503   }
6504   case Intrinsic::sdiv_fix:
6505   case Intrinsic::udiv_fix:
6506   case Intrinsic::sdiv_fix_sat:
6507   case Intrinsic::udiv_fix_sat: {
6508     SDValue Op1 = getValue(I.getArgOperand(0));
6509     SDValue Op2 = getValue(I.getArgOperand(1));
6510     SDValue Op3 = getValue(I.getArgOperand(2));
6511     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6512                               Op1, Op2, Op3, DAG, TLI));
6513     return;
6514   }
6515   case Intrinsic::smax: {
6516     SDValue Op1 = getValue(I.getArgOperand(0));
6517     SDValue Op2 = getValue(I.getArgOperand(1));
6518     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6519     return;
6520   }
6521   case Intrinsic::smin: {
6522     SDValue Op1 = getValue(I.getArgOperand(0));
6523     SDValue Op2 = getValue(I.getArgOperand(1));
6524     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6525     return;
6526   }
6527   case Intrinsic::umax: {
6528     SDValue Op1 = getValue(I.getArgOperand(0));
6529     SDValue Op2 = getValue(I.getArgOperand(1));
6530     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6531     return;
6532   }
6533   case Intrinsic::umin: {
6534     SDValue Op1 = getValue(I.getArgOperand(0));
6535     SDValue Op2 = getValue(I.getArgOperand(1));
6536     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6537     return;
6538   }
6539   case Intrinsic::abs: {
6540     // TODO: Preserve "int min is poison" arg in SDAG?
6541     SDValue Op1 = getValue(I.getArgOperand(0));
6542     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6543     return;
6544   }
6545   case Intrinsic::stacksave: {
6546     SDValue Op = getRoot();
6547     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6548     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6549     setValue(&I, Res);
6550     DAG.setRoot(Res.getValue(1));
6551     return;
6552   }
6553   case Intrinsic::stackrestore:
6554     Res = getValue(I.getArgOperand(0));
6555     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6556     return;
6557   case Intrinsic::get_dynamic_area_offset: {
6558     SDValue Op = getRoot();
6559     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6560     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6561     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6562     // target.
6563     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6564       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6565                          " intrinsic!");
6566     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6567                       Op);
6568     DAG.setRoot(Op);
6569     setValue(&I, Res);
6570     return;
6571   }
6572   case Intrinsic::stackguard: {
6573     MachineFunction &MF = DAG.getMachineFunction();
6574     const Module &M = *MF.getFunction().getParent();
6575     SDValue Chain = getRoot();
6576     if (TLI.useLoadStackGuardNode()) {
6577       Res = getLoadStackGuard(DAG, sdl, Chain);
6578     } else {
6579       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6580       const Value *Global = TLI.getSDagStackGuard(M);
6581       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6582       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6583                         MachinePointerInfo(Global, 0), Align,
6584                         MachineMemOperand::MOVolatile);
6585     }
6586     if (TLI.useStackGuardXorFP())
6587       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6588     DAG.setRoot(Chain);
6589     setValue(&I, Res);
6590     return;
6591   }
6592   case Intrinsic::stackprotector: {
6593     // Emit code into the DAG to store the stack guard onto the stack.
6594     MachineFunction &MF = DAG.getMachineFunction();
6595     MachineFrameInfo &MFI = MF.getFrameInfo();
6596     SDValue Src, Chain = getRoot();
6597 
6598     if (TLI.useLoadStackGuardNode())
6599       Src = getLoadStackGuard(DAG, sdl, Chain);
6600     else
6601       Src = getValue(I.getArgOperand(0));   // The guard's value.
6602 
6603     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6604 
6605     int FI = FuncInfo.StaticAllocaMap[Slot];
6606     MFI.setStackProtectorIndex(FI);
6607     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6608 
6609     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6610 
6611     // Store the stack protector onto the stack.
6612     Res = DAG.getStore(
6613         Chain, sdl, Src, FIN,
6614         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6615         MaybeAlign(), MachineMemOperand::MOVolatile);
6616     setValue(&I, Res);
6617     DAG.setRoot(Res);
6618     return;
6619   }
6620   case Intrinsic::objectsize:
6621     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6622 
6623   case Intrinsic::is_constant:
6624     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6625 
6626   case Intrinsic::annotation:
6627   case Intrinsic::ptr_annotation:
6628   case Intrinsic::launder_invariant_group:
6629   case Intrinsic::strip_invariant_group:
6630     // Drop the intrinsic, but forward the value
6631     setValue(&I, getValue(I.getOperand(0)));
6632     return;
6633 
6634   case Intrinsic::assume:
6635   case Intrinsic::experimental_noalias_scope_decl:
6636   case Intrinsic::var_annotation:
6637   case Intrinsic::sideeffect:
6638     // Discard annotate attributes, noalias scope declarations, assumptions, and
6639     // artificial side-effects.
6640     return;
6641 
6642   case Intrinsic::codeview_annotation: {
6643     // Emit a label associated with this metadata.
6644     MachineFunction &MF = DAG.getMachineFunction();
6645     MCSymbol *Label =
6646         MF.getMMI().getContext().createTempSymbol("annotation", true);
6647     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6648     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6649     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6650     DAG.setRoot(Res);
6651     return;
6652   }
6653 
6654   case Intrinsic::init_trampoline: {
6655     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6656 
6657     SDValue Ops[6];
6658     Ops[0] = getRoot();
6659     Ops[1] = getValue(I.getArgOperand(0));
6660     Ops[2] = getValue(I.getArgOperand(1));
6661     Ops[3] = getValue(I.getArgOperand(2));
6662     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6663     Ops[5] = DAG.getSrcValue(F);
6664 
6665     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6666 
6667     DAG.setRoot(Res);
6668     return;
6669   }
6670   case Intrinsic::adjust_trampoline:
6671     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6672                              TLI.getPointerTy(DAG.getDataLayout()),
6673                              getValue(I.getArgOperand(0))));
6674     return;
6675   case Intrinsic::gcroot: {
6676     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6677            "only valid in functions with gc specified, enforced by Verifier");
6678     assert(GFI && "implied by previous");
6679     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6680     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6681 
6682     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6683     GFI->addStackRoot(FI->getIndex(), TypeMap);
6684     return;
6685   }
6686   case Intrinsic::gcread:
6687   case Intrinsic::gcwrite:
6688     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6689   case Intrinsic::flt_rounds:
6690     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6691     setValue(&I, Res);
6692     DAG.setRoot(Res.getValue(1));
6693     return;
6694 
6695   case Intrinsic::expect:
6696     // Just replace __builtin_expect(exp, c) with EXP.
6697     setValue(&I, getValue(I.getArgOperand(0)));
6698     return;
6699 
6700   case Intrinsic::ubsantrap:
6701   case Intrinsic::debugtrap:
6702   case Intrinsic::trap: {
6703     StringRef TrapFuncName =
6704         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6705     if (TrapFuncName.empty()) {
6706       switch (Intrinsic) {
6707       case Intrinsic::trap:
6708         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6709         break;
6710       case Intrinsic::debugtrap:
6711         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6712         break;
6713       case Intrinsic::ubsantrap:
6714         DAG.setRoot(DAG.getNode(
6715             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6716             DAG.getTargetConstant(
6717                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6718                 MVT::i32)));
6719         break;
6720       default: llvm_unreachable("unknown trap intrinsic");
6721       }
6722       return;
6723     }
6724     TargetLowering::ArgListTy Args;
6725     if (Intrinsic == Intrinsic::ubsantrap) {
6726       Args.push_back(TargetLoweringBase::ArgListEntry());
6727       Args[0].Val = I.getArgOperand(0);
6728       Args[0].Node = getValue(Args[0].Val);
6729       Args[0].Ty = Args[0].Val->getType();
6730     }
6731 
6732     TargetLowering::CallLoweringInfo CLI(DAG);
6733     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6734         CallingConv::C, I.getType(),
6735         DAG.getExternalSymbol(TrapFuncName.data(),
6736                               TLI.getPointerTy(DAG.getDataLayout())),
6737         std::move(Args));
6738 
6739     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6740     DAG.setRoot(Result.second);
6741     return;
6742   }
6743 
6744   case Intrinsic::uadd_with_overflow:
6745   case Intrinsic::sadd_with_overflow:
6746   case Intrinsic::usub_with_overflow:
6747   case Intrinsic::ssub_with_overflow:
6748   case Intrinsic::umul_with_overflow:
6749   case Intrinsic::smul_with_overflow: {
6750     ISD::NodeType Op;
6751     switch (Intrinsic) {
6752     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6753     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6754     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6755     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6756     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6757     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6758     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6759     }
6760     SDValue Op1 = getValue(I.getArgOperand(0));
6761     SDValue Op2 = getValue(I.getArgOperand(1));
6762 
6763     EVT ResultVT = Op1.getValueType();
6764     EVT OverflowVT = MVT::i1;
6765     if (ResultVT.isVector())
6766       OverflowVT = EVT::getVectorVT(
6767           *Context, OverflowVT, ResultVT.getVectorElementCount());
6768 
6769     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6770     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6771     return;
6772   }
6773   case Intrinsic::prefetch: {
6774     SDValue Ops[5];
6775     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6776     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6777     Ops[0] = DAG.getRoot();
6778     Ops[1] = getValue(I.getArgOperand(0));
6779     Ops[2] = getValue(I.getArgOperand(1));
6780     Ops[3] = getValue(I.getArgOperand(2));
6781     Ops[4] = getValue(I.getArgOperand(3));
6782     SDValue Result = DAG.getMemIntrinsicNode(
6783         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6784         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6785         /* align */ None, Flags);
6786 
6787     // Chain the prefetch in parallell with any pending loads, to stay out of
6788     // the way of later optimizations.
6789     PendingLoads.push_back(Result);
6790     Result = getRoot();
6791     DAG.setRoot(Result);
6792     return;
6793   }
6794   case Intrinsic::lifetime_start:
6795   case Intrinsic::lifetime_end: {
6796     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6797     // Stack coloring is not enabled in O0, discard region information.
6798     if (TM.getOptLevel() == CodeGenOpt::None)
6799       return;
6800 
6801     const int64_t ObjectSize =
6802         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6803     Value *const ObjectPtr = I.getArgOperand(1);
6804     SmallVector<const Value *, 4> Allocas;
6805     getUnderlyingObjects(ObjectPtr, Allocas);
6806 
6807     for (const Value *Alloca : Allocas) {
6808       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6809 
6810       // Could not find an Alloca.
6811       if (!LifetimeObject)
6812         continue;
6813 
6814       // First check that the Alloca is static, otherwise it won't have a
6815       // valid frame index.
6816       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6817       if (SI == FuncInfo.StaticAllocaMap.end())
6818         return;
6819 
6820       const int FrameIndex = SI->second;
6821       int64_t Offset;
6822       if (GetPointerBaseWithConstantOffset(
6823               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6824         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6825       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6826                                 Offset);
6827       DAG.setRoot(Res);
6828     }
6829     return;
6830   }
6831   case Intrinsic::pseudoprobe: {
6832     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6833     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6834     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6835     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6836     DAG.setRoot(Res);
6837     return;
6838   }
6839   case Intrinsic::invariant_start:
6840     // Discard region information.
6841     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6842     return;
6843   case Intrinsic::invariant_end:
6844     // Discard region information.
6845     return;
6846   case Intrinsic::clear_cache:
6847     /// FunctionName may be null.
6848     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6849       lowerCallToExternalSymbol(I, FunctionName);
6850     return;
6851   case Intrinsic::donothing:
6852   case Intrinsic::seh_try_begin:
6853   case Intrinsic::seh_scope_begin:
6854   case Intrinsic::seh_try_end:
6855   case Intrinsic::seh_scope_end:
6856     // ignore
6857     return;
6858   case Intrinsic::experimental_stackmap:
6859     visitStackmap(I);
6860     return;
6861   case Intrinsic::experimental_patchpoint_void:
6862   case Intrinsic::experimental_patchpoint_i64:
6863     visitPatchpoint(I);
6864     return;
6865   case Intrinsic::experimental_gc_statepoint:
6866     LowerStatepoint(cast<GCStatepointInst>(I));
6867     return;
6868   case Intrinsic::experimental_gc_result:
6869     visitGCResult(cast<GCResultInst>(I));
6870     return;
6871   case Intrinsic::experimental_gc_relocate:
6872     visitGCRelocate(cast<GCRelocateInst>(I));
6873     return;
6874   case Intrinsic::instrprof_increment:
6875     llvm_unreachable("instrprof failed to lower an increment");
6876   case Intrinsic::instrprof_value_profile:
6877     llvm_unreachable("instrprof failed to lower a value profiling call");
6878   case Intrinsic::localescape: {
6879     MachineFunction &MF = DAG.getMachineFunction();
6880     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6881 
6882     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6883     // is the same on all targets.
6884     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6885       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6886       if (isa<ConstantPointerNull>(Arg))
6887         continue; // Skip null pointers. They represent a hole in index space.
6888       AllocaInst *Slot = cast<AllocaInst>(Arg);
6889       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6890              "can only escape static allocas");
6891       int FI = FuncInfo.StaticAllocaMap[Slot];
6892       MCSymbol *FrameAllocSym =
6893           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6894               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6895       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6896               TII->get(TargetOpcode::LOCAL_ESCAPE))
6897           .addSym(FrameAllocSym)
6898           .addFrameIndex(FI);
6899     }
6900 
6901     return;
6902   }
6903 
6904   case Intrinsic::localrecover: {
6905     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6906     MachineFunction &MF = DAG.getMachineFunction();
6907 
6908     // Get the symbol that defines the frame offset.
6909     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6910     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6911     unsigned IdxVal =
6912         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6913     MCSymbol *FrameAllocSym =
6914         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6915             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6916 
6917     Value *FP = I.getArgOperand(1);
6918     SDValue FPVal = getValue(FP);
6919     EVT PtrVT = FPVal.getValueType();
6920 
6921     // Create a MCSymbol for the label to avoid any target lowering
6922     // that would make this PC relative.
6923     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6924     SDValue OffsetVal =
6925         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6926 
6927     // Add the offset to the FP.
6928     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6929     setValue(&I, Add);
6930 
6931     return;
6932   }
6933 
6934   case Intrinsic::eh_exceptionpointer:
6935   case Intrinsic::eh_exceptioncode: {
6936     // Get the exception pointer vreg, copy from it, and resize it to fit.
6937     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6938     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6939     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6940     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6941     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
6942     if (Intrinsic == Intrinsic::eh_exceptioncode)
6943       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
6944     setValue(&I, N);
6945     return;
6946   }
6947   case Intrinsic::xray_customevent: {
6948     // Here we want to make sure that the intrinsic behaves as if it has a
6949     // specific calling convention, and only for x86_64.
6950     // FIXME: Support other platforms later.
6951     const auto &Triple = DAG.getTarget().getTargetTriple();
6952     if (Triple.getArch() != Triple::x86_64)
6953       return;
6954 
6955     SmallVector<SDValue, 8> Ops;
6956 
6957     // We want to say that we always want the arguments in registers.
6958     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6959     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6960     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6961     SDValue Chain = getRoot();
6962     Ops.push_back(LogEntryVal);
6963     Ops.push_back(StrSizeVal);
6964     Ops.push_back(Chain);
6965 
6966     // We need to enforce the calling convention for the callsite, so that
6967     // argument ordering is enforced correctly, and that register allocation can
6968     // see that some registers may be assumed clobbered and have to preserve
6969     // them across calls to the intrinsic.
6970     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6971                                            sdl, NodeTys, Ops);
6972     SDValue patchableNode = SDValue(MN, 0);
6973     DAG.setRoot(patchableNode);
6974     setValue(&I, patchableNode);
6975     return;
6976   }
6977   case Intrinsic::xray_typedevent: {
6978     // Here we want to make sure that the intrinsic behaves as if it has a
6979     // specific calling convention, and only for x86_64.
6980     // FIXME: Support other platforms later.
6981     const auto &Triple = DAG.getTarget().getTargetTriple();
6982     if (Triple.getArch() != Triple::x86_64)
6983       return;
6984 
6985     SmallVector<SDValue, 8> Ops;
6986 
6987     // We want to say that we always want the arguments in registers.
6988     // It's unclear to me how manipulating the selection DAG here forces callers
6989     // to provide arguments in registers instead of on the stack.
6990     SDValue LogTypeId = getValue(I.getArgOperand(0));
6991     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6992     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6993     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6994     SDValue Chain = getRoot();
6995     Ops.push_back(LogTypeId);
6996     Ops.push_back(LogEntryVal);
6997     Ops.push_back(StrSizeVal);
6998     Ops.push_back(Chain);
6999 
7000     // We need to enforce the calling convention for the callsite, so that
7001     // argument ordering is enforced correctly, and that register allocation can
7002     // see that some registers may be assumed clobbered and have to preserve
7003     // them across calls to the intrinsic.
7004     MachineSDNode *MN = DAG.getMachineNode(
7005         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7006     SDValue patchableNode = SDValue(MN, 0);
7007     DAG.setRoot(patchableNode);
7008     setValue(&I, patchableNode);
7009     return;
7010   }
7011   case Intrinsic::experimental_deoptimize:
7012     LowerDeoptimizeCall(&I);
7013     return;
7014   case Intrinsic::experimental_stepvector:
7015     visitStepVector(I);
7016     return;
7017   case Intrinsic::vector_reduce_fadd:
7018   case Intrinsic::vector_reduce_fmul:
7019   case Intrinsic::vector_reduce_add:
7020   case Intrinsic::vector_reduce_mul:
7021   case Intrinsic::vector_reduce_and:
7022   case Intrinsic::vector_reduce_or:
7023   case Intrinsic::vector_reduce_xor:
7024   case Intrinsic::vector_reduce_smax:
7025   case Intrinsic::vector_reduce_smin:
7026   case Intrinsic::vector_reduce_umax:
7027   case Intrinsic::vector_reduce_umin:
7028   case Intrinsic::vector_reduce_fmax:
7029   case Intrinsic::vector_reduce_fmin:
7030     visitVectorReduce(I, Intrinsic);
7031     return;
7032 
7033   case Intrinsic::icall_branch_funnel: {
7034     SmallVector<SDValue, 16> Ops;
7035     Ops.push_back(getValue(I.getArgOperand(0)));
7036 
7037     int64_t Offset;
7038     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7039         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7040     if (!Base)
7041       report_fatal_error(
7042           "llvm.icall.branch.funnel operand must be a GlobalValue");
7043     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7044 
7045     struct BranchFunnelTarget {
7046       int64_t Offset;
7047       SDValue Target;
7048     };
7049     SmallVector<BranchFunnelTarget, 8> Targets;
7050 
7051     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7052       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7053           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7054       if (ElemBase != Base)
7055         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7056                            "to the same GlobalValue");
7057 
7058       SDValue Val = getValue(I.getArgOperand(Op + 1));
7059       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7060       if (!GA)
7061         report_fatal_error(
7062             "llvm.icall.branch.funnel operand must be a GlobalValue");
7063       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7064                                      GA->getGlobal(), sdl, Val.getValueType(),
7065                                      GA->getOffset())});
7066     }
7067     llvm::sort(Targets,
7068                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7069                  return T1.Offset < T2.Offset;
7070                });
7071 
7072     for (auto &T : Targets) {
7073       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7074       Ops.push_back(T.Target);
7075     }
7076 
7077     Ops.push_back(DAG.getRoot()); // Chain
7078     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7079                                  MVT::Other, Ops),
7080               0);
7081     DAG.setRoot(N);
7082     setValue(&I, N);
7083     HasTailCall = true;
7084     return;
7085   }
7086 
7087   case Intrinsic::wasm_landingpad_index:
7088     // Information this intrinsic contained has been transferred to
7089     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7090     // delete it now.
7091     return;
7092 
7093   case Intrinsic::aarch64_settag:
7094   case Intrinsic::aarch64_settag_zero: {
7095     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7096     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7097     SDValue Val = TSI.EmitTargetCodeForSetTag(
7098         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7099         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7100         ZeroMemory);
7101     DAG.setRoot(Val);
7102     setValue(&I, Val);
7103     return;
7104   }
7105   case Intrinsic::ptrmask: {
7106     SDValue Ptr = getValue(I.getOperand(0));
7107     SDValue Const = getValue(I.getOperand(1));
7108 
7109     EVT PtrVT = Ptr.getValueType();
7110     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7111                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7112     return;
7113   }
7114   case Intrinsic::get_active_lane_mask: {
7115     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7116     SDValue Index = getValue(I.getOperand(0));
7117     EVT ElementVT = Index.getValueType();
7118 
7119     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7120       visitTargetIntrinsic(I, Intrinsic);
7121       return;
7122     }
7123 
7124     SDValue TripCount = getValue(I.getOperand(1));
7125     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7126 
7127     SDValue VectorIndex, VectorTripCount;
7128     if (VecTy.isScalableVector()) {
7129       VectorIndex = DAG.getSplatVector(VecTy, sdl, Index);
7130       VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount);
7131     } else {
7132       VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index);
7133       VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount);
7134     }
7135     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7136     SDValue VectorInduction = DAG.getNode(
7137         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7138     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7139                                  VectorTripCount, ISD::CondCode::SETULT);
7140     setValue(&I, SetCC);
7141     return;
7142   }
7143   case Intrinsic::experimental_vector_insert: {
7144     SDValue Vec = getValue(I.getOperand(0));
7145     SDValue SubVec = getValue(I.getOperand(1));
7146     SDValue Index = getValue(I.getOperand(2));
7147 
7148     // The intrinsic's index type is i64, but the SDNode requires an index type
7149     // suitable for the target. Convert the index as required.
7150     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7151     if (Index.getValueType() != VectorIdxTy)
7152       Index = DAG.getVectorIdxConstant(
7153           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7154 
7155     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7156     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7157                              Index));
7158     return;
7159   }
7160   case Intrinsic::experimental_vector_extract: {
7161     SDValue Vec = getValue(I.getOperand(0));
7162     SDValue Index = getValue(I.getOperand(1));
7163     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7164 
7165     // The intrinsic's index type is i64, but the SDNode requires an index type
7166     // suitable for the target. Convert the index as required.
7167     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7168     if (Index.getValueType() != VectorIdxTy)
7169       Index = DAG.getVectorIdxConstant(
7170           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7171 
7172     setValue(&I,
7173              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7174     return;
7175   }
7176   case Intrinsic::experimental_vector_reverse:
7177     visitVectorReverse(I);
7178     return;
7179   case Intrinsic::experimental_vector_splice:
7180     visitVectorSplice(I);
7181     return;
7182   }
7183 }
7184 
7185 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7186     const ConstrainedFPIntrinsic &FPI) {
7187   SDLoc sdl = getCurSDLoc();
7188 
7189   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7190   SmallVector<EVT, 4> ValueVTs;
7191   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7192   ValueVTs.push_back(MVT::Other); // Out chain
7193 
7194   // We do not need to serialize constrained FP intrinsics against
7195   // each other or against (nonvolatile) loads, so they can be
7196   // chained like loads.
7197   SDValue Chain = DAG.getRoot();
7198   SmallVector<SDValue, 4> Opers;
7199   Opers.push_back(Chain);
7200   if (FPI.isUnaryOp()) {
7201     Opers.push_back(getValue(FPI.getArgOperand(0)));
7202   } else if (FPI.isTernaryOp()) {
7203     Opers.push_back(getValue(FPI.getArgOperand(0)));
7204     Opers.push_back(getValue(FPI.getArgOperand(1)));
7205     Opers.push_back(getValue(FPI.getArgOperand(2)));
7206   } else {
7207     Opers.push_back(getValue(FPI.getArgOperand(0)));
7208     Opers.push_back(getValue(FPI.getArgOperand(1)));
7209   }
7210 
7211   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7212     assert(Result.getNode()->getNumValues() == 2);
7213 
7214     // Push node to the appropriate list so that future instructions can be
7215     // chained up correctly.
7216     SDValue OutChain = Result.getValue(1);
7217     switch (EB) {
7218     case fp::ExceptionBehavior::ebIgnore:
7219       // The only reason why ebIgnore nodes still need to be chained is that
7220       // they might depend on the current rounding mode, and therefore must
7221       // not be moved across instruction that may change that mode.
7222       LLVM_FALLTHROUGH;
7223     case fp::ExceptionBehavior::ebMayTrap:
7224       // These must not be moved across calls or instructions that may change
7225       // floating-point exception masks.
7226       PendingConstrainedFP.push_back(OutChain);
7227       break;
7228     case fp::ExceptionBehavior::ebStrict:
7229       // These must not be moved across calls or instructions that may change
7230       // floating-point exception masks or read floating-point exception flags.
7231       // In addition, they cannot be optimized out even if unused.
7232       PendingConstrainedFPStrict.push_back(OutChain);
7233       break;
7234     }
7235   };
7236 
7237   SDVTList VTs = DAG.getVTList(ValueVTs);
7238   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7239 
7240   SDNodeFlags Flags;
7241   if (EB == fp::ExceptionBehavior::ebIgnore)
7242     Flags.setNoFPExcept(true);
7243 
7244   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7245     Flags.copyFMF(*FPOp);
7246 
7247   unsigned Opcode;
7248   switch (FPI.getIntrinsicID()) {
7249   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7250 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7251   case Intrinsic::INTRINSIC:                                                   \
7252     Opcode = ISD::STRICT_##DAGN;                                               \
7253     break;
7254 #include "llvm/IR/ConstrainedOps.def"
7255   case Intrinsic::experimental_constrained_fmuladd: {
7256     Opcode = ISD::STRICT_FMA;
7257     // Break fmuladd into fmul and fadd.
7258     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7259         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7260                                         ValueVTs[0])) {
7261       Opers.pop_back();
7262       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7263       pushOutChain(Mul, EB);
7264       Opcode = ISD::STRICT_FADD;
7265       Opers.clear();
7266       Opers.push_back(Mul.getValue(1));
7267       Opers.push_back(Mul.getValue(0));
7268       Opers.push_back(getValue(FPI.getArgOperand(2)));
7269     }
7270     break;
7271   }
7272   }
7273 
7274   // A few strict DAG nodes carry additional operands that are not
7275   // set up by the default code above.
7276   switch (Opcode) {
7277   default: break;
7278   case ISD::STRICT_FP_ROUND:
7279     Opers.push_back(
7280         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7281     break;
7282   case ISD::STRICT_FSETCC:
7283   case ISD::STRICT_FSETCCS: {
7284     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7285     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7286     if (TM.Options.NoNaNsFPMath)
7287       Condition = getFCmpCodeWithoutNaN(Condition);
7288     Opers.push_back(DAG.getCondCode(Condition));
7289     break;
7290   }
7291   }
7292 
7293   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7294   pushOutChain(Result, EB);
7295 
7296   SDValue FPResult = Result.getValue(0);
7297   setValue(&FPI, FPResult);
7298 }
7299 
7300 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7301   Optional<unsigned> ResOPC;
7302   switch (VPIntrin.getIntrinsicID()) {
7303 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7304 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) ResOPC = ISD::VPSD;
7305 #define END_REGISTER_VP_INTRINSIC(VPID) break;
7306 #include "llvm/IR/VPIntrinsics.def"
7307   }
7308 
7309   if (!ResOPC.hasValue())
7310     llvm_unreachable(
7311         "Inconsistency: no SDNode available for this VPIntrinsic!");
7312 
7313   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7314       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7315     if (VPIntrin.getFastMathFlags().allowReassoc())
7316       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7317                                                 : ISD::VP_REDUCE_FMUL;
7318   }
7319 
7320   return ResOPC.getValue();
7321 }
7322 
7323 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT,
7324                                             SmallVector<SDValue, 7> &OpValues,
7325                                             bool IsGather) {
7326   SDLoc DL = getCurSDLoc();
7327   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7328   Value *PtrOperand = VPIntrin.getArgOperand(0);
7329   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7330   if (!Alignment)
7331     Alignment = DAG.getEVTAlign(VT);
7332   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7333   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7334   SDValue LD;
7335   bool AddToChain = true;
7336   if (!IsGather) {
7337     // Do not serialize variable-length loads of constant memory with
7338     // anything.
7339     MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7340     AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7341     SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7342     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7343         MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7344         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7345     LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7346                        MMO, false /*IsExpanding */);
7347   } else {
7348     unsigned AS =
7349         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7350     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7351         MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7352         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7353     SDValue Base, Index, Scale;
7354     ISD::MemIndexType IndexType;
7355     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7356                                       this, VPIntrin.getParent());
7357     if (!UniformBase) {
7358       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7359       Index = getValue(PtrOperand);
7360       IndexType = ISD::SIGNED_UNSCALED;
7361       Scale =
7362           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7363     }
7364     EVT IdxVT = Index.getValueType();
7365     EVT EltTy = IdxVT.getVectorElementType();
7366     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7367       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7368       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7369     }
7370     LD = DAG.getGatherVP(
7371         DAG.getVTList(VT, MVT::Other), VT, DL,
7372         {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7373         IndexType);
7374   }
7375   if (AddToChain)
7376     PendingLoads.push_back(LD.getValue(1));
7377   setValue(&VPIntrin, LD);
7378 }
7379 
7380 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin,
7381                                               SmallVector<SDValue, 7> &OpValues,
7382                                               bool IsScatter) {
7383   SDLoc DL = getCurSDLoc();
7384   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7385   Value *PtrOperand = VPIntrin.getArgOperand(1);
7386   EVT VT = OpValues[0].getValueType();
7387   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7388   if (!Alignment)
7389     Alignment = DAG.getEVTAlign(VT);
7390   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7391   SDValue ST;
7392   if (!IsScatter) {
7393     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7394         MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7395         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7396     ST =
7397         DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], OpValues[1],
7398                        OpValues[2], OpValues[3], MMO, false /* IsTruncating */);
7399   } else {
7400     unsigned AS =
7401         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7402     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7403         MachinePointerInfo(AS), MachineMemOperand::MOStore,
7404         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7405     SDValue Base, Index, Scale;
7406     ISD::MemIndexType IndexType;
7407     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7408                                       this, VPIntrin.getParent());
7409     if (!UniformBase) {
7410       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7411       Index = getValue(PtrOperand);
7412       IndexType = ISD::SIGNED_UNSCALED;
7413       Scale =
7414           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7415     }
7416     EVT IdxVT = Index.getValueType();
7417     EVT EltTy = IdxVT.getVectorElementType();
7418     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7419       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7420       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7421     }
7422     ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7423                           {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7424                            OpValues[2], OpValues[3]},
7425                           MMO, IndexType);
7426   }
7427   DAG.setRoot(ST);
7428   setValue(&VPIntrin, ST);
7429 }
7430 
7431 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7432     const VPIntrinsic &VPIntrin) {
7433   SDLoc DL = getCurSDLoc();
7434   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7435 
7436   SmallVector<EVT, 4> ValueVTs;
7437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7438   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7439   SDVTList VTs = DAG.getVTList(ValueVTs);
7440 
7441   auto EVLParamPos =
7442       VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
7443 
7444   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7445   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7446          "Unexpected target EVL type");
7447 
7448   // Request operands.
7449   SmallVector<SDValue, 7> OpValues;
7450   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7451     auto Op = getValue(VPIntrin.getArgOperand(I));
7452     if (I == EVLParamPos)
7453       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7454     OpValues.push_back(Op);
7455   }
7456 
7457   switch (Opcode) {
7458   default: {
7459     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7460     setValue(&VPIntrin, Result);
7461     break;
7462   }
7463   case ISD::VP_LOAD:
7464   case ISD::VP_GATHER:
7465     visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues,
7466                       Opcode == ISD::VP_GATHER);
7467     break;
7468   case ISD::VP_STORE:
7469   case ISD::VP_SCATTER:
7470     visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER);
7471     break;
7472   }
7473 }
7474 
7475 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7476                                           const BasicBlock *EHPadBB,
7477                                           MCSymbol *&BeginLabel) {
7478   MachineFunction &MF = DAG.getMachineFunction();
7479   MachineModuleInfo &MMI = MF.getMMI();
7480 
7481   // Insert a label before the invoke call to mark the try range.  This can be
7482   // used to detect deletion of the invoke via the MachineModuleInfo.
7483   BeginLabel = MMI.getContext().createTempSymbol();
7484 
7485   // For SjLj, keep track of which landing pads go with which invokes
7486   // so as to maintain the ordering of pads in the LSDA.
7487   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7488   if (CallSiteIndex) {
7489     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7490     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7491 
7492     // Now that the call site is handled, stop tracking it.
7493     MMI.setCurrentCallSite(0);
7494   }
7495 
7496   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7497 }
7498 
7499 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7500                                         const BasicBlock *EHPadBB,
7501                                         MCSymbol *BeginLabel) {
7502   assert(BeginLabel && "BeginLabel should've been set");
7503 
7504   MachineFunction &MF = DAG.getMachineFunction();
7505   MachineModuleInfo &MMI = MF.getMMI();
7506 
7507   // Insert a label at the end of the invoke call to mark the try range.  This
7508   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7509   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7510   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7511 
7512   // Inform MachineModuleInfo of range.
7513   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7514   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7515   // actually use outlined funclets and their LSDA info style.
7516   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7517     assert(II && "II should've been set");
7518     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7519     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7520   } else if (!isScopedEHPersonality(Pers)) {
7521     assert(EHPadBB);
7522     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7523   }
7524 
7525   return Chain;
7526 }
7527 
7528 std::pair<SDValue, SDValue>
7529 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7530                                     const BasicBlock *EHPadBB) {
7531   MCSymbol *BeginLabel = nullptr;
7532 
7533   if (EHPadBB) {
7534     // Both PendingLoads and PendingExports must be flushed here;
7535     // this call might not return.
7536     (void)getRoot();
7537     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7538     CLI.setChain(getRoot());
7539   }
7540 
7541   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7542   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7543 
7544   assert((CLI.IsTailCall || Result.second.getNode()) &&
7545          "Non-null chain expected with non-tail call!");
7546   assert((Result.second.getNode() || !Result.first.getNode()) &&
7547          "Null value expected with tail call!");
7548 
7549   if (!Result.second.getNode()) {
7550     // As a special case, a null chain means that a tail call has been emitted
7551     // and the DAG root is already updated.
7552     HasTailCall = true;
7553 
7554     // Since there's no actual continuation from this block, nothing can be
7555     // relying on us setting vregs for them.
7556     PendingExports.clear();
7557   } else {
7558     DAG.setRoot(Result.second);
7559   }
7560 
7561   if (EHPadBB) {
7562     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7563                            BeginLabel));
7564   }
7565 
7566   return Result;
7567 }
7568 
7569 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7570                                       bool isTailCall,
7571                                       bool isMustTailCall,
7572                                       const BasicBlock *EHPadBB) {
7573   auto &DL = DAG.getDataLayout();
7574   FunctionType *FTy = CB.getFunctionType();
7575   Type *RetTy = CB.getType();
7576 
7577   TargetLowering::ArgListTy Args;
7578   Args.reserve(CB.arg_size());
7579 
7580   const Value *SwiftErrorVal = nullptr;
7581   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7582 
7583   if (isTailCall) {
7584     // Avoid emitting tail calls in functions with the disable-tail-calls
7585     // attribute.
7586     auto *Caller = CB.getParent()->getParent();
7587     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7588         "true" && !isMustTailCall)
7589       isTailCall = false;
7590 
7591     // We can't tail call inside a function with a swifterror argument. Lowering
7592     // does not support this yet. It would have to move into the swifterror
7593     // register before the call.
7594     if (TLI.supportSwiftError() &&
7595         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7596       isTailCall = false;
7597   }
7598 
7599   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7600     TargetLowering::ArgListEntry Entry;
7601     const Value *V = *I;
7602 
7603     // Skip empty types
7604     if (V->getType()->isEmptyTy())
7605       continue;
7606 
7607     SDValue ArgNode = getValue(V);
7608     Entry.Node = ArgNode; Entry.Ty = V->getType();
7609 
7610     Entry.setAttributes(&CB, I - CB.arg_begin());
7611 
7612     // Use swifterror virtual register as input to the call.
7613     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7614       SwiftErrorVal = V;
7615       // We find the virtual register for the actual swifterror argument.
7616       // Instead of using the Value, we use the virtual register instead.
7617       Entry.Node =
7618           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7619                           EVT(TLI.getPointerTy(DL)));
7620     }
7621 
7622     Args.push_back(Entry);
7623 
7624     // If we have an explicit sret argument that is an Instruction, (i.e., it
7625     // might point to function-local memory), we can't meaningfully tail-call.
7626     if (Entry.IsSRet && isa<Instruction>(V))
7627       isTailCall = false;
7628   }
7629 
7630   // If call site has a cfguardtarget operand bundle, create and add an
7631   // additional ArgListEntry.
7632   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7633     TargetLowering::ArgListEntry Entry;
7634     Value *V = Bundle->Inputs[0];
7635     SDValue ArgNode = getValue(V);
7636     Entry.Node = ArgNode;
7637     Entry.Ty = V->getType();
7638     Entry.IsCFGuardTarget = true;
7639     Args.push_back(Entry);
7640   }
7641 
7642   // Check if target-independent constraints permit a tail call here.
7643   // Target-dependent constraints are checked within TLI->LowerCallTo.
7644   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7645     isTailCall = false;
7646 
7647   // Disable tail calls if there is an swifterror argument. Targets have not
7648   // been updated to support tail calls.
7649   if (TLI.supportSwiftError() && SwiftErrorVal)
7650     isTailCall = false;
7651 
7652   TargetLowering::CallLoweringInfo CLI(DAG);
7653   CLI.setDebugLoc(getCurSDLoc())
7654       .setChain(getRoot())
7655       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7656       .setTailCall(isTailCall)
7657       .setConvergent(CB.isConvergent())
7658       .setIsPreallocated(
7659           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7660   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7661 
7662   if (Result.first.getNode()) {
7663     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7664     setValue(&CB, Result.first);
7665   }
7666 
7667   // The last element of CLI.InVals has the SDValue for swifterror return.
7668   // Here we copy it to a virtual register and update SwiftErrorMap for
7669   // book-keeping.
7670   if (SwiftErrorVal && TLI.supportSwiftError()) {
7671     // Get the last element of InVals.
7672     SDValue Src = CLI.InVals.back();
7673     Register VReg =
7674         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7675     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7676     DAG.setRoot(CopyNode);
7677   }
7678 }
7679 
7680 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7681                              SelectionDAGBuilder &Builder) {
7682   // Check to see if this load can be trivially constant folded, e.g. if the
7683   // input is from a string literal.
7684   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7685     // Cast pointer to the type we really want to load.
7686     Type *LoadTy =
7687         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7688     if (LoadVT.isVector())
7689       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7690 
7691     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7692                                          PointerType::getUnqual(LoadTy));
7693 
7694     if (const Constant *LoadCst =
7695             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7696                                          LoadTy, Builder.DAG.getDataLayout()))
7697       return Builder.getValue(LoadCst);
7698   }
7699 
7700   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7701   // still constant memory, the input chain can be the entry node.
7702   SDValue Root;
7703   bool ConstantMemory = false;
7704 
7705   // Do not serialize (non-volatile) loads of constant memory with anything.
7706   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7707     Root = Builder.DAG.getEntryNode();
7708     ConstantMemory = true;
7709   } else {
7710     // Do not serialize non-volatile loads against each other.
7711     Root = Builder.DAG.getRoot();
7712   }
7713 
7714   SDValue Ptr = Builder.getValue(PtrVal);
7715   SDValue LoadVal =
7716       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7717                           MachinePointerInfo(PtrVal), Align(1));
7718 
7719   if (!ConstantMemory)
7720     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7721   return LoadVal;
7722 }
7723 
7724 /// Record the value for an instruction that produces an integer result,
7725 /// converting the type where necessary.
7726 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7727                                                   SDValue Value,
7728                                                   bool IsSigned) {
7729   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7730                                                     I.getType(), true);
7731   if (IsSigned)
7732     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7733   else
7734     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7735   setValue(&I, Value);
7736 }
7737 
7738 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7739 /// true and lower it. Otherwise return false, and it will be lowered like a
7740 /// normal call.
7741 /// The caller already checked that \p I calls the appropriate LibFunc with a
7742 /// correct prototype.
7743 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7744   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7745   const Value *Size = I.getArgOperand(2);
7746   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7747   if (CSize && CSize->getZExtValue() == 0) {
7748     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7749                                                           I.getType(), true);
7750     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7751     return true;
7752   }
7753 
7754   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7755   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7756       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7757       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7758   if (Res.first.getNode()) {
7759     processIntegerCallValue(I, Res.first, true);
7760     PendingLoads.push_back(Res.second);
7761     return true;
7762   }
7763 
7764   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7765   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7766   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7767     return false;
7768 
7769   // If the target has a fast compare for the given size, it will return a
7770   // preferred load type for that size. Require that the load VT is legal and
7771   // that the target supports unaligned loads of that type. Otherwise, return
7772   // INVALID.
7773   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7774     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7775     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7776     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7777       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7778       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7779       // TODO: Check alignment of src and dest ptrs.
7780       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7781       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7782       if (!TLI.isTypeLegal(LVT) ||
7783           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7784           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7785         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7786     }
7787 
7788     return LVT;
7789   };
7790 
7791   // This turns into unaligned loads. We only do this if the target natively
7792   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7793   // we'll only produce a small number of byte loads.
7794   MVT LoadVT;
7795   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7796   switch (NumBitsToCompare) {
7797   default:
7798     return false;
7799   case 16:
7800     LoadVT = MVT::i16;
7801     break;
7802   case 32:
7803     LoadVT = MVT::i32;
7804     break;
7805   case 64:
7806   case 128:
7807   case 256:
7808     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7809     break;
7810   }
7811 
7812   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7813     return false;
7814 
7815   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7816   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7817 
7818   // Bitcast to a wide integer type if the loads are vectors.
7819   if (LoadVT.isVector()) {
7820     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7821     LoadL = DAG.getBitcast(CmpVT, LoadL);
7822     LoadR = DAG.getBitcast(CmpVT, LoadR);
7823   }
7824 
7825   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7826   processIntegerCallValue(I, Cmp, false);
7827   return true;
7828 }
7829 
7830 /// See if we can lower a memchr call into an optimized form. If so, return
7831 /// true and lower it. Otherwise return false, and it will be lowered like a
7832 /// normal call.
7833 /// The caller already checked that \p I calls the appropriate LibFunc with a
7834 /// correct prototype.
7835 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7836   const Value *Src = I.getArgOperand(0);
7837   const Value *Char = I.getArgOperand(1);
7838   const Value *Length = I.getArgOperand(2);
7839 
7840   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7841   std::pair<SDValue, SDValue> Res =
7842     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7843                                 getValue(Src), getValue(Char), getValue(Length),
7844                                 MachinePointerInfo(Src));
7845   if (Res.first.getNode()) {
7846     setValue(&I, Res.first);
7847     PendingLoads.push_back(Res.second);
7848     return true;
7849   }
7850 
7851   return false;
7852 }
7853 
7854 /// See if we can lower a mempcpy call into an optimized form. If so, return
7855 /// true and lower it. Otherwise return false, and it will be lowered like a
7856 /// normal call.
7857 /// The caller already checked that \p I calls the appropriate LibFunc with a
7858 /// correct prototype.
7859 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7860   SDValue Dst = getValue(I.getArgOperand(0));
7861   SDValue Src = getValue(I.getArgOperand(1));
7862   SDValue Size = getValue(I.getArgOperand(2));
7863 
7864   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7865   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7866   // DAG::getMemcpy needs Alignment to be defined.
7867   Align Alignment = std::min(DstAlign, SrcAlign);
7868 
7869   bool isVol = false;
7870   SDLoc sdl = getCurSDLoc();
7871 
7872   // In the mempcpy context we need to pass in a false value for isTailCall
7873   // because the return pointer needs to be adjusted by the size of
7874   // the copied memory.
7875   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7876   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7877                              /*isTailCall=*/false,
7878                              MachinePointerInfo(I.getArgOperand(0)),
7879                              MachinePointerInfo(I.getArgOperand(1)),
7880                              I.getAAMetadata());
7881   assert(MC.getNode() != nullptr &&
7882          "** memcpy should not be lowered as TailCall in mempcpy context **");
7883   DAG.setRoot(MC);
7884 
7885   // Check if Size needs to be truncated or extended.
7886   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7887 
7888   // Adjust return pointer to point just past the last dst byte.
7889   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7890                                     Dst, Size);
7891   setValue(&I, DstPlusSize);
7892   return true;
7893 }
7894 
7895 /// See if we can lower a strcpy call into an optimized form.  If so, return
7896 /// true and lower it, otherwise return false and it will be lowered like a
7897 /// normal call.
7898 /// The caller already checked that \p I calls the appropriate LibFunc with a
7899 /// correct prototype.
7900 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7901   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7902 
7903   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7904   std::pair<SDValue, SDValue> Res =
7905     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7906                                 getValue(Arg0), getValue(Arg1),
7907                                 MachinePointerInfo(Arg0),
7908                                 MachinePointerInfo(Arg1), isStpcpy);
7909   if (Res.first.getNode()) {
7910     setValue(&I, Res.first);
7911     DAG.setRoot(Res.second);
7912     return true;
7913   }
7914 
7915   return false;
7916 }
7917 
7918 /// See if we can lower a strcmp call into an optimized form.  If so, return
7919 /// true and lower it, otherwise return false and it will be lowered like a
7920 /// normal call.
7921 /// The caller already checked that \p I calls the appropriate LibFunc with a
7922 /// correct prototype.
7923 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7924   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7925 
7926   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7927   std::pair<SDValue, SDValue> Res =
7928     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7929                                 getValue(Arg0), getValue(Arg1),
7930                                 MachinePointerInfo(Arg0),
7931                                 MachinePointerInfo(Arg1));
7932   if (Res.first.getNode()) {
7933     processIntegerCallValue(I, Res.first, true);
7934     PendingLoads.push_back(Res.second);
7935     return true;
7936   }
7937 
7938   return false;
7939 }
7940 
7941 /// See if we can lower a strlen call into an optimized form.  If so, return
7942 /// true and lower it, otherwise return false and it will be lowered like a
7943 /// normal call.
7944 /// The caller already checked that \p I calls the appropriate LibFunc with a
7945 /// correct prototype.
7946 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7947   const Value *Arg0 = I.getArgOperand(0);
7948 
7949   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7950   std::pair<SDValue, SDValue> Res =
7951     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7952                                 getValue(Arg0), MachinePointerInfo(Arg0));
7953   if (Res.first.getNode()) {
7954     processIntegerCallValue(I, Res.first, false);
7955     PendingLoads.push_back(Res.second);
7956     return true;
7957   }
7958 
7959   return false;
7960 }
7961 
7962 /// See if we can lower a strnlen call into an optimized form.  If so, return
7963 /// true and lower it, otherwise return false and it will be lowered like a
7964 /// normal call.
7965 /// The caller already checked that \p I calls the appropriate LibFunc with a
7966 /// correct prototype.
7967 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7968   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7969 
7970   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7971   std::pair<SDValue, SDValue> Res =
7972     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7973                                  getValue(Arg0), getValue(Arg1),
7974                                  MachinePointerInfo(Arg0));
7975   if (Res.first.getNode()) {
7976     processIntegerCallValue(I, Res.first, false);
7977     PendingLoads.push_back(Res.second);
7978     return true;
7979   }
7980 
7981   return false;
7982 }
7983 
7984 /// See if we can lower a unary floating-point operation into an SDNode with
7985 /// the specified Opcode.  If so, return true and lower it, otherwise return
7986 /// false and it will be lowered like a normal call.
7987 /// The caller already checked that \p I calls the appropriate LibFunc with a
7988 /// correct prototype.
7989 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7990                                               unsigned Opcode) {
7991   // We already checked this call's prototype; verify it doesn't modify errno.
7992   if (!I.onlyReadsMemory())
7993     return false;
7994 
7995   SDNodeFlags Flags;
7996   Flags.copyFMF(cast<FPMathOperator>(I));
7997 
7998   SDValue Tmp = getValue(I.getArgOperand(0));
7999   setValue(&I,
8000            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8001   return true;
8002 }
8003 
8004 /// See if we can lower a binary floating-point operation into an SDNode with
8005 /// the specified Opcode. If so, return true and lower it. Otherwise return
8006 /// false, and it will be lowered like a normal call.
8007 /// The caller already checked that \p I calls the appropriate LibFunc with a
8008 /// correct prototype.
8009 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8010                                                unsigned Opcode) {
8011   // We already checked this call's prototype; verify it doesn't modify errno.
8012   if (!I.onlyReadsMemory())
8013     return false;
8014 
8015   SDNodeFlags Flags;
8016   Flags.copyFMF(cast<FPMathOperator>(I));
8017 
8018   SDValue Tmp0 = getValue(I.getArgOperand(0));
8019   SDValue Tmp1 = getValue(I.getArgOperand(1));
8020   EVT VT = Tmp0.getValueType();
8021   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8022   return true;
8023 }
8024 
8025 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8026   // Handle inline assembly differently.
8027   if (I.isInlineAsm()) {
8028     visitInlineAsm(I);
8029     return;
8030   }
8031 
8032   if (Function *F = I.getCalledFunction()) {
8033     diagnoseDontCall(I);
8034 
8035     if (F->isDeclaration()) {
8036       // Is this an LLVM intrinsic or a target-specific intrinsic?
8037       unsigned IID = F->getIntrinsicID();
8038       if (!IID)
8039         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8040           IID = II->getIntrinsicID(F);
8041 
8042       if (IID) {
8043         visitIntrinsicCall(I, IID);
8044         return;
8045       }
8046     }
8047 
8048     // Check for well-known libc/libm calls.  If the function is internal, it
8049     // can't be a library call.  Don't do the check if marked as nobuiltin for
8050     // some reason or the call site requires strict floating point semantics.
8051     LibFunc Func;
8052     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8053         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8054         LibInfo->hasOptimizedCodeGen(Func)) {
8055       switch (Func) {
8056       default: break;
8057       case LibFunc_bcmp:
8058         if (visitMemCmpBCmpCall(I))
8059           return;
8060         break;
8061       case LibFunc_copysign:
8062       case LibFunc_copysignf:
8063       case LibFunc_copysignl:
8064         // We already checked this call's prototype; verify it doesn't modify
8065         // errno.
8066         if (I.onlyReadsMemory()) {
8067           SDValue LHS = getValue(I.getArgOperand(0));
8068           SDValue RHS = getValue(I.getArgOperand(1));
8069           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8070                                    LHS.getValueType(), LHS, RHS));
8071           return;
8072         }
8073         break;
8074       case LibFunc_fabs:
8075       case LibFunc_fabsf:
8076       case LibFunc_fabsl:
8077         if (visitUnaryFloatCall(I, ISD::FABS))
8078           return;
8079         break;
8080       case LibFunc_fmin:
8081       case LibFunc_fminf:
8082       case LibFunc_fminl:
8083         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8084           return;
8085         break;
8086       case LibFunc_fmax:
8087       case LibFunc_fmaxf:
8088       case LibFunc_fmaxl:
8089         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8090           return;
8091         break;
8092       case LibFunc_sin:
8093       case LibFunc_sinf:
8094       case LibFunc_sinl:
8095         if (visitUnaryFloatCall(I, ISD::FSIN))
8096           return;
8097         break;
8098       case LibFunc_cos:
8099       case LibFunc_cosf:
8100       case LibFunc_cosl:
8101         if (visitUnaryFloatCall(I, ISD::FCOS))
8102           return;
8103         break;
8104       case LibFunc_sqrt:
8105       case LibFunc_sqrtf:
8106       case LibFunc_sqrtl:
8107       case LibFunc_sqrt_finite:
8108       case LibFunc_sqrtf_finite:
8109       case LibFunc_sqrtl_finite:
8110         if (visitUnaryFloatCall(I, ISD::FSQRT))
8111           return;
8112         break;
8113       case LibFunc_floor:
8114       case LibFunc_floorf:
8115       case LibFunc_floorl:
8116         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8117           return;
8118         break;
8119       case LibFunc_nearbyint:
8120       case LibFunc_nearbyintf:
8121       case LibFunc_nearbyintl:
8122         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8123           return;
8124         break;
8125       case LibFunc_ceil:
8126       case LibFunc_ceilf:
8127       case LibFunc_ceill:
8128         if (visitUnaryFloatCall(I, ISD::FCEIL))
8129           return;
8130         break;
8131       case LibFunc_rint:
8132       case LibFunc_rintf:
8133       case LibFunc_rintl:
8134         if (visitUnaryFloatCall(I, ISD::FRINT))
8135           return;
8136         break;
8137       case LibFunc_round:
8138       case LibFunc_roundf:
8139       case LibFunc_roundl:
8140         if (visitUnaryFloatCall(I, ISD::FROUND))
8141           return;
8142         break;
8143       case LibFunc_trunc:
8144       case LibFunc_truncf:
8145       case LibFunc_truncl:
8146         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8147           return;
8148         break;
8149       case LibFunc_log2:
8150       case LibFunc_log2f:
8151       case LibFunc_log2l:
8152         if (visitUnaryFloatCall(I, ISD::FLOG2))
8153           return;
8154         break;
8155       case LibFunc_exp2:
8156       case LibFunc_exp2f:
8157       case LibFunc_exp2l:
8158         if (visitUnaryFloatCall(I, ISD::FEXP2))
8159           return;
8160         break;
8161       case LibFunc_memcmp:
8162         if (visitMemCmpBCmpCall(I))
8163           return;
8164         break;
8165       case LibFunc_mempcpy:
8166         if (visitMemPCpyCall(I))
8167           return;
8168         break;
8169       case LibFunc_memchr:
8170         if (visitMemChrCall(I))
8171           return;
8172         break;
8173       case LibFunc_strcpy:
8174         if (visitStrCpyCall(I, false))
8175           return;
8176         break;
8177       case LibFunc_stpcpy:
8178         if (visitStrCpyCall(I, true))
8179           return;
8180         break;
8181       case LibFunc_strcmp:
8182         if (visitStrCmpCall(I))
8183           return;
8184         break;
8185       case LibFunc_strlen:
8186         if (visitStrLenCall(I))
8187           return;
8188         break;
8189       case LibFunc_strnlen:
8190         if (visitStrNLenCall(I))
8191           return;
8192         break;
8193       }
8194     }
8195   }
8196 
8197   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8198   // have to do anything here to lower funclet bundles.
8199   // CFGuardTarget bundles are lowered in LowerCallTo.
8200   assert(!I.hasOperandBundlesOtherThan(
8201              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8202               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8203               LLVMContext::OB_clang_arc_attachedcall}) &&
8204          "Cannot lower calls with arbitrary operand bundles!");
8205 
8206   SDValue Callee = getValue(I.getCalledOperand());
8207 
8208   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8209     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8210   else
8211     // Check if we can potentially perform a tail call. More detailed checking
8212     // is be done within LowerCallTo, after more information about the call is
8213     // known.
8214     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8215 }
8216 
8217 namespace {
8218 
8219 /// AsmOperandInfo - This contains information for each constraint that we are
8220 /// lowering.
8221 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8222 public:
8223   /// CallOperand - If this is the result output operand or a clobber
8224   /// this is null, otherwise it is the incoming operand to the CallInst.
8225   /// This gets modified as the asm is processed.
8226   SDValue CallOperand;
8227 
8228   /// AssignedRegs - If this is a register or register class operand, this
8229   /// contains the set of register corresponding to the operand.
8230   RegsForValue AssignedRegs;
8231 
8232   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8233     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8234   }
8235 
8236   /// Whether or not this operand accesses memory
8237   bool hasMemory(const TargetLowering &TLI) const {
8238     // Indirect operand accesses access memory.
8239     if (isIndirect)
8240       return true;
8241 
8242     for (const auto &Code : Codes)
8243       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8244         return true;
8245 
8246     return false;
8247   }
8248 
8249   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8250   /// corresponds to.  If there is no Value* for this operand, it returns
8251   /// MVT::Other.
8252   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8253                            const DataLayout &DL,
8254                            llvm::Type *ParamElemType) const {
8255     if (!CallOperandVal) return MVT::Other;
8256 
8257     if (isa<BasicBlock>(CallOperandVal))
8258       return TLI.getProgramPointerTy(DL);
8259 
8260     llvm::Type *OpTy = CallOperandVal->getType();
8261 
8262     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8263     // If this is an indirect operand, the operand is a pointer to the
8264     // accessed type.
8265     if (isIndirect) {
8266       OpTy = ParamElemType;
8267       assert(OpTy && "Indirect opernad must have elementtype attribute");
8268     }
8269 
8270     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8271     if (StructType *STy = dyn_cast<StructType>(OpTy))
8272       if (STy->getNumElements() == 1)
8273         OpTy = STy->getElementType(0);
8274 
8275     // If OpTy is not a single value, it may be a struct/union that we
8276     // can tile with integers.
8277     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8278       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8279       switch (BitSize) {
8280       default: break;
8281       case 1:
8282       case 8:
8283       case 16:
8284       case 32:
8285       case 64:
8286       case 128:
8287         OpTy = IntegerType::get(Context, BitSize);
8288         break;
8289       }
8290     }
8291 
8292     return TLI.getAsmOperandValueType(DL, OpTy, true);
8293   }
8294 };
8295 
8296 
8297 } // end anonymous namespace
8298 
8299 /// Make sure that the output operand \p OpInfo and its corresponding input
8300 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8301 /// out).
8302 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8303                                SDISelAsmOperandInfo &MatchingOpInfo,
8304                                SelectionDAG &DAG) {
8305   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8306     return;
8307 
8308   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8309   const auto &TLI = DAG.getTargetLoweringInfo();
8310 
8311   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8312       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8313                                        OpInfo.ConstraintVT);
8314   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8315       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8316                                        MatchingOpInfo.ConstraintVT);
8317   if ((OpInfo.ConstraintVT.isInteger() !=
8318        MatchingOpInfo.ConstraintVT.isInteger()) ||
8319       (MatchRC.second != InputRC.second)) {
8320     // FIXME: error out in a more elegant fashion
8321     report_fatal_error("Unsupported asm: input constraint"
8322                        " with a matching output constraint of"
8323                        " incompatible type!");
8324   }
8325   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8326 }
8327 
8328 /// Get a direct memory input to behave well as an indirect operand.
8329 /// This may introduce stores, hence the need for a \p Chain.
8330 /// \return The (possibly updated) chain.
8331 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8332                                         SDISelAsmOperandInfo &OpInfo,
8333                                         SelectionDAG &DAG) {
8334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8335 
8336   // If we don't have an indirect input, put it in the constpool if we can,
8337   // otherwise spill it to a stack slot.
8338   // TODO: This isn't quite right. We need to handle these according to
8339   // the addressing mode that the constraint wants. Also, this may take
8340   // an additional register for the computation and we don't want that
8341   // either.
8342 
8343   // If the operand is a float, integer, or vector constant, spill to a
8344   // constant pool entry to get its address.
8345   const Value *OpVal = OpInfo.CallOperandVal;
8346   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8347       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8348     OpInfo.CallOperand = DAG.getConstantPool(
8349         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8350     return Chain;
8351   }
8352 
8353   // Otherwise, create a stack slot and emit a store to it before the asm.
8354   Type *Ty = OpVal->getType();
8355   auto &DL = DAG.getDataLayout();
8356   uint64_t TySize = DL.getTypeAllocSize(Ty);
8357   MachineFunction &MF = DAG.getMachineFunction();
8358   int SSFI = MF.getFrameInfo().CreateStackObject(
8359       TySize, DL.getPrefTypeAlign(Ty), false);
8360   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8361   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8362                             MachinePointerInfo::getFixedStack(MF, SSFI),
8363                             TLI.getMemValueType(DL, Ty));
8364   OpInfo.CallOperand = StackSlot;
8365 
8366   return Chain;
8367 }
8368 
8369 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8370 /// specified operand.  We prefer to assign virtual registers, to allow the
8371 /// register allocator to handle the assignment process.  However, if the asm
8372 /// uses features that we can't model on machineinstrs, we have SDISel do the
8373 /// allocation.  This produces generally horrible, but correct, code.
8374 ///
8375 ///   OpInfo describes the operand
8376 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8377 static llvm::Optional<unsigned>
8378 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8379                      SDISelAsmOperandInfo &OpInfo,
8380                      SDISelAsmOperandInfo &RefOpInfo) {
8381   LLVMContext &Context = *DAG.getContext();
8382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8383 
8384   MachineFunction &MF = DAG.getMachineFunction();
8385   SmallVector<unsigned, 4> Regs;
8386   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8387 
8388   // No work to do for memory operations.
8389   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8390     return None;
8391 
8392   // If this is a constraint for a single physreg, or a constraint for a
8393   // register class, find it.
8394   unsigned AssignedReg;
8395   const TargetRegisterClass *RC;
8396   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8397       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8398   // RC is unset only on failure. Return immediately.
8399   if (!RC)
8400     return None;
8401 
8402   // Get the actual register value type.  This is important, because the user
8403   // may have asked for (e.g.) the AX register in i32 type.  We need to
8404   // remember that AX is actually i16 to get the right extension.
8405   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8406 
8407   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8408     // If this is an FP operand in an integer register (or visa versa), or more
8409     // generally if the operand value disagrees with the register class we plan
8410     // to stick it in, fix the operand type.
8411     //
8412     // If this is an input value, the bitcast to the new type is done now.
8413     // Bitcast for output value is done at the end of visitInlineAsm().
8414     if ((OpInfo.Type == InlineAsm::isOutput ||
8415          OpInfo.Type == InlineAsm::isInput) &&
8416         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8417       // Try to convert to the first EVT that the reg class contains.  If the
8418       // types are identical size, use a bitcast to convert (e.g. two differing
8419       // vector types).  Note: output bitcast is done at the end of
8420       // visitInlineAsm().
8421       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8422         // Exclude indirect inputs while they are unsupported because the code
8423         // to perform the load is missing and thus OpInfo.CallOperand still
8424         // refers to the input address rather than the pointed-to value.
8425         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8426           OpInfo.CallOperand =
8427               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8428         OpInfo.ConstraintVT = RegVT;
8429         // If the operand is an FP value and we want it in integer registers,
8430         // use the corresponding integer type. This turns an f64 value into
8431         // i64, which can be passed with two i32 values on a 32-bit machine.
8432       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8433         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8434         if (OpInfo.Type == InlineAsm::isInput)
8435           OpInfo.CallOperand =
8436               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8437         OpInfo.ConstraintVT = VT;
8438       }
8439     }
8440   }
8441 
8442   // No need to allocate a matching input constraint since the constraint it's
8443   // matching to has already been allocated.
8444   if (OpInfo.isMatchingInputConstraint())
8445     return None;
8446 
8447   EVT ValueVT = OpInfo.ConstraintVT;
8448   if (OpInfo.ConstraintVT == MVT::Other)
8449     ValueVT = RegVT;
8450 
8451   // Initialize NumRegs.
8452   unsigned NumRegs = 1;
8453   if (OpInfo.ConstraintVT != MVT::Other)
8454     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8455 
8456   // If this is a constraint for a specific physical register, like {r17},
8457   // assign it now.
8458 
8459   // If this associated to a specific register, initialize iterator to correct
8460   // place. If virtual, make sure we have enough registers
8461 
8462   // Initialize iterator if necessary
8463   TargetRegisterClass::iterator I = RC->begin();
8464   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8465 
8466   // Do not check for single registers.
8467   if (AssignedReg) {
8468     I = std::find(I, RC->end(), AssignedReg);
8469     if (I == RC->end()) {
8470       // RC does not contain the selected register, which indicates a
8471       // mismatch between the register and the required type/bitwidth.
8472       return {AssignedReg};
8473     }
8474   }
8475 
8476   for (; NumRegs; --NumRegs, ++I) {
8477     assert(I != RC->end() && "Ran out of registers to allocate!");
8478     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8479     Regs.push_back(R);
8480   }
8481 
8482   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8483   return None;
8484 }
8485 
8486 static unsigned
8487 findMatchingInlineAsmOperand(unsigned OperandNo,
8488                              const std::vector<SDValue> &AsmNodeOperands) {
8489   // Scan until we find the definition we already emitted of this operand.
8490   unsigned CurOp = InlineAsm::Op_FirstOperand;
8491   for (; OperandNo; --OperandNo) {
8492     // Advance to the next operand.
8493     unsigned OpFlag =
8494         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8495     assert((InlineAsm::isRegDefKind(OpFlag) ||
8496             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8497             InlineAsm::isMemKind(OpFlag)) &&
8498            "Skipped past definitions?");
8499     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8500   }
8501   return CurOp;
8502 }
8503 
8504 namespace {
8505 
8506 class ExtraFlags {
8507   unsigned Flags = 0;
8508 
8509 public:
8510   explicit ExtraFlags(const CallBase &Call) {
8511     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8512     if (IA->hasSideEffects())
8513       Flags |= InlineAsm::Extra_HasSideEffects;
8514     if (IA->isAlignStack())
8515       Flags |= InlineAsm::Extra_IsAlignStack;
8516     if (Call.isConvergent())
8517       Flags |= InlineAsm::Extra_IsConvergent;
8518     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8519   }
8520 
8521   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8522     // Ideally, we would only check against memory constraints.  However, the
8523     // meaning of an Other constraint can be target-specific and we can't easily
8524     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8525     // for Other constraints as well.
8526     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8527         OpInfo.ConstraintType == TargetLowering::C_Other) {
8528       if (OpInfo.Type == InlineAsm::isInput)
8529         Flags |= InlineAsm::Extra_MayLoad;
8530       else if (OpInfo.Type == InlineAsm::isOutput)
8531         Flags |= InlineAsm::Extra_MayStore;
8532       else if (OpInfo.Type == InlineAsm::isClobber)
8533         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8534     }
8535   }
8536 
8537   unsigned get() const { return Flags; }
8538 };
8539 
8540 } // end anonymous namespace
8541 
8542 /// visitInlineAsm - Handle a call to an InlineAsm object.
8543 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8544                                          const BasicBlock *EHPadBB) {
8545   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8546 
8547   /// ConstraintOperands - Information about all of the constraints.
8548   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8549 
8550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8551   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8552       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8553 
8554   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8555   // AsmDialect, MayLoad, MayStore).
8556   bool HasSideEffect = IA->hasSideEffects();
8557   ExtraFlags ExtraInfo(Call);
8558 
8559   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8560   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8561   unsigned NumMatchingOps = 0;
8562   for (auto &T : TargetConstraints) {
8563     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8564     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8565 
8566     // Compute the value type for each operand.
8567     if (OpInfo.hasArg()) {
8568       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
8569 
8570       // Process the call argument. BasicBlocks are labels, currently appearing
8571       // only in asm's.
8572       if (isa<CallBrInst>(Call) &&
8573           ArgNo >= (cast<CallBrInst>(&Call)->arg_size() -
8574                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8575                         NumMatchingOps) &&
8576           (NumMatchingOps == 0 ||
8577            ArgNo < (cast<CallBrInst>(&Call)->arg_size() - NumMatchingOps))) {
8578         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8579         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8580         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8581       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8582         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8583       } else {
8584         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8585       }
8586 
8587       Type *ParamElemTy = Call.getAttributes().getParamElementType(ArgNo);
8588       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8589                                            DAG.getDataLayout(), ParamElemTy);
8590       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8591       ArgNo++;
8592     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8593       // The return value of the call is this value.  As such, there is no
8594       // corresponding argument.
8595       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8596       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8597         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8598             DAG.getDataLayout(), STy->getElementType(ResNo));
8599       } else {
8600         assert(ResNo == 0 && "Asm only has one result!");
8601         OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
8602             DAG.getDataLayout(), Call.getType()).getSimpleVT();
8603       }
8604       ++ResNo;
8605     } else {
8606       OpInfo.ConstraintVT = MVT::Other;
8607     }
8608 
8609     if (OpInfo.hasMatchingInput())
8610       ++NumMatchingOps;
8611 
8612     if (!HasSideEffect)
8613       HasSideEffect = OpInfo.hasMemory(TLI);
8614 
8615     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8616     // FIXME: Could we compute this on OpInfo rather than T?
8617 
8618     // Compute the constraint code and ConstraintType to use.
8619     TLI.ComputeConstraintToUse(T, SDValue());
8620 
8621     if (T.ConstraintType == TargetLowering::C_Immediate &&
8622         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8623       // We've delayed emitting a diagnostic like the "n" constraint because
8624       // inlining could cause an integer showing up.
8625       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8626                                           "' expects an integer constant "
8627                                           "expression");
8628 
8629     ExtraInfo.update(T);
8630   }
8631 
8632   // We won't need to flush pending loads if this asm doesn't touch
8633   // memory and is nonvolatile.
8634   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8635 
8636   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8637   if (EmitEHLabels) {
8638     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8639   }
8640   bool IsCallBr = isa<CallBrInst>(Call);
8641 
8642   if (IsCallBr || EmitEHLabels) {
8643     // If this is a callbr or invoke we need to flush pending exports since
8644     // inlineasm_br and invoke are terminators.
8645     // We need to do this before nodes are glued to the inlineasm_br node.
8646     Chain = getControlRoot();
8647   }
8648 
8649   MCSymbol *BeginLabel = nullptr;
8650   if (EmitEHLabels) {
8651     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8652   }
8653 
8654   // Second pass over the constraints: compute which constraint option to use.
8655   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8656     // If this is an output operand with a matching input operand, look up the
8657     // matching input. If their types mismatch, e.g. one is an integer, the
8658     // other is floating point, or their sizes are different, flag it as an
8659     // error.
8660     if (OpInfo.hasMatchingInput()) {
8661       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8662       patchMatchingInput(OpInfo, Input, DAG);
8663     }
8664 
8665     // Compute the constraint code and ConstraintType to use.
8666     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8667 
8668     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8669         OpInfo.Type == InlineAsm::isClobber)
8670       continue;
8671 
8672     // If this is a memory input, and if the operand is not indirect, do what we
8673     // need to provide an address for the memory input.
8674     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8675         !OpInfo.isIndirect) {
8676       assert((OpInfo.isMultipleAlternative ||
8677               (OpInfo.Type == InlineAsm::isInput)) &&
8678              "Can only indirectify direct input operands!");
8679 
8680       // Memory operands really want the address of the value.
8681       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8682 
8683       // There is no longer a Value* corresponding to this operand.
8684       OpInfo.CallOperandVal = nullptr;
8685 
8686       // It is now an indirect operand.
8687       OpInfo.isIndirect = true;
8688     }
8689 
8690   }
8691 
8692   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8693   std::vector<SDValue> AsmNodeOperands;
8694   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8695   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8696       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8697 
8698   // If we have a !srcloc metadata node associated with it, we want to attach
8699   // this to the ultimately generated inline asm machineinstr.  To do this, we
8700   // pass in the third operand as this (potentially null) inline asm MDNode.
8701   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8702   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8703 
8704   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8705   // bits as operand 3.
8706   AsmNodeOperands.push_back(DAG.getTargetConstant(
8707       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8708 
8709   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8710   // this, assign virtual and physical registers for inputs and otput.
8711   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8712     // Assign Registers.
8713     SDISelAsmOperandInfo &RefOpInfo =
8714         OpInfo.isMatchingInputConstraint()
8715             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8716             : OpInfo;
8717     const auto RegError =
8718         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8719     if (RegError.hasValue()) {
8720       const MachineFunction &MF = DAG.getMachineFunction();
8721       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8722       const char *RegName = TRI.getName(RegError.getValue());
8723       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8724                                    "' allocated for constraint '" +
8725                                    Twine(OpInfo.ConstraintCode) +
8726                                    "' does not match required type");
8727       return;
8728     }
8729 
8730     auto DetectWriteToReservedRegister = [&]() {
8731       const MachineFunction &MF = DAG.getMachineFunction();
8732       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8733       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8734         if (Register::isPhysicalRegister(Reg) &&
8735             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8736           const char *RegName = TRI.getName(Reg);
8737           emitInlineAsmError(Call, "write to reserved register '" +
8738                                        Twine(RegName) + "'");
8739           return true;
8740         }
8741       }
8742       return false;
8743     };
8744 
8745     switch (OpInfo.Type) {
8746     case InlineAsm::isOutput:
8747       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8748         unsigned ConstraintID =
8749             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8750         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8751                "Failed to convert memory constraint code to constraint id.");
8752 
8753         // Add information to the INLINEASM node to know about this output.
8754         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8755         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8756         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8757                                                         MVT::i32));
8758         AsmNodeOperands.push_back(OpInfo.CallOperand);
8759       } else {
8760         // Otherwise, this outputs to a register (directly for C_Register /
8761         // C_RegisterClass, and a target-defined fashion for
8762         // C_Immediate/C_Other). Find a register that we can use.
8763         if (OpInfo.AssignedRegs.Regs.empty()) {
8764           emitInlineAsmError(
8765               Call, "couldn't allocate output register for constraint '" +
8766                         Twine(OpInfo.ConstraintCode) + "'");
8767           return;
8768         }
8769 
8770         if (DetectWriteToReservedRegister())
8771           return;
8772 
8773         // Add information to the INLINEASM node to know that this register is
8774         // set.
8775         OpInfo.AssignedRegs.AddInlineAsmOperands(
8776             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8777                                   : InlineAsm::Kind_RegDef,
8778             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8779       }
8780       break;
8781 
8782     case InlineAsm::isInput: {
8783       SDValue InOperandVal = OpInfo.CallOperand;
8784 
8785       if (OpInfo.isMatchingInputConstraint()) {
8786         // If this is required to match an output register we have already set,
8787         // just use its register.
8788         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8789                                                   AsmNodeOperands);
8790         unsigned OpFlag =
8791           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8792         if (InlineAsm::isRegDefKind(OpFlag) ||
8793             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8794           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8795           if (OpInfo.isIndirect) {
8796             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8797             emitInlineAsmError(Call, "inline asm not supported yet: "
8798                                      "don't know how to handle tied "
8799                                      "indirect register inputs");
8800             return;
8801           }
8802 
8803           SmallVector<unsigned, 4> Regs;
8804           MachineFunction &MF = DAG.getMachineFunction();
8805           MachineRegisterInfo &MRI = MF.getRegInfo();
8806           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8807           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8808           Register TiedReg = R->getReg();
8809           MVT RegVT = R->getSimpleValueType(0);
8810           const TargetRegisterClass *RC =
8811               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8812               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
8813                                       : TRI.getMinimalPhysRegClass(TiedReg);
8814           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8815           for (unsigned i = 0; i != NumRegs; ++i)
8816             Regs.push_back(MRI.createVirtualRegister(RC));
8817 
8818           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8819 
8820           SDLoc dl = getCurSDLoc();
8821           // Use the produced MatchedRegs object to
8822           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8823           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8824                                            true, OpInfo.getMatchedOperand(), dl,
8825                                            DAG, AsmNodeOperands);
8826           break;
8827         }
8828 
8829         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8830         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8831                "Unexpected number of operands");
8832         // Add information to the INLINEASM node to know about this input.
8833         // See InlineAsm.h isUseOperandTiedToDef.
8834         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8835         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8836                                                     OpInfo.getMatchedOperand());
8837         AsmNodeOperands.push_back(DAG.getTargetConstant(
8838             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8839         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8840         break;
8841       }
8842 
8843       // Treat indirect 'X' constraint as memory.
8844       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8845           OpInfo.isIndirect)
8846         OpInfo.ConstraintType = TargetLowering::C_Memory;
8847 
8848       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8849           OpInfo.ConstraintType == TargetLowering::C_Other) {
8850         std::vector<SDValue> Ops;
8851         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8852                                           Ops, DAG);
8853         if (Ops.empty()) {
8854           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8855             if (isa<ConstantSDNode>(InOperandVal)) {
8856               emitInlineAsmError(Call, "value out of range for constraint '" +
8857                                            Twine(OpInfo.ConstraintCode) + "'");
8858               return;
8859             }
8860 
8861           emitInlineAsmError(Call,
8862                              "invalid operand for inline asm constraint '" +
8863                                  Twine(OpInfo.ConstraintCode) + "'");
8864           return;
8865         }
8866 
8867         // Add information to the INLINEASM node to know about this input.
8868         unsigned ResOpType =
8869           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8870         AsmNodeOperands.push_back(DAG.getTargetConstant(
8871             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8872         llvm::append_range(AsmNodeOperands, Ops);
8873         break;
8874       }
8875 
8876       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8877         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8878         assert(InOperandVal.getValueType() ==
8879                    TLI.getPointerTy(DAG.getDataLayout()) &&
8880                "Memory operands expect pointer values");
8881 
8882         unsigned ConstraintID =
8883             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8884         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8885                "Failed to convert memory constraint code to constraint id.");
8886 
8887         // Add information to the INLINEASM node to know about this input.
8888         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8889         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8890         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8891                                                         getCurSDLoc(),
8892                                                         MVT::i32));
8893         AsmNodeOperands.push_back(InOperandVal);
8894         break;
8895       }
8896 
8897       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8898               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8899              "Unknown constraint type!");
8900 
8901       // TODO: Support this.
8902       if (OpInfo.isIndirect) {
8903         emitInlineAsmError(
8904             Call, "Don't know how to handle indirect register inputs yet "
8905                   "for constraint '" +
8906                       Twine(OpInfo.ConstraintCode) + "'");
8907         return;
8908       }
8909 
8910       // Copy the input into the appropriate registers.
8911       if (OpInfo.AssignedRegs.Regs.empty()) {
8912         emitInlineAsmError(Call,
8913                            "couldn't allocate input reg for constraint '" +
8914                                Twine(OpInfo.ConstraintCode) + "'");
8915         return;
8916       }
8917 
8918       if (DetectWriteToReservedRegister())
8919         return;
8920 
8921       SDLoc dl = getCurSDLoc();
8922 
8923       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8924                                         &Call);
8925 
8926       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8927                                                dl, DAG, AsmNodeOperands);
8928       break;
8929     }
8930     case InlineAsm::isClobber:
8931       // Add the clobbered value to the operand list, so that the register
8932       // allocator is aware that the physreg got clobbered.
8933       if (!OpInfo.AssignedRegs.Regs.empty())
8934         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8935                                                  false, 0, getCurSDLoc(), DAG,
8936                                                  AsmNodeOperands);
8937       break;
8938     }
8939   }
8940 
8941   // Finish up input operands.  Set the input chain and add the flag last.
8942   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8943   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8944 
8945   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8946   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8947                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8948   Flag = Chain.getValue(1);
8949 
8950   // Do additional work to generate outputs.
8951 
8952   SmallVector<EVT, 1> ResultVTs;
8953   SmallVector<SDValue, 1> ResultValues;
8954   SmallVector<SDValue, 8> OutChains;
8955 
8956   llvm::Type *CallResultType = Call.getType();
8957   ArrayRef<Type *> ResultTypes;
8958   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8959     ResultTypes = StructResult->elements();
8960   else if (!CallResultType->isVoidTy())
8961     ResultTypes = makeArrayRef(CallResultType);
8962 
8963   auto CurResultType = ResultTypes.begin();
8964   auto handleRegAssign = [&](SDValue V) {
8965     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8966     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8967     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8968     ++CurResultType;
8969     // If the type of the inline asm call site return value is different but has
8970     // same size as the type of the asm output bitcast it.  One example of this
8971     // is for vectors with different width / number of elements.  This can
8972     // happen for register classes that can contain multiple different value
8973     // types.  The preg or vreg allocated may not have the same VT as was
8974     // expected.
8975     //
8976     // This can also happen for a return value that disagrees with the register
8977     // class it is put in, eg. a double in a general-purpose register on a
8978     // 32-bit machine.
8979     if (ResultVT != V.getValueType() &&
8980         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8981       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8982     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8983              V.getValueType().isInteger()) {
8984       // If a result value was tied to an input value, the computed result
8985       // may have a wider width than the expected result.  Extract the
8986       // relevant portion.
8987       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8988     }
8989     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8990     ResultVTs.push_back(ResultVT);
8991     ResultValues.push_back(V);
8992   };
8993 
8994   // Deal with output operands.
8995   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8996     if (OpInfo.Type == InlineAsm::isOutput) {
8997       SDValue Val;
8998       // Skip trivial output operands.
8999       if (OpInfo.AssignedRegs.Regs.empty())
9000         continue;
9001 
9002       switch (OpInfo.ConstraintType) {
9003       case TargetLowering::C_Register:
9004       case TargetLowering::C_RegisterClass:
9005         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9006                                                   Chain, &Flag, &Call);
9007         break;
9008       case TargetLowering::C_Immediate:
9009       case TargetLowering::C_Other:
9010         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9011                                               OpInfo, DAG);
9012         break;
9013       case TargetLowering::C_Memory:
9014         break; // Already handled.
9015       case TargetLowering::C_Unknown:
9016         assert(false && "Unexpected unknown constraint");
9017       }
9018 
9019       // Indirect output manifest as stores. Record output chains.
9020       if (OpInfo.isIndirect) {
9021         const Value *Ptr = OpInfo.CallOperandVal;
9022         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9023         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9024                                      MachinePointerInfo(Ptr));
9025         OutChains.push_back(Store);
9026       } else {
9027         // generate CopyFromRegs to associated registers.
9028         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9029         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9030           for (const SDValue &V : Val->op_values())
9031             handleRegAssign(V);
9032         } else
9033           handleRegAssign(Val);
9034       }
9035     }
9036   }
9037 
9038   // Set results.
9039   if (!ResultValues.empty()) {
9040     assert(CurResultType == ResultTypes.end() &&
9041            "Mismatch in number of ResultTypes");
9042     assert(ResultValues.size() == ResultTypes.size() &&
9043            "Mismatch in number of output operands in asm result");
9044 
9045     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9046                             DAG.getVTList(ResultVTs), ResultValues);
9047     setValue(&Call, V);
9048   }
9049 
9050   // Collect store chains.
9051   if (!OutChains.empty())
9052     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9053 
9054   if (EmitEHLabels) {
9055     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9056   }
9057 
9058   // Only Update Root if inline assembly has a memory effect.
9059   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9060       EmitEHLabels)
9061     DAG.setRoot(Chain);
9062 }
9063 
9064 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9065                                              const Twine &Message) {
9066   LLVMContext &Ctx = *DAG.getContext();
9067   Ctx.emitError(&Call, Message);
9068 
9069   // Make sure we leave the DAG in a valid state
9070   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9071   SmallVector<EVT, 1> ValueVTs;
9072   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9073 
9074   if (ValueVTs.empty())
9075     return;
9076 
9077   SmallVector<SDValue, 1> Ops;
9078   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9079     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9080 
9081   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9082 }
9083 
9084 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9085   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9086                           MVT::Other, getRoot(),
9087                           getValue(I.getArgOperand(0)),
9088                           DAG.getSrcValue(I.getArgOperand(0))));
9089 }
9090 
9091 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9092   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9093   const DataLayout &DL = DAG.getDataLayout();
9094   SDValue V = DAG.getVAArg(
9095       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9096       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9097       DL.getABITypeAlign(I.getType()).value());
9098   DAG.setRoot(V.getValue(1));
9099 
9100   if (I.getType()->isPointerTy())
9101     V = DAG.getPtrExtOrTrunc(
9102         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9103   setValue(&I, V);
9104 }
9105 
9106 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9107   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9108                           MVT::Other, getRoot(),
9109                           getValue(I.getArgOperand(0)),
9110                           DAG.getSrcValue(I.getArgOperand(0))));
9111 }
9112 
9113 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9114   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9115                           MVT::Other, getRoot(),
9116                           getValue(I.getArgOperand(0)),
9117                           getValue(I.getArgOperand(1)),
9118                           DAG.getSrcValue(I.getArgOperand(0)),
9119                           DAG.getSrcValue(I.getArgOperand(1))));
9120 }
9121 
9122 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9123                                                     const Instruction &I,
9124                                                     SDValue Op) {
9125   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9126   if (!Range)
9127     return Op;
9128 
9129   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9130   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9131     return Op;
9132 
9133   APInt Lo = CR.getUnsignedMin();
9134   if (!Lo.isMinValue())
9135     return Op;
9136 
9137   APInt Hi = CR.getUnsignedMax();
9138   unsigned Bits = std::max(Hi.getActiveBits(),
9139                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9140 
9141   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9142 
9143   SDLoc SL = getCurSDLoc();
9144 
9145   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9146                              DAG.getValueType(SmallVT));
9147   unsigned NumVals = Op.getNode()->getNumValues();
9148   if (NumVals == 1)
9149     return ZExt;
9150 
9151   SmallVector<SDValue, 4> Ops;
9152 
9153   Ops.push_back(ZExt);
9154   for (unsigned I = 1; I != NumVals; ++I)
9155     Ops.push_back(Op.getValue(I));
9156 
9157   return DAG.getMergeValues(Ops, SL);
9158 }
9159 
9160 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9161 /// the call being lowered.
9162 ///
9163 /// This is a helper for lowering intrinsics that follow a target calling
9164 /// convention or require stack pointer adjustment. Only a subset of the
9165 /// intrinsic's operands need to participate in the calling convention.
9166 void SelectionDAGBuilder::populateCallLoweringInfo(
9167     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9168     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9169     bool IsPatchPoint) {
9170   TargetLowering::ArgListTy Args;
9171   Args.reserve(NumArgs);
9172 
9173   // Populate the argument list.
9174   // Attributes for args start at offset 1, after the return attribute.
9175   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9176        ArgI != ArgE; ++ArgI) {
9177     const Value *V = Call->getOperand(ArgI);
9178 
9179     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9180 
9181     TargetLowering::ArgListEntry Entry;
9182     Entry.Node = getValue(V);
9183     Entry.Ty = V->getType();
9184     Entry.setAttributes(Call, ArgI);
9185     Args.push_back(Entry);
9186   }
9187 
9188   CLI.setDebugLoc(getCurSDLoc())
9189       .setChain(getRoot())
9190       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9191       .setDiscardResult(Call->use_empty())
9192       .setIsPatchPoint(IsPatchPoint)
9193       .setIsPreallocated(
9194           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9195 }
9196 
9197 /// Add a stack map intrinsic call's live variable operands to a stackmap
9198 /// or patchpoint target node's operand list.
9199 ///
9200 /// Constants are converted to TargetConstants purely as an optimization to
9201 /// avoid constant materialization and register allocation.
9202 ///
9203 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9204 /// generate addess computation nodes, and so FinalizeISel can convert the
9205 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9206 /// address materialization and register allocation, but may also be required
9207 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9208 /// alloca in the entry block, then the runtime may assume that the alloca's
9209 /// StackMap location can be read immediately after compilation and that the
9210 /// location is valid at any point during execution (this is similar to the
9211 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9212 /// only available in a register, then the runtime would need to trap when
9213 /// execution reaches the StackMap in order to read the alloca's location.
9214 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9215                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9216                                 SelectionDAGBuilder &Builder) {
9217   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9218     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9219     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9220       Ops.push_back(
9221         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9222       Ops.push_back(
9223         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9224     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9225       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9226       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9227           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9228     } else
9229       Ops.push_back(OpVal);
9230   }
9231 }
9232 
9233 /// Lower llvm.experimental.stackmap directly to its target opcode.
9234 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9235   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9236   //                                  [live variables...])
9237 
9238   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9239 
9240   SDValue Chain, InFlag, Callee, NullPtr;
9241   SmallVector<SDValue, 32> Ops;
9242 
9243   SDLoc DL = getCurSDLoc();
9244   Callee = getValue(CI.getCalledOperand());
9245   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9246 
9247   // The stackmap intrinsic only records the live variables (the arguments
9248   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9249   // intrinsic, this won't be lowered to a function call. This means we don't
9250   // have to worry about calling conventions and target specific lowering code.
9251   // Instead we perform the call lowering right here.
9252   //
9253   // chain, flag = CALLSEQ_START(chain, 0, 0)
9254   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9255   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9256   //
9257   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9258   InFlag = Chain.getValue(1);
9259 
9260   // Add the <id> and <numBytes> constants.
9261   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9262   Ops.push_back(DAG.getTargetConstant(
9263                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9264   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9265   Ops.push_back(DAG.getTargetConstant(
9266                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9267                   MVT::i32));
9268 
9269   // Push live variables for the stack map.
9270   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9271 
9272   // We are not pushing any register mask info here on the operands list,
9273   // because the stackmap doesn't clobber anything.
9274 
9275   // Push the chain and the glue flag.
9276   Ops.push_back(Chain);
9277   Ops.push_back(InFlag);
9278 
9279   // Create the STACKMAP node.
9280   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9281   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9282   Chain = SDValue(SM, 0);
9283   InFlag = Chain.getValue(1);
9284 
9285   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9286 
9287   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9288 
9289   // Set the root to the target-lowered call chain.
9290   DAG.setRoot(Chain);
9291 
9292   // Inform the Frame Information that we have a stackmap in this function.
9293   FuncInfo.MF->getFrameInfo().setHasStackMap();
9294 }
9295 
9296 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9297 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9298                                           const BasicBlock *EHPadBB) {
9299   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9300   //                                                 i32 <numBytes>,
9301   //                                                 i8* <target>,
9302   //                                                 i32 <numArgs>,
9303   //                                                 [Args...],
9304   //                                                 [live variables...])
9305 
9306   CallingConv::ID CC = CB.getCallingConv();
9307   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9308   bool HasDef = !CB.getType()->isVoidTy();
9309   SDLoc dl = getCurSDLoc();
9310   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9311 
9312   // Handle immediate and symbolic callees.
9313   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9314     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9315                                    /*isTarget=*/true);
9316   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9317     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9318                                          SDLoc(SymbolicCallee),
9319                                          SymbolicCallee->getValueType(0));
9320 
9321   // Get the real number of arguments participating in the call <numArgs>
9322   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9323   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9324 
9325   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9326   // Intrinsics include all meta-operands up to but not including CC.
9327   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9328   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9329          "Not enough arguments provided to the patchpoint intrinsic");
9330 
9331   // For AnyRegCC the arguments are lowered later on manually.
9332   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9333   Type *ReturnTy =
9334       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9335 
9336   TargetLowering::CallLoweringInfo CLI(DAG);
9337   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9338                            ReturnTy, true);
9339   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9340 
9341   SDNode *CallEnd = Result.second.getNode();
9342   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9343     CallEnd = CallEnd->getOperand(0).getNode();
9344 
9345   /// Get a call instruction from the call sequence chain.
9346   /// Tail calls are not allowed.
9347   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9348          "Expected a callseq node.");
9349   SDNode *Call = CallEnd->getOperand(0).getNode();
9350   bool HasGlue = Call->getGluedNode();
9351 
9352   // Replace the target specific call node with the patchable intrinsic.
9353   SmallVector<SDValue, 8> Ops;
9354 
9355   // Add the <id> and <numBytes> constants.
9356   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9357   Ops.push_back(DAG.getTargetConstant(
9358                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9359   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9360   Ops.push_back(DAG.getTargetConstant(
9361                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9362                   MVT::i32));
9363 
9364   // Add the callee.
9365   Ops.push_back(Callee);
9366 
9367   // Adjust <numArgs> to account for any arguments that have been passed on the
9368   // stack instead.
9369   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9370   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9371   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9372   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9373 
9374   // Add the calling convention
9375   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9376 
9377   // Add the arguments we omitted previously. The register allocator should
9378   // place these in any free register.
9379   if (IsAnyRegCC)
9380     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9381       Ops.push_back(getValue(CB.getArgOperand(i)));
9382 
9383   // Push the arguments from the call instruction up to the register mask.
9384   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9385   Ops.append(Call->op_begin() + 2, e);
9386 
9387   // Push live variables for the stack map.
9388   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9389 
9390   // Push the register mask info.
9391   if (HasGlue)
9392     Ops.push_back(*(Call->op_end()-2));
9393   else
9394     Ops.push_back(*(Call->op_end()-1));
9395 
9396   // Push the chain (this is originally the first operand of the call, but
9397   // becomes now the last or second to last operand).
9398   Ops.push_back(*(Call->op_begin()));
9399 
9400   // Push the glue flag (last operand).
9401   if (HasGlue)
9402     Ops.push_back(*(Call->op_end()-1));
9403 
9404   SDVTList NodeTys;
9405   if (IsAnyRegCC && HasDef) {
9406     // Create the return types based on the intrinsic definition
9407     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9408     SmallVector<EVT, 3> ValueVTs;
9409     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9410     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9411 
9412     // There is always a chain and a glue type at the end
9413     ValueVTs.push_back(MVT::Other);
9414     ValueVTs.push_back(MVT::Glue);
9415     NodeTys = DAG.getVTList(ValueVTs);
9416   } else
9417     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9418 
9419   // Replace the target specific call node with a PATCHPOINT node.
9420   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9421                                          dl, NodeTys, Ops);
9422 
9423   // Update the NodeMap.
9424   if (HasDef) {
9425     if (IsAnyRegCC)
9426       setValue(&CB, SDValue(MN, 0));
9427     else
9428       setValue(&CB, Result.first);
9429   }
9430 
9431   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9432   // call sequence. Furthermore the location of the chain and glue can change
9433   // when the AnyReg calling convention is used and the intrinsic returns a
9434   // value.
9435   if (IsAnyRegCC && HasDef) {
9436     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9437     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9438     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9439   } else
9440     DAG.ReplaceAllUsesWith(Call, MN);
9441   DAG.DeleteNode(Call);
9442 
9443   // Inform the Frame Information that we have a patchpoint in this function.
9444   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9445 }
9446 
9447 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9448                                             unsigned Intrinsic) {
9449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9450   SDValue Op1 = getValue(I.getArgOperand(0));
9451   SDValue Op2;
9452   if (I.arg_size() > 1)
9453     Op2 = getValue(I.getArgOperand(1));
9454   SDLoc dl = getCurSDLoc();
9455   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9456   SDValue Res;
9457   SDNodeFlags SDFlags;
9458   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9459     SDFlags.copyFMF(*FPMO);
9460 
9461   switch (Intrinsic) {
9462   case Intrinsic::vector_reduce_fadd:
9463     if (SDFlags.hasAllowReassociation())
9464       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9465                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9466                         SDFlags);
9467     else
9468       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9469     break;
9470   case Intrinsic::vector_reduce_fmul:
9471     if (SDFlags.hasAllowReassociation())
9472       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9473                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9474                         SDFlags);
9475     else
9476       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9477     break;
9478   case Intrinsic::vector_reduce_add:
9479     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9480     break;
9481   case Intrinsic::vector_reduce_mul:
9482     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9483     break;
9484   case Intrinsic::vector_reduce_and:
9485     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9486     break;
9487   case Intrinsic::vector_reduce_or:
9488     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9489     break;
9490   case Intrinsic::vector_reduce_xor:
9491     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9492     break;
9493   case Intrinsic::vector_reduce_smax:
9494     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9495     break;
9496   case Intrinsic::vector_reduce_smin:
9497     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9498     break;
9499   case Intrinsic::vector_reduce_umax:
9500     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9501     break;
9502   case Intrinsic::vector_reduce_umin:
9503     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9504     break;
9505   case Intrinsic::vector_reduce_fmax:
9506     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9507     break;
9508   case Intrinsic::vector_reduce_fmin:
9509     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9510     break;
9511   default:
9512     llvm_unreachable("Unhandled vector reduce intrinsic");
9513   }
9514   setValue(&I, Res);
9515 }
9516 
9517 /// Returns an AttributeList representing the attributes applied to the return
9518 /// value of the given call.
9519 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9520   SmallVector<Attribute::AttrKind, 2> Attrs;
9521   if (CLI.RetSExt)
9522     Attrs.push_back(Attribute::SExt);
9523   if (CLI.RetZExt)
9524     Attrs.push_back(Attribute::ZExt);
9525   if (CLI.IsInReg)
9526     Attrs.push_back(Attribute::InReg);
9527 
9528   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9529                             Attrs);
9530 }
9531 
9532 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9533 /// implementation, which just calls LowerCall.
9534 /// FIXME: When all targets are
9535 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9536 std::pair<SDValue, SDValue>
9537 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9538   // Handle the incoming return values from the call.
9539   CLI.Ins.clear();
9540   Type *OrigRetTy = CLI.RetTy;
9541   SmallVector<EVT, 4> RetTys;
9542   SmallVector<uint64_t, 4> Offsets;
9543   auto &DL = CLI.DAG.getDataLayout();
9544   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9545 
9546   if (CLI.IsPostTypeLegalization) {
9547     // If we are lowering a libcall after legalization, split the return type.
9548     SmallVector<EVT, 4> OldRetTys;
9549     SmallVector<uint64_t, 4> OldOffsets;
9550     RetTys.swap(OldRetTys);
9551     Offsets.swap(OldOffsets);
9552 
9553     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9554       EVT RetVT = OldRetTys[i];
9555       uint64_t Offset = OldOffsets[i];
9556       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9557       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9558       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9559       RetTys.append(NumRegs, RegisterVT);
9560       for (unsigned j = 0; j != NumRegs; ++j)
9561         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9562     }
9563   }
9564 
9565   SmallVector<ISD::OutputArg, 4> Outs;
9566   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9567 
9568   bool CanLowerReturn =
9569       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9570                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9571 
9572   SDValue DemoteStackSlot;
9573   int DemoteStackIdx = -100;
9574   if (!CanLowerReturn) {
9575     // FIXME: equivalent assert?
9576     // assert(!CS.hasInAllocaArgument() &&
9577     //        "sret demotion is incompatible with inalloca");
9578     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9579     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9580     MachineFunction &MF = CLI.DAG.getMachineFunction();
9581     DemoteStackIdx =
9582         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9583     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9584                                               DL.getAllocaAddrSpace());
9585 
9586     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9587     ArgListEntry Entry;
9588     Entry.Node = DemoteStackSlot;
9589     Entry.Ty = StackSlotPtrType;
9590     Entry.IsSExt = false;
9591     Entry.IsZExt = false;
9592     Entry.IsInReg = false;
9593     Entry.IsSRet = true;
9594     Entry.IsNest = false;
9595     Entry.IsByVal = false;
9596     Entry.IsByRef = false;
9597     Entry.IsReturned = false;
9598     Entry.IsSwiftSelf = false;
9599     Entry.IsSwiftAsync = false;
9600     Entry.IsSwiftError = false;
9601     Entry.IsCFGuardTarget = false;
9602     Entry.Alignment = Alignment;
9603     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9604     CLI.NumFixedArgs += 1;
9605     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9606 
9607     // sret demotion isn't compatible with tail-calls, since the sret argument
9608     // points into the callers stack frame.
9609     CLI.IsTailCall = false;
9610   } else {
9611     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9612         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9613     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9614       ISD::ArgFlagsTy Flags;
9615       if (NeedsRegBlock) {
9616         Flags.setInConsecutiveRegs();
9617         if (I == RetTys.size() - 1)
9618           Flags.setInConsecutiveRegsLast();
9619       }
9620       EVT VT = RetTys[I];
9621       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9622                                                      CLI.CallConv, VT);
9623       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9624                                                        CLI.CallConv, VT);
9625       for (unsigned i = 0; i != NumRegs; ++i) {
9626         ISD::InputArg MyFlags;
9627         MyFlags.Flags = Flags;
9628         MyFlags.VT = RegisterVT;
9629         MyFlags.ArgVT = VT;
9630         MyFlags.Used = CLI.IsReturnValueUsed;
9631         if (CLI.RetTy->isPointerTy()) {
9632           MyFlags.Flags.setPointer();
9633           MyFlags.Flags.setPointerAddrSpace(
9634               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9635         }
9636         if (CLI.RetSExt)
9637           MyFlags.Flags.setSExt();
9638         if (CLI.RetZExt)
9639           MyFlags.Flags.setZExt();
9640         if (CLI.IsInReg)
9641           MyFlags.Flags.setInReg();
9642         CLI.Ins.push_back(MyFlags);
9643       }
9644     }
9645   }
9646 
9647   // We push in swifterror return as the last element of CLI.Ins.
9648   ArgListTy &Args = CLI.getArgs();
9649   if (supportSwiftError()) {
9650     for (const ArgListEntry &Arg : Args) {
9651       if (Arg.IsSwiftError) {
9652         ISD::InputArg MyFlags;
9653         MyFlags.VT = getPointerTy(DL);
9654         MyFlags.ArgVT = EVT(getPointerTy(DL));
9655         MyFlags.Flags.setSwiftError();
9656         CLI.Ins.push_back(MyFlags);
9657       }
9658     }
9659   }
9660 
9661   // Handle all of the outgoing arguments.
9662   CLI.Outs.clear();
9663   CLI.OutVals.clear();
9664   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9665     SmallVector<EVT, 4> ValueVTs;
9666     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9667     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9668     Type *FinalType = Args[i].Ty;
9669     if (Args[i].IsByVal)
9670       FinalType = Args[i].IndirectType;
9671     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9672         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9673     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9674          ++Value) {
9675       EVT VT = ValueVTs[Value];
9676       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9677       SDValue Op = SDValue(Args[i].Node.getNode(),
9678                            Args[i].Node.getResNo() + Value);
9679       ISD::ArgFlagsTy Flags;
9680 
9681       // Certain targets (such as MIPS), may have a different ABI alignment
9682       // for a type depending on the context. Give the target a chance to
9683       // specify the alignment it wants.
9684       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9685       Flags.setOrigAlign(OriginalAlignment);
9686 
9687       if (Args[i].Ty->isPointerTy()) {
9688         Flags.setPointer();
9689         Flags.setPointerAddrSpace(
9690             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9691       }
9692       if (Args[i].IsZExt)
9693         Flags.setZExt();
9694       if (Args[i].IsSExt)
9695         Flags.setSExt();
9696       if (Args[i].IsInReg) {
9697         // If we are using vectorcall calling convention, a structure that is
9698         // passed InReg - is surely an HVA
9699         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9700             isa<StructType>(FinalType)) {
9701           // The first value of a structure is marked
9702           if (0 == Value)
9703             Flags.setHvaStart();
9704           Flags.setHva();
9705         }
9706         // Set InReg Flag
9707         Flags.setInReg();
9708       }
9709       if (Args[i].IsSRet)
9710         Flags.setSRet();
9711       if (Args[i].IsSwiftSelf)
9712         Flags.setSwiftSelf();
9713       if (Args[i].IsSwiftAsync)
9714         Flags.setSwiftAsync();
9715       if (Args[i].IsSwiftError)
9716         Flags.setSwiftError();
9717       if (Args[i].IsCFGuardTarget)
9718         Flags.setCFGuardTarget();
9719       if (Args[i].IsByVal)
9720         Flags.setByVal();
9721       if (Args[i].IsByRef)
9722         Flags.setByRef();
9723       if (Args[i].IsPreallocated) {
9724         Flags.setPreallocated();
9725         // Set the byval flag for CCAssignFn callbacks that don't know about
9726         // preallocated.  This way we can know how many bytes we should've
9727         // allocated and how many bytes a callee cleanup function will pop.  If
9728         // we port preallocated to more targets, we'll have to add custom
9729         // preallocated handling in the various CC lowering callbacks.
9730         Flags.setByVal();
9731       }
9732       if (Args[i].IsInAlloca) {
9733         Flags.setInAlloca();
9734         // Set the byval flag for CCAssignFn callbacks that don't know about
9735         // inalloca.  This way we can know how many bytes we should've allocated
9736         // and how many bytes a callee cleanup function will pop.  If we port
9737         // inalloca to more targets, we'll have to add custom inalloca handling
9738         // in the various CC lowering callbacks.
9739         Flags.setByVal();
9740       }
9741       Align MemAlign;
9742       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9743         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9744         Flags.setByValSize(FrameSize);
9745 
9746         // info is not there but there are cases it cannot get right.
9747         if (auto MA = Args[i].Alignment)
9748           MemAlign = *MA;
9749         else
9750           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9751       } else if (auto MA = Args[i].Alignment) {
9752         MemAlign = *MA;
9753       } else {
9754         MemAlign = OriginalAlignment;
9755       }
9756       Flags.setMemAlign(MemAlign);
9757       if (Args[i].IsNest)
9758         Flags.setNest();
9759       if (NeedsRegBlock)
9760         Flags.setInConsecutiveRegs();
9761 
9762       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9763                                                  CLI.CallConv, VT);
9764       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9765                                                         CLI.CallConv, VT);
9766       SmallVector<SDValue, 4> Parts(NumParts);
9767       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9768 
9769       if (Args[i].IsSExt)
9770         ExtendKind = ISD::SIGN_EXTEND;
9771       else if (Args[i].IsZExt)
9772         ExtendKind = ISD::ZERO_EXTEND;
9773 
9774       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9775       // for now.
9776       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9777           CanLowerReturn) {
9778         assert((CLI.RetTy == Args[i].Ty ||
9779                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9780                  CLI.RetTy->getPointerAddressSpace() ==
9781                      Args[i].Ty->getPointerAddressSpace())) &&
9782                RetTys.size() == NumValues && "unexpected use of 'returned'");
9783         // Before passing 'returned' to the target lowering code, ensure that
9784         // either the register MVT and the actual EVT are the same size or that
9785         // the return value and argument are extended in the same way; in these
9786         // cases it's safe to pass the argument register value unchanged as the
9787         // return register value (although it's at the target's option whether
9788         // to do so)
9789         // TODO: allow code generation to take advantage of partially preserved
9790         // registers rather than clobbering the entire register when the
9791         // parameter extension method is not compatible with the return
9792         // extension method
9793         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9794             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9795              CLI.RetZExt == Args[i].IsZExt))
9796           Flags.setReturned();
9797       }
9798 
9799       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9800                      CLI.CallConv, ExtendKind);
9801 
9802       for (unsigned j = 0; j != NumParts; ++j) {
9803         // if it isn't first piece, alignment must be 1
9804         // For scalable vectors the scalable part is currently handled
9805         // by individual targets, so we just use the known minimum size here.
9806         ISD::OutputArg MyFlags(
9807             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9808             i < CLI.NumFixedArgs, i,
9809             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
9810         if (NumParts > 1 && j == 0)
9811           MyFlags.Flags.setSplit();
9812         else if (j != 0) {
9813           MyFlags.Flags.setOrigAlign(Align(1));
9814           if (j == NumParts - 1)
9815             MyFlags.Flags.setSplitEnd();
9816         }
9817 
9818         CLI.Outs.push_back(MyFlags);
9819         CLI.OutVals.push_back(Parts[j]);
9820       }
9821 
9822       if (NeedsRegBlock && Value == NumValues - 1)
9823         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9824     }
9825   }
9826 
9827   SmallVector<SDValue, 4> InVals;
9828   CLI.Chain = LowerCall(CLI, InVals);
9829 
9830   // Update CLI.InVals to use outside of this function.
9831   CLI.InVals = InVals;
9832 
9833   // Verify that the target's LowerCall behaved as expected.
9834   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9835          "LowerCall didn't return a valid chain!");
9836   assert((!CLI.IsTailCall || InVals.empty()) &&
9837          "LowerCall emitted a return value for a tail call!");
9838   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9839          "LowerCall didn't emit the correct number of values!");
9840 
9841   // For a tail call, the return value is merely live-out and there aren't
9842   // any nodes in the DAG representing it. Return a special value to
9843   // indicate that a tail call has been emitted and no more Instructions
9844   // should be processed in the current block.
9845   if (CLI.IsTailCall) {
9846     CLI.DAG.setRoot(CLI.Chain);
9847     return std::make_pair(SDValue(), SDValue());
9848   }
9849 
9850 #ifndef NDEBUG
9851   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9852     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9853     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9854            "LowerCall emitted a value with the wrong type!");
9855   }
9856 #endif
9857 
9858   SmallVector<SDValue, 4> ReturnValues;
9859   if (!CanLowerReturn) {
9860     // The instruction result is the result of loading from the
9861     // hidden sret parameter.
9862     SmallVector<EVT, 1> PVTs;
9863     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9864 
9865     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9866     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9867     EVT PtrVT = PVTs[0];
9868 
9869     unsigned NumValues = RetTys.size();
9870     ReturnValues.resize(NumValues);
9871     SmallVector<SDValue, 4> Chains(NumValues);
9872 
9873     // An aggregate return value cannot wrap around the address space, so
9874     // offsets to its parts don't wrap either.
9875     SDNodeFlags Flags;
9876     Flags.setNoUnsignedWrap(true);
9877 
9878     MachineFunction &MF = CLI.DAG.getMachineFunction();
9879     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9880     for (unsigned i = 0; i < NumValues; ++i) {
9881       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9882                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9883                                                         PtrVT), Flags);
9884       SDValue L = CLI.DAG.getLoad(
9885           RetTys[i], CLI.DL, CLI.Chain, Add,
9886           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9887                                             DemoteStackIdx, Offsets[i]),
9888           HiddenSRetAlign);
9889       ReturnValues[i] = L;
9890       Chains[i] = L.getValue(1);
9891     }
9892 
9893     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9894   } else {
9895     // Collect the legal value parts into potentially illegal values
9896     // that correspond to the original function's return values.
9897     Optional<ISD::NodeType> AssertOp;
9898     if (CLI.RetSExt)
9899       AssertOp = ISD::AssertSext;
9900     else if (CLI.RetZExt)
9901       AssertOp = ISD::AssertZext;
9902     unsigned CurReg = 0;
9903     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9904       EVT VT = RetTys[I];
9905       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9906                                                      CLI.CallConv, VT);
9907       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9908                                                        CLI.CallConv, VT);
9909 
9910       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9911                                               NumRegs, RegisterVT, VT, nullptr,
9912                                               CLI.CallConv, AssertOp));
9913       CurReg += NumRegs;
9914     }
9915 
9916     // For a function returning void, there is no return value. We can't create
9917     // such a node, so we just return a null return value in that case. In
9918     // that case, nothing will actually look at the value.
9919     if (ReturnValues.empty())
9920       return std::make_pair(SDValue(), CLI.Chain);
9921   }
9922 
9923   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9924                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9925   return std::make_pair(Res, CLI.Chain);
9926 }
9927 
9928 /// Places new result values for the node in Results (their number
9929 /// and types must exactly match those of the original return values of
9930 /// the node), or leaves Results empty, which indicates that the node is not
9931 /// to be custom lowered after all.
9932 void TargetLowering::LowerOperationWrapper(SDNode *N,
9933                                            SmallVectorImpl<SDValue> &Results,
9934                                            SelectionDAG &DAG) const {
9935   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9936 
9937   if (!Res.getNode())
9938     return;
9939 
9940   // If the original node has one result, take the return value from
9941   // LowerOperation as is. It might not be result number 0.
9942   if (N->getNumValues() == 1) {
9943     Results.push_back(Res);
9944     return;
9945   }
9946 
9947   // If the original node has multiple results, then the return node should
9948   // have the same number of results.
9949   assert((N->getNumValues() == Res->getNumValues()) &&
9950       "Lowering returned the wrong number of results!");
9951 
9952   // Places new result values base on N result number.
9953   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9954     Results.push_back(Res.getValue(I));
9955 }
9956 
9957 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9958   llvm_unreachable("LowerOperation not implemented for this target!");
9959 }
9960 
9961 void
9962 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9963   SDValue Op = getNonRegisterValue(V);
9964   assert((Op.getOpcode() != ISD::CopyFromReg ||
9965           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9966          "Copy from a reg to the same reg!");
9967   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9968 
9969   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9970   // If this is an InlineAsm we have to match the registers required, not the
9971   // notional registers required by the type.
9972 
9973   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9974                    None); // This is not an ABI copy.
9975   SDValue Chain = DAG.getEntryNode();
9976 
9977   ISD::NodeType ExtendType = ISD::ANY_EXTEND;
9978   auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
9979   if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
9980     ExtendType = PreferredExtendIt->second;
9981   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9982   PendingExports.push_back(Chain);
9983 }
9984 
9985 #include "llvm/CodeGen/SelectionDAGISel.h"
9986 
9987 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9988 /// entry block, return true.  This includes arguments used by switches, since
9989 /// the switch may expand into multiple basic blocks.
9990 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9991   // With FastISel active, we may be splitting blocks, so force creation
9992   // of virtual registers for all non-dead arguments.
9993   if (FastISel)
9994     return A->use_empty();
9995 
9996   const BasicBlock &Entry = A->getParent()->front();
9997   for (const User *U : A->users())
9998     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9999       return false;  // Use not in entry block.
10000 
10001   return true;
10002 }
10003 
10004 using ArgCopyElisionMapTy =
10005     DenseMap<const Argument *,
10006              std::pair<const AllocaInst *, const StoreInst *>>;
10007 
10008 /// Scan the entry block of the function in FuncInfo for arguments that look
10009 /// like copies into a local alloca. Record any copied arguments in
10010 /// ArgCopyElisionCandidates.
10011 static void
10012 findArgumentCopyElisionCandidates(const DataLayout &DL,
10013                                   FunctionLoweringInfo *FuncInfo,
10014                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10015   // Record the state of every static alloca used in the entry block. Argument
10016   // allocas are all used in the entry block, so we need approximately as many
10017   // entries as we have arguments.
10018   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10019   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10020   unsigned NumArgs = FuncInfo->Fn->arg_size();
10021   StaticAllocas.reserve(NumArgs * 2);
10022 
10023   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10024     if (!V)
10025       return nullptr;
10026     V = V->stripPointerCasts();
10027     const auto *AI = dyn_cast<AllocaInst>(V);
10028     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10029       return nullptr;
10030     auto Iter = StaticAllocas.insert({AI, Unknown});
10031     return &Iter.first->second;
10032   };
10033 
10034   // Look for stores of arguments to static allocas. Look through bitcasts and
10035   // GEPs to handle type coercions, as long as the alloca is fully initialized
10036   // by the store. Any non-store use of an alloca escapes it and any subsequent
10037   // unanalyzed store might write it.
10038   // FIXME: Handle structs initialized with multiple stores.
10039   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10040     // Look for stores, and handle non-store uses conservatively.
10041     const auto *SI = dyn_cast<StoreInst>(&I);
10042     if (!SI) {
10043       // We will look through cast uses, so ignore them completely.
10044       if (I.isCast())
10045         continue;
10046       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10047       // to allocas.
10048       if (I.isDebugOrPseudoInst())
10049         continue;
10050       // This is an unknown instruction. Assume it escapes or writes to all
10051       // static alloca operands.
10052       for (const Use &U : I.operands()) {
10053         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10054           *Info = StaticAllocaInfo::Clobbered;
10055       }
10056       continue;
10057     }
10058 
10059     // If the stored value is a static alloca, mark it as escaped.
10060     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10061       *Info = StaticAllocaInfo::Clobbered;
10062 
10063     // Check if the destination is a static alloca.
10064     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10065     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10066     if (!Info)
10067       continue;
10068     const AllocaInst *AI = cast<AllocaInst>(Dst);
10069 
10070     // Skip allocas that have been initialized or clobbered.
10071     if (*Info != StaticAllocaInfo::Unknown)
10072       continue;
10073 
10074     // Check if the stored value is an argument, and that this store fully
10075     // initializes the alloca.
10076     // If the argument type has padding bits we can't directly forward a pointer
10077     // as the upper bits may contain garbage.
10078     // Don't elide copies from the same argument twice.
10079     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10080     const auto *Arg = dyn_cast<Argument>(Val);
10081     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10082         Arg->getType()->isEmptyTy() ||
10083         DL.getTypeStoreSize(Arg->getType()) !=
10084             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10085         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10086         ArgCopyElisionCandidates.count(Arg)) {
10087       *Info = StaticAllocaInfo::Clobbered;
10088       continue;
10089     }
10090 
10091     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10092                       << '\n');
10093 
10094     // Mark this alloca and store for argument copy elision.
10095     *Info = StaticAllocaInfo::Elidable;
10096     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10097 
10098     // Stop scanning if we've seen all arguments. This will happen early in -O0
10099     // builds, which is useful, because -O0 builds have large entry blocks and
10100     // many allocas.
10101     if (ArgCopyElisionCandidates.size() == NumArgs)
10102       break;
10103   }
10104 }
10105 
10106 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10107 /// ArgVal is a load from a suitable fixed stack object.
10108 static void tryToElideArgumentCopy(
10109     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10110     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10111     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10112     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10113     SDValue ArgVal, bool &ArgHasUses) {
10114   // Check if this is a load from a fixed stack object.
10115   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10116   if (!LNode)
10117     return;
10118   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10119   if (!FINode)
10120     return;
10121 
10122   // Check that the fixed stack object is the right size and alignment.
10123   // Look at the alignment that the user wrote on the alloca instead of looking
10124   // at the stack object.
10125   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10126   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10127   const AllocaInst *AI = ArgCopyIter->second.first;
10128   int FixedIndex = FINode->getIndex();
10129   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10130   int OldIndex = AllocaIndex;
10131   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10132   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10133     LLVM_DEBUG(
10134         dbgs() << "  argument copy elision failed due to bad fixed stack "
10135                   "object size\n");
10136     return;
10137   }
10138   Align RequiredAlignment = AI->getAlign();
10139   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10140     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10141                          "greater than stack argument alignment ("
10142                       << DebugStr(RequiredAlignment) << " vs "
10143                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10144     return;
10145   }
10146 
10147   // Perform the elision. Delete the old stack object and replace its only use
10148   // in the variable info map. Mark the stack object as mutable.
10149   LLVM_DEBUG({
10150     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10151            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10152            << '\n';
10153   });
10154   MFI.RemoveStackObject(OldIndex);
10155   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10156   AllocaIndex = FixedIndex;
10157   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10158   Chains.push_back(ArgVal.getValue(1));
10159 
10160   // Avoid emitting code for the store implementing the copy.
10161   const StoreInst *SI = ArgCopyIter->second.second;
10162   ElidedArgCopyInstrs.insert(SI);
10163 
10164   // Check for uses of the argument again so that we can avoid exporting ArgVal
10165   // if it is't used by anything other than the store.
10166   for (const Value *U : Arg.users()) {
10167     if (U != SI) {
10168       ArgHasUses = true;
10169       break;
10170     }
10171   }
10172 }
10173 
10174 void SelectionDAGISel::LowerArguments(const Function &F) {
10175   SelectionDAG &DAG = SDB->DAG;
10176   SDLoc dl = SDB->getCurSDLoc();
10177   const DataLayout &DL = DAG.getDataLayout();
10178   SmallVector<ISD::InputArg, 16> Ins;
10179 
10180   // In Naked functions we aren't going to save any registers.
10181   if (F.hasFnAttribute(Attribute::Naked))
10182     return;
10183 
10184   if (!FuncInfo->CanLowerReturn) {
10185     // Put in an sret pointer parameter before all the other parameters.
10186     SmallVector<EVT, 1> ValueVTs;
10187     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10188                     F.getReturnType()->getPointerTo(
10189                         DAG.getDataLayout().getAllocaAddrSpace()),
10190                     ValueVTs);
10191 
10192     // NOTE: Assuming that a pointer will never break down to more than one VT
10193     // or one register.
10194     ISD::ArgFlagsTy Flags;
10195     Flags.setSRet();
10196     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10197     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10198                          ISD::InputArg::NoArgIndex, 0);
10199     Ins.push_back(RetArg);
10200   }
10201 
10202   // Look for stores of arguments to static allocas. Mark such arguments with a
10203   // flag to ask the target to give us the memory location of that argument if
10204   // available.
10205   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10206   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10207                                     ArgCopyElisionCandidates);
10208 
10209   // Set up the incoming argument description vector.
10210   for (const Argument &Arg : F.args()) {
10211     unsigned ArgNo = Arg.getArgNo();
10212     SmallVector<EVT, 4> ValueVTs;
10213     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10214     bool isArgValueUsed = !Arg.use_empty();
10215     unsigned PartBase = 0;
10216     Type *FinalType = Arg.getType();
10217     if (Arg.hasAttribute(Attribute::ByVal))
10218       FinalType = Arg.getParamByValType();
10219     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10220         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10221     for (unsigned Value = 0, NumValues = ValueVTs.size();
10222          Value != NumValues; ++Value) {
10223       EVT VT = ValueVTs[Value];
10224       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10225       ISD::ArgFlagsTy Flags;
10226 
10227 
10228       if (Arg.getType()->isPointerTy()) {
10229         Flags.setPointer();
10230         Flags.setPointerAddrSpace(
10231             cast<PointerType>(Arg.getType())->getAddressSpace());
10232       }
10233       if (Arg.hasAttribute(Attribute::ZExt))
10234         Flags.setZExt();
10235       if (Arg.hasAttribute(Attribute::SExt))
10236         Flags.setSExt();
10237       if (Arg.hasAttribute(Attribute::InReg)) {
10238         // If we are using vectorcall calling convention, a structure that is
10239         // passed InReg - is surely an HVA
10240         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10241             isa<StructType>(Arg.getType())) {
10242           // The first value of a structure is marked
10243           if (0 == Value)
10244             Flags.setHvaStart();
10245           Flags.setHva();
10246         }
10247         // Set InReg Flag
10248         Flags.setInReg();
10249       }
10250       if (Arg.hasAttribute(Attribute::StructRet))
10251         Flags.setSRet();
10252       if (Arg.hasAttribute(Attribute::SwiftSelf))
10253         Flags.setSwiftSelf();
10254       if (Arg.hasAttribute(Attribute::SwiftAsync))
10255         Flags.setSwiftAsync();
10256       if (Arg.hasAttribute(Attribute::SwiftError))
10257         Flags.setSwiftError();
10258       if (Arg.hasAttribute(Attribute::ByVal))
10259         Flags.setByVal();
10260       if (Arg.hasAttribute(Attribute::ByRef))
10261         Flags.setByRef();
10262       if (Arg.hasAttribute(Attribute::InAlloca)) {
10263         Flags.setInAlloca();
10264         // Set the byval flag for CCAssignFn callbacks that don't know about
10265         // inalloca.  This way we can know how many bytes we should've allocated
10266         // and how many bytes a callee cleanup function will pop.  If we port
10267         // inalloca to more targets, we'll have to add custom inalloca handling
10268         // in the various CC lowering callbacks.
10269         Flags.setByVal();
10270       }
10271       if (Arg.hasAttribute(Attribute::Preallocated)) {
10272         Flags.setPreallocated();
10273         // Set the byval flag for CCAssignFn callbacks that don't know about
10274         // preallocated.  This way we can know how many bytes we should've
10275         // allocated and how many bytes a callee cleanup function will pop.  If
10276         // we port preallocated to more targets, we'll have to add custom
10277         // preallocated handling in the various CC lowering callbacks.
10278         Flags.setByVal();
10279       }
10280 
10281       // Certain targets (such as MIPS), may have a different ABI alignment
10282       // for a type depending on the context. Give the target a chance to
10283       // specify the alignment it wants.
10284       const Align OriginalAlignment(
10285           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10286       Flags.setOrigAlign(OriginalAlignment);
10287 
10288       Align MemAlign;
10289       Type *ArgMemTy = nullptr;
10290       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10291           Flags.isByRef()) {
10292         if (!ArgMemTy)
10293           ArgMemTy = Arg.getPointeeInMemoryValueType();
10294 
10295         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10296 
10297         // For in-memory arguments, size and alignment should be passed from FE.
10298         // BE will guess if this info is not there but there are cases it cannot
10299         // get right.
10300         if (auto ParamAlign = Arg.getParamStackAlign())
10301           MemAlign = *ParamAlign;
10302         else if ((ParamAlign = Arg.getParamAlign()))
10303           MemAlign = *ParamAlign;
10304         else
10305           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10306         if (Flags.isByRef())
10307           Flags.setByRefSize(MemSize);
10308         else
10309           Flags.setByValSize(MemSize);
10310       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10311         MemAlign = *ParamAlign;
10312       } else {
10313         MemAlign = OriginalAlignment;
10314       }
10315       Flags.setMemAlign(MemAlign);
10316 
10317       if (Arg.hasAttribute(Attribute::Nest))
10318         Flags.setNest();
10319       if (NeedsRegBlock)
10320         Flags.setInConsecutiveRegs();
10321       if (ArgCopyElisionCandidates.count(&Arg))
10322         Flags.setCopyElisionCandidate();
10323       if (Arg.hasAttribute(Attribute::Returned))
10324         Flags.setReturned();
10325 
10326       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10327           *CurDAG->getContext(), F.getCallingConv(), VT);
10328       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10329           *CurDAG->getContext(), F.getCallingConv(), VT);
10330       for (unsigned i = 0; i != NumRegs; ++i) {
10331         // For scalable vectors, use the minimum size; individual targets
10332         // are responsible for handling scalable vector arguments and
10333         // return values.
10334         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10335                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10336         if (NumRegs > 1 && i == 0)
10337           MyFlags.Flags.setSplit();
10338         // if it isn't first piece, alignment must be 1
10339         else if (i > 0) {
10340           MyFlags.Flags.setOrigAlign(Align(1));
10341           if (i == NumRegs - 1)
10342             MyFlags.Flags.setSplitEnd();
10343         }
10344         Ins.push_back(MyFlags);
10345       }
10346       if (NeedsRegBlock && Value == NumValues - 1)
10347         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10348       PartBase += VT.getStoreSize().getKnownMinSize();
10349     }
10350   }
10351 
10352   // Call the target to set up the argument values.
10353   SmallVector<SDValue, 8> InVals;
10354   SDValue NewRoot = TLI->LowerFormalArguments(
10355       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10356 
10357   // Verify that the target's LowerFormalArguments behaved as expected.
10358   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10359          "LowerFormalArguments didn't return a valid chain!");
10360   assert(InVals.size() == Ins.size() &&
10361          "LowerFormalArguments didn't emit the correct number of values!");
10362   LLVM_DEBUG({
10363     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10364       assert(InVals[i].getNode() &&
10365              "LowerFormalArguments emitted a null value!");
10366       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10367              "LowerFormalArguments emitted a value with the wrong type!");
10368     }
10369   });
10370 
10371   // Update the DAG with the new chain value resulting from argument lowering.
10372   DAG.setRoot(NewRoot);
10373 
10374   // Set up the argument values.
10375   unsigned i = 0;
10376   if (!FuncInfo->CanLowerReturn) {
10377     // Create a virtual register for the sret pointer, and put in a copy
10378     // from the sret argument into it.
10379     SmallVector<EVT, 1> ValueVTs;
10380     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10381                     F.getReturnType()->getPointerTo(
10382                         DAG.getDataLayout().getAllocaAddrSpace()),
10383                     ValueVTs);
10384     MVT VT = ValueVTs[0].getSimpleVT();
10385     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10386     Optional<ISD::NodeType> AssertOp = None;
10387     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10388                                         nullptr, F.getCallingConv(), AssertOp);
10389 
10390     MachineFunction& MF = SDB->DAG.getMachineFunction();
10391     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10392     Register SRetReg =
10393         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10394     FuncInfo->DemoteRegister = SRetReg;
10395     NewRoot =
10396         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10397     DAG.setRoot(NewRoot);
10398 
10399     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10400     ++i;
10401   }
10402 
10403   SmallVector<SDValue, 4> Chains;
10404   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10405   for (const Argument &Arg : F.args()) {
10406     SmallVector<SDValue, 4> ArgValues;
10407     SmallVector<EVT, 4> ValueVTs;
10408     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10409     unsigned NumValues = ValueVTs.size();
10410     if (NumValues == 0)
10411       continue;
10412 
10413     bool ArgHasUses = !Arg.use_empty();
10414 
10415     // Elide the copying store if the target loaded this argument from a
10416     // suitable fixed stack object.
10417     if (Ins[i].Flags.isCopyElisionCandidate()) {
10418       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10419                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10420                              InVals[i], ArgHasUses);
10421     }
10422 
10423     // If this argument is unused then remember its value. It is used to generate
10424     // debugging information.
10425     bool isSwiftErrorArg =
10426         TLI->supportSwiftError() &&
10427         Arg.hasAttribute(Attribute::SwiftError);
10428     if (!ArgHasUses && !isSwiftErrorArg) {
10429       SDB->setUnusedArgValue(&Arg, InVals[i]);
10430 
10431       // Also remember any frame index for use in FastISel.
10432       if (FrameIndexSDNode *FI =
10433           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10434         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10435     }
10436 
10437     for (unsigned Val = 0; Val != NumValues; ++Val) {
10438       EVT VT = ValueVTs[Val];
10439       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10440                                                       F.getCallingConv(), VT);
10441       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10442           *CurDAG->getContext(), F.getCallingConv(), VT);
10443 
10444       // Even an apparent 'unused' swifterror argument needs to be returned. So
10445       // we do generate a copy for it that can be used on return from the
10446       // function.
10447       if (ArgHasUses || isSwiftErrorArg) {
10448         Optional<ISD::NodeType> AssertOp;
10449         if (Arg.hasAttribute(Attribute::SExt))
10450           AssertOp = ISD::AssertSext;
10451         else if (Arg.hasAttribute(Attribute::ZExt))
10452           AssertOp = ISD::AssertZext;
10453 
10454         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10455                                              PartVT, VT, nullptr,
10456                                              F.getCallingConv(), AssertOp));
10457       }
10458 
10459       i += NumParts;
10460     }
10461 
10462     // We don't need to do anything else for unused arguments.
10463     if (ArgValues.empty())
10464       continue;
10465 
10466     // Note down frame index.
10467     if (FrameIndexSDNode *FI =
10468         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10469       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10470 
10471     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10472                                      SDB->getCurSDLoc());
10473 
10474     SDB->setValue(&Arg, Res);
10475     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10476       // We want to associate the argument with the frame index, among
10477       // involved operands, that correspond to the lowest address. The
10478       // getCopyFromParts function, called earlier, is swapping the order of
10479       // the operands to BUILD_PAIR depending on endianness. The result of
10480       // that swapping is that the least significant bits of the argument will
10481       // be in the first operand of the BUILD_PAIR node, and the most
10482       // significant bits will be in the second operand.
10483       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10484       if (LoadSDNode *LNode =
10485           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10486         if (FrameIndexSDNode *FI =
10487             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10488           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10489     }
10490 
10491     // Analyses past this point are naive and don't expect an assertion.
10492     if (Res.getOpcode() == ISD::AssertZext)
10493       Res = Res.getOperand(0);
10494 
10495     // Update the SwiftErrorVRegDefMap.
10496     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10497       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10498       if (Register::isVirtualRegister(Reg))
10499         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10500                                    Reg);
10501     }
10502 
10503     // If this argument is live outside of the entry block, insert a copy from
10504     // wherever we got it to the vreg that other BB's will reference it as.
10505     if (Res.getOpcode() == ISD::CopyFromReg) {
10506       // If we can, though, try to skip creating an unnecessary vreg.
10507       // FIXME: This isn't very clean... it would be nice to make this more
10508       // general.
10509       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10510       if (Register::isVirtualRegister(Reg)) {
10511         FuncInfo->ValueMap[&Arg] = Reg;
10512         continue;
10513       }
10514     }
10515     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10516       FuncInfo->InitializeRegForValue(&Arg);
10517       SDB->CopyToExportRegsIfNeeded(&Arg);
10518     }
10519   }
10520 
10521   if (!Chains.empty()) {
10522     Chains.push_back(NewRoot);
10523     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10524   }
10525 
10526   DAG.setRoot(NewRoot);
10527 
10528   assert(i == InVals.size() && "Argument register count mismatch!");
10529 
10530   // If any argument copy elisions occurred and we have debug info, update the
10531   // stale frame indices used in the dbg.declare variable info table.
10532   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10533   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10534     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10535       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10536       if (I != ArgCopyElisionFrameIndexMap.end())
10537         VI.Slot = I->second;
10538     }
10539   }
10540 
10541   // Finally, if the target has anything special to do, allow it to do so.
10542   emitFunctionEntryCode();
10543 }
10544 
10545 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10546 /// ensure constants are generated when needed.  Remember the virtual registers
10547 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10548 /// directly add them, because expansion might result in multiple MBB's for one
10549 /// BB.  As such, the start of the BB might correspond to a different MBB than
10550 /// the end.
10551 void
10552 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10553   const Instruction *TI = LLVMBB->getTerminator();
10554 
10555   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10556 
10557   // Check PHI nodes in successors that expect a value to be available from this
10558   // block.
10559   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10560     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10561     if (!isa<PHINode>(SuccBB->begin())) continue;
10562     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10563 
10564     // If this terminator has multiple identical successors (common for
10565     // switches), only handle each succ once.
10566     if (!SuccsHandled.insert(SuccMBB).second)
10567       continue;
10568 
10569     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10570 
10571     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10572     // nodes and Machine PHI nodes, but the incoming operands have not been
10573     // emitted yet.
10574     for (const PHINode &PN : SuccBB->phis()) {
10575       // Ignore dead phi's.
10576       if (PN.use_empty())
10577         continue;
10578 
10579       // Skip empty types
10580       if (PN.getType()->isEmptyTy())
10581         continue;
10582 
10583       unsigned Reg;
10584       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10585 
10586       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10587         unsigned &RegOut = ConstantsOut[C];
10588         if (RegOut == 0) {
10589           RegOut = FuncInfo.CreateRegs(C);
10590           CopyValueToVirtualRegister(C, RegOut);
10591         }
10592         Reg = RegOut;
10593       } else {
10594         DenseMap<const Value *, Register>::iterator I =
10595           FuncInfo.ValueMap.find(PHIOp);
10596         if (I != FuncInfo.ValueMap.end())
10597           Reg = I->second;
10598         else {
10599           assert(isa<AllocaInst>(PHIOp) &&
10600                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10601                  "Didn't codegen value into a register!??");
10602           Reg = FuncInfo.CreateRegs(PHIOp);
10603           CopyValueToVirtualRegister(PHIOp, Reg);
10604         }
10605       }
10606 
10607       // Remember that this register needs to added to the machine PHI node as
10608       // the input for this MBB.
10609       SmallVector<EVT, 4> ValueVTs;
10610       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10611       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10612       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10613         EVT VT = ValueVTs[vti];
10614         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10615         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10616           FuncInfo.PHINodesToUpdate.push_back(
10617               std::make_pair(&*MBBI++, Reg + i));
10618         Reg += NumRegisters;
10619       }
10620     }
10621   }
10622 
10623   ConstantsOut.clear();
10624 }
10625 
10626 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10627   MachineFunction::iterator I(MBB);
10628   if (++I == FuncInfo.MF->end())
10629     return nullptr;
10630   return &*I;
10631 }
10632 
10633 /// During lowering new call nodes can be created (such as memset, etc.).
10634 /// Those will become new roots of the current DAG, but complications arise
10635 /// when they are tail calls. In such cases, the call lowering will update
10636 /// the root, but the builder still needs to know that a tail call has been
10637 /// lowered in order to avoid generating an additional return.
10638 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10639   // If the node is null, we do have a tail call.
10640   if (MaybeTC.getNode() != nullptr)
10641     DAG.setRoot(MaybeTC);
10642   else
10643     HasTailCall = true;
10644 }
10645 
10646 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10647                                         MachineBasicBlock *SwitchMBB,
10648                                         MachineBasicBlock *DefaultMBB) {
10649   MachineFunction *CurMF = FuncInfo.MF;
10650   MachineBasicBlock *NextMBB = nullptr;
10651   MachineFunction::iterator BBI(W.MBB);
10652   if (++BBI != FuncInfo.MF->end())
10653     NextMBB = &*BBI;
10654 
10655   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10656 
10657   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10658 
10659   if (Size == 2 && W.MBB == SwitchMBB) {
10660     // If any two of the cases has the same destination, and if one value
10661     // is the same as the other, but has one bit unset that the other has set,
10662     // use bit manipulation to do two compares at once.  For example:
10663     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10664     // TODO: This could be extended to merge any 2 cases in switches with 3
10665     // cases.
10666     // TODO: Handle cases where W.CaseBB != SwitchBB.
10667     CaseCluster &Small = *W.FirstCluster;
10668     CaseCluster &Big = *W.LastCluster;
10669 
10670     if (Small.Low == Small.High && Big.Low == Big.High &&
10671         Small.MBB == Big.MBB) {
10672       const APInt &SmallValue = Small.Low->getValue();
10673       const APInt &BigValue = Big.Low->getValue();
10674 
10675       // Check that there is only one bit different.
10676       APInt CommonBit = BigValue ^ SmallValue;
10677       if (CommonBit.isPowerOf2()) {
10678         SDValue CondLHS = getValue(Cond);
10679         EVT VT = CondLHS.getValueType();
10680         SDLoc DL = getCurSDLoc();
10681 
10682         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10683                                  DAG.getConstant(CommonBit, DL, VT));
10684         SDValue Cond = DAG.getSetCC(
10685             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10686             ISD::SETEQ);
10687 
10688         // Update successor info.
10689         // Both Small and Big will jump to Small.BB, so we sum up the
10690         // probabilities.
10691         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10692         if (BPI)
10693           addSuccessorWithProb(
10694               SwitchMBB, DefaultMBB,
10695               // The default destination is the first successor in IR.
10696               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10697         else
10698           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10699 
10700         // Insert the true branch.
10701         SDValue BrCond =
10702             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10703                         DAG.getBasicBlock(Small.MBB));
10704         // Insert the false branch.
10705         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10706                              DAG.getBasicBlock(DefaultMBB));
10707 
10708         DAG.setRoot(BrCond);
10709         return;
10710       }
10711     }
10712   }
10713 
10714   if (TM.getOptLevel() != CodeGenOpt::None) {
10715     // Here, we order cases by probability so the most likely case will be
10716     // checked first. However, two clusters can have the same probability in
10717     // which case their relative ordering is non-deterministic. So we use Low
10718     // as a tie-breaker as clusters are guaranteed to never overlap.
10719     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10720                [](const CaseCluster &a, const CaseCluster &b) {
10721       return a.Prob != b.Prob ?
10722              a.Prob > b.Prob :
10723              a.Low->getValue().slt(b.Low->getValue());
10724     });
10725 
10726     // Rearrange the case blocks so that the last one falls through if possible
10727     // without changing the order of probabilities.
10728     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10729       --I;
10730       if (I->Prob > W.LastCluster->Prob)
10731         break;
10732       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10733         std::swap(*I, *W.LastCluster);
10734         break;
10735       }
10736     }
10737   }
10738 
10739   // Compute total probability.
10740   BranchProbability DefaultProb = W.DefaultProb;
10741   BranchProbability UnhandledProbs = DefaultProb;
10742   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10743     UnhandledProbs += I->Prob;
10744 
10745   MachineBasicBlock *CurMBB = W.MBB;
10746   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10747     bool FallthroughUnreachable = false;
10748     MachineBasicBlock *Fallthrough;
10749     if (I == W.LastCluster) {
10750       // For the last cluster, fall through to the default destination.
10751       Fallthrough = DefaultMBB;
10752       FallthroughUnreachable = isa<UnreachableInst>(
10753           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10754     } else {
10755       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10756       CurMF->insert(BBI, Fallthrough);
10757       // Put Cond in a virtual register to make it available from the new blocks.
10758       ExportFromCurrentBlock(Cond);
10759     }
10760     UnhandledProbs -= I->Prob;
10761 
10762     switch (I->Kind) {
10763       case CC_JumpTable: {
10764         // FIXME: Optimize away range check based on pivot comparisons.
10765         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10766         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10767 
10768         // The jump block hasn't been inserted yet; insert it here.
10769         MachineBasicBlock *JumpMBB = JT->MBB;
10770         CurMF->insert(BBI, JumpMBB);
10771 
10772         auto JumpProb = I->Prob;
10773         auto FallthroughProb = UnhandledProbs;
10774 
10775         // If the default statement is a target of the jump table, we evenly
10776         // distribute the default probability to successors of CurMBB. Also
10777         // update the probability on the edge from JumpMBB to Fallthrough.
10778         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10779                                               SE = JumpMBB->succ_end();
10780              SI != SE; ++SI) {
10781           if (*SI == DefaultMBB) {
10782             JumpProb += DefaultProb / 2;
10783             FallthroughProb -= DefaultProb / 2;
10784             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10785             JumpMBB->normalizeSuccProbs();
10786             break;
10787           }
10788         }
10789 
10790         if (FallthroughUnreachable)
10791           JTH->FallthroughUnreachable = true;
10792 
10793         if (!JTH->FallthroughUnreachable)
10794           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10795         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10796         CurMBB->normalizeSuccProbs();
10797 
10798         // The jump table header will be inserted in our current block, do the
10799         // range check, and fall through to our fallthrough block.
10800         JTH->HeaderBB = CurMBB;
10801         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10802 
10803         // If we're in the right place, emit the jump table header right now.
10804         if (CurMBB == SwitchMBB) {
10805           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10806           JTH->Emitted = true;
10807         }
10808         break;
10809       }
10810       case CC_BitTests: {
10811         // FIXME: Optimize away range check based on pivot comparisons.
10812         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10813 
10814         // The bit test blocks haven't been inserted yet; insert them here.
10815         for (BitTestCase &BTC : BTB->Cases)
10816           CurMF->insert(BBI, BTC.ThisBB);
10817 
10818         // Fill in fields of the BitTestBlock.
10819         BTB->Parent = CurMBB;
10820         BTB->Default = Fallthrough;
10821 
10822         BTB->DefaultProb = UnhandledProbs;
10823         // If the cases in bit test don't form a contiguous range, we evenly
10824         // distribute the probability on the edge to Fallthrough to two
10825         // successors of CurMBB.
10826         if (!BTB->ContiguousRange) {
10827           BTB->Prob += DefaultProb / 2;
10828           BTB->DefaultProb -= DefaultProb / 2;
10829         }
10830 
10831         if (FallthroughUnreachable)
10832           BTB->FallthroughUnreachable = true;
10833 
10834         // If we're in the right place, emit the bit test header right now.
10835         if (CurMBB == SwitchMBB) {
10836           visitBitTestHeader(*BTB, SwitchMBB);
10837           BTB->Emitted = true;
10838         }
10839         break;
10840       }
10841       case CC_Range: {
10842         const Value *RHS, *LHS, *MHS;
10843         ISD::CondCode CC;
10844         if (I->Low == I->High) {
10845           // Check Cond == I->Low.
10846           CC = ISD::SETEQ;
10847           LHS = Cond;
10848           RHS=I->Low;
10849           MHS = nullptr;
10850         } else {
10851           // Check I->Low <= Cond <= I->High.
10852           CC = ISD::SETLE;
10853           LHS = I->Low;
10854           MHS = Cond;
10855           RHS = I->High;
10856         }
10857 
10858         // If Fallthrough is unreachable, fold away the comparison.
10859         if (FallthroughUnreachable)
10860           CC = ISD::SETTRUE;
10861 
10862         // The false probability is the sum of all unhandled cases.
10863         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10864                      getCurSDLoc(), I->Prob, UnhandledProbs);
10865 
10866         if (CurMBB == SwitchMBB)
10867           visitSwitchCase(CB, SwitchMBB);
10868         else
10869           SL->SwitchCases.push_back(CB);
10870 
10871         break;
10872       }
10873     }
10874     CurMBB = Fallthrough;
10875   }
10876 }
10877 
10878 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10879                                               CaseClusterIt First,
10880                                               CaseClusterIt Last) {
10881   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10882     if (X.Prob != CC.Prob)
10883       return X.Prob > CC.Prob;
10884 
10885     // Ties are broken by comparing the case value.
10886     return X.Low->getValue().slt(CC.Low->getValue());
10887   });
10888 }
10889 
10890 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10891                                         const SwitchWorkListItem &W,
10892                                         Value *Cond,
10893                                         MachineBasicBlock *SwitchMBB) {
10894   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10895          "Clusters not sorted?");
10896 
10897   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10898 
10899   // Balance the tree based on branch probabilities to create a near-optimal (in
10900   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10901   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10902   CaseClusterIt LastLeft = W.FirstCluster;
10903   CaseClusterIt FirstRight = W.LastCluster;
10904   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10905   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10906 
10907   // Move LastLeft and FirstRight towards each other from opposite directions to
10908   // find a partitioning of the clusters which balances the probability on both
10909   // sides. If LeftProb and RightProb are equal, alternate which side is
10910   // taken to ensure 0-probability nodes are distributed evenly.
10911   unsigned I = 0;
10912   while (LastLeft + 1 < FirstRight) {
10913     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10914       LeftProb += (++LastLeft)->Prob;
10915     else
10916       RightProb += (--FirstRight)->Prob;
10917     I++;
10918   }
10919 
10920   while (true) {
10921     // Our binary search tree differs from a typical BST in that ours can have up
10922     // to three values in each leaf. The pivot selection above doesn't take that
10923     // into account, which means the tree might require more nodes and be less
10924     // efficient. We compensate for this here.
10925 
10926     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10927     unsigned NumRight = W.LastCluster - FirstRight + 1;
10928 
10929     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10930       // If one side has less than 3 clusters, and the other has more than 3,
10931       // consider taking a cluster from the other side.
10932 
10933       if (NumLeft < NumRight) {
10934         // Consider moving the first cluster on the right to the left side.
10935         CaseCluster &CC = *FirstRight;
10936         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10937         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10938         if (LeftSideRank <= RightSideRank) {
10939           // Moving the cluster to the left does not demote it.
10940           ++LastLeft;
10941           ++FirstRight;
10942           continue;
10943         }
10944       } else {
10945         assert(NumRight < NumLeft);
10946         // Consider moving the last element on the left to the right side.
10947         CaseCluster &CC = *LastLeft;
10948         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10949         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10950         if (RightSideRank <= LeftSideRank) {
10951           // Moving the cluster to the right does not demot it.
10952           --LastLeft;
10953           --FirstRight;
10954           continue;
10955         }
10956       }
10957     }
10958     break;
10959   }
10960 
10961   assert(LastLeft + 1 == FirstRight);
10962   assert(LastLeft >= W.FirstCluster);
10963   assert(FirstRight <= W.LastCluster);
10964 
10965   // Use the first element on the right as pivot since we will make less-than
10966   // comparisons against it.
10967   CaseClusterIt PivotCluster = FirstRight;
10968   assert(PivotCluster > W.FirstCluster);
10969   assert(PivotCluster <= W.LastCluster);
10970 
10971   CaseClusterIt FirstLeft = W.FirstCluster;
10972   CaseClusterIt LastRight = W.LastCluster;
10973 
10974   const ConstantInt *Pivot = PivotCluster->Low;
10975 
10976   // New blocks will be inserted immediately after the current one.
10977   MachineFunction::iterator BBI(W.MBB);
10978   ++BBI;
10979 
10980   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10981   // we can branch to its destination directly if it's squeezed exactly in
10982   // between the known lower bound and Pivot - 1.
10983   MachineBasicBlock *LeftMBB;
10984   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10985       FirstLeft->Low == W.GE &&
10986       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10987     LeftMBB = FirstLeft->MBB;
10988   } else {
10989     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10990     FuncInfo.MF->insert(BBI, LeftMBB);
10991     WorkList.push_back(
10992         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10993     // Put Cond in a virtual register to make it available from the new blocks.
10994     ExportFromCurrentBlock(Cond);
10995   }
10996 
10997   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10998   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10999   // directly if RHS.High equals the current upper bound.
11000   MachineBasicBlock *RightMBB;
11001   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11002       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11003     RightMBB = FirstRight->MBB;
11004   } else {
11005     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11006     FuncInfo.MF->insert(BBI, RightMBB);
11007     WorkList.push_back(
11008         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11009     // Put Cond in a virtual register to make it available from the new blocks.
11010     ExportFromCurrentBlock(Cond);
11011   }
11012 
11013   // Create the CaseBlock record that will be used to lower the branch.
11014   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11015                getCurSDLoc(), LeftProb, RightProb);
11016 
11017   if (W.MBB == SwitchMBB)
11018     visitSwitchCase(CB, SwitchMBB);
11019   else
11020     SL->SwitchCases.push_back(CB);
11021 }
11022 
11023 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11024 // from the swith statement.
11025 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11026                                             BranchProbability PeeledCaseProb) {
11027   if (PeeledCaseProb == BranchProbability::getOne())
11028     return BranchProbability::getZero();
11029   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11030 
11031   uint32_t Numerator = CaseProb.getNumerator();
11032   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11033   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11034 }
11035 
11036 // Try to peel the top probability case if it exceeds the threshold.
11037 // Return current MachineBasicBlock for the switch statement if the peeling
11038 // does not occur.
11039 // If the peeling is performed, return the newly created MachineBasicBlock
11040 // for the peeled switch statement. Also update Clusters to remove the peeled
11041 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11042 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11043     const SwitchInst &SI, CaseClusterVector &Clusters,
11044     BranchProbability &PeeledCaseProb) {
11045   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11046   // Don't perform if there is only one cluster or optimizing for size.
11047   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11048       TM.getOptLevel() == CodeGenOpt::None ||
11049       SwitchMBB->getParent()->getFunction().hasMinSize())
11050     return SwitchMBB;
11051 
11052   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11053   unsigned PeeledCaseIndex = 0;
11054   bool SwitchPeeled = false;
11055   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11056     CaseCluster &CC = Clusters[Index];
11057     if (CC.Prob < TopCaseProb)
11058       continue;
11059     TopCaseProb = CC.Prob;
11060     PeeledCaseIndex = Index;
11061     SwitchPeeled = true;
11062   }
11063   if (!SwitchPeeled)
11064     return SwitchMBB;
11065 
11066   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11067                     << TopCaseProb << "\n");
11068 
11069   // Record the MBB for the peeled switch statement.
11070   MachineFunction::iterator BBI(SwitchMBB);
11071   ++BBI;
11072   MachineBasicBlock *PeeledSwitchMBB =
11073       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11074   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11075 
11076   ExportFromCurrentBlock(SI.getCondition());
11077   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11078   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11079                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11080   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11081 
11082   Clusters.erase(PeeledCaseIt);
11083   for (CaseCluster &CC : Clusters) {
11084     LLVM_DEBUG(
11085         dbgs() << "Scale the probablity for one cluster, before scaling: "
11086                << CC.Prob << "\n");
11087     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11088     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11089   }
11090   PeeledCaseProb = TopCaseProb;
11091   return PeeledSwitchMBB;
11092 }
11093 
11094 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11095   // Extract cases from the switch.
11096   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11097   CaseClusterVector Clusters;
11098   Clusters.reserve(SI.getNumCases());
11099   for (auto I : SI.cases()) {
11100     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11101     const ConstantInt *CaseVal = I.getCaseValue();
11102     BranchProbability Prob =
11103         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11104             : BranchProbability(1, SI.getNumCases() + 1);
11105     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11106   }
11107 
11108   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11109 
11110   // Cluster adjacent cases with the same destination. We do this at all
11111   // optimization levels because it's cheap to do and will make codegen faster
11112   // if there are many clusters.
11113   sortAndRangeify(Clusters);
11114 
11115   // The branch probablity of the peeled case.
11116   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11117   MachineBasicBlock *PeeledSwitchMBB =
11118       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11119 
11120   // If there is only the default destination, jump there directly.
11121   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11122   if (Clusters.empty()) {
11123     assert(PeeledSwitchMBB == SwitchMBB);
11124     SwitchMBB->addSuccessor(DefaultMBB);
11125     if (DefaultMBB != NextBlock(SwitchMBB)) {
11126       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11127                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11128     }
11129     return;
11130   }
11131 
11132   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11133   SL->findBitTestClusters(Clusters, &SI);
11134 
11135   LLVM_DEBUG({
11136     dbgs() << "Case clusters: ";
11137     for (const CaseCluster &C : Clusters) {
11138       if (C.Kind == CC_JumpTable)
11139         dbgs() << "JT:";
11140       if (C.Kind == CC_BitTests)
11141         dbgs() << "BT:";
11142 
11143       C.Low->getValue().print(dbgs(), true);
11144       if (C.Low != C.High) {
11145         dbgs() << '-';
11146         C.High->getValue().print(dbgs(), true);
11147       }
11148       dbgs() << ' ';
11149     }
11150     dbgs() << '\n';
11151   });
11152 
11153   assert(!Clusters.empty());
11154   SwitchWorkList WorkList;
11155   CaseClusterIt First = Clusters.begin();
11156   CaseClusterIt Last = Clusters.end() - 1;
11157   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11158   // Scale the branchprobability for DefaultMBB if the peel occurs and
11159   // DefaultMBB is not replaced.
11160   if (PeeledCaseProb != BranchProbability::getZero() &&
11161       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11162     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11163   WorkList.push_back(
11164       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11165 
11166   while (!WorkList.empty()) {
11167     SwitchWorkListItem W = WorkList.pop_back_val();
11168     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11169 
11170     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11171         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11172       // For optimized builds, lower large range as a balanced binary tree.
11173       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11174       continue;
11175     }
11176 
11177     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11178   }
11179 }
11180 
11181 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11182   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11183   auto DL = getCurSDLoc();
11184   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11185   setValue(&I, DAG.getStepVector(DL, ResultVT));
11186 }
11187 
11188 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11189   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11190   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11191 
11192   SDLoc DL = getCurSDLoc();
11193   SDValue V = getValue(I.getOperand(0));
11194   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11195 
11196   if (VT.isScalableVector()) {
11197     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11198     return;
11199   }
11200 
11201   // Use VECTOR_SHUFFLE for the fixed-length vector
11202   // to maintain existing behavior.
11203   SmallVector<int, 8> Mask;
11204   unsigned NumElts = VT.getVectorMinNumElements();
11205   for (unsigned i = 0; i != NumElts; ++i)
11206     Mask.push_back(NumElts - 1 - i);
11207 
11208   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11209 }
11210 
11211 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11212   SmallVector<EVT, 4> ValueVTs;
11213   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11214                   ValueVTs);
11215   unsigned NumValues = ValueVTs.size();
11216   if (NumValues == 0) return;
11217 
11218   SmallVector<SDValue, 4> Values(NumValues);
11219   SDValue Op = getValue(I.getOperand(0));
11220 
11221   for (unsigned i = 0; i != NumValues; ++i)
11222     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11223                             SDValue(Op.getNode(), Op.getResNo() + i));
11224 
11225   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11226                            DAG.getVTList(ValueVTs), Values));
11227 }
11228 
11229 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11231   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11232 
11233   SDLoc DL = getCurSDLoc();
11234   SDValue V1 = getValue(I.getOperand(0));
11235   SDValue V2 = getValue(I.getOperand(1));
11236   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11237 
11238   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11239   if (VT.isScalableVector()) {
11240     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11241     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11242                              DAG.getConstant(Imm, DL, IdxVT)));
11243     return;
11244   }
11245 
11246   unsigned NumElts = VT.getVectorNumElements();
11247 
11248   if ((-Imm > NumElts) || (Imm >= NumElts)) {
11249     // Result is undefined if immediate is out-of-bounds.
11250     setValue(&I, DAG.getUNDEF(VT));
11251     return;
11252   }
11253 
11254   uint64_t Idx = (NumElts + Imm) % NumElts;
11255 
11256   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11257   SmallVector<int, 8> Mask;
11258   for (unsigned i = 0; i < NumElts; ++i)
11259     Mask.push_back(Idx + i);
11260   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11261 }
11262