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