xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision b0319ab79bf59669803cc2475fae1d12f8eeaca9)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/BranchProbabilityInfo.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/Analysis/Loads.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/ProfileSummaryInfo.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Analysis/VectorUtils.h"
37 #include "llvm/CodeGen/Analysis.h"
38 #include "llvm/CodeGen/FunctionLoweringInfo.h"
39 #include "llvm/CodeGen/GCMetadata.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
53 #include "llvm/CodeGen/StackMaps.h"
54 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
55 #include "llvm/CodeGen/TargetFrameLowering.h"
56 #include "llvm/CodeGen/TargetInstrInfo.h"
57 #include "llvm/CodeGen/TargetOpcodes.h"
58 #include "llvm/CodeGen/TargetRegisterInfo.h"
59 #include "llvm/CodeGen/TargetSubtargetInfo.h"
60 #include "llvm/CodeGen/WinEHFuncInfo.h"
61 #include "llvm/IR/Argument.h"
62 #include "llvm/IR/Attributes.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CFG.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/ConstantRange.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DebugInfoMetadata.h"
71 #include "llvm/IR/DerivedTypes.h"
72 #include "llvm/IR/DiagnosticInfo.h"
73 #include "llvm/IR/Function.h"
74 #include "llvm/IR/GetElementPtrTypeIterator.h"
75 #include "llvm/IR/InlineAsm.h"
76 #include "llvm/IR/InstrTypes.h"
77 #include "llvm/IR/Instructions.h"
78 #include "llvm/IR/IntrinsicInst.h"
79 #include "llvm/IR/Intrinsics.h"
80 #include "llvm/IR/IntrinsicsAArch64.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Module.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Statepoint.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/MC/MCContext.h"
92 #include "llvm/MC/MCSymbol.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/MathExtras.h"
99 #include "llvm/Support/raw_ostream.h"
100 #include "llvm/Target/TargetIntrinsicInfo.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetOptions.h"
103 #include "llvm/Transforms/Utils/Local.h"
104 #include <cstddef>
105 #include <cstring>
106 #include <iterator>
107 #include <limits>
108 #include <numeric>
109 #include <tuple>
110 
111 using namespace llvm;
112 using namespace PatternMatch;
113 using namespace SwitchCG;
114 
115 #define DEBUG_TYPE "isel"
116 
117 /// LimitFloatPrecision - Generate low-precision inline sequences for
118 /// some float libcalls (6, 8 or 12 bits).
119 static unsigned LimitFloatPrecision;
120 
121 static cl::opt<bool>
122     InsertAssertAlign("insert-assert-align", cl::init(true),
123                       cl::desc("Insert the experimental `assertalign` node."),
124                       cl::ReallyHidden);
125 
126 static cl::opt<unsigned, true>
127     LimitFPPrecision("limit-float-precision",
128                      cl::desc("Generate low-precision inline sequences "
129                               "for some float libcalls"),
130                      cl::location(LimitFloatPrecision), cl::Hidden,
131                      cl::init(0));
132 
133 static cl::opt<unsigned> SwitchPeelThreshold(
134     "switch-peel-threshold", cl::Hidden, cl::init(66),
135     cl::desc("Set the case probability threshold for peeling the case from a "
136              "switch statement. A value greater than 100 will void this "
137              "optimization"));
138 
139 // Limit the width of DAG chains. This is important in general to prevent
140 // DAG-based analysis from blowing up. For example, alias analysis and
141 // load clustering may not complete in reasonable time. It is difficult to
142 // recognize and avoid this situation within each individual analysis, and
143 // future analyses are likely to have the same behavior. Limiting DAG width is
144 // the safe approach and will be especially important with global DAGs.
145 //
146 // MaxParallelChains default is arbitrarily high to avoid affecting
147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
148 // sequence over this should have been converted to llvm.memcpy by the
149 // frontend. It is easy to induce this behavior with .ll code such as:
150 // %buffer = alloca [4096 x i8]
151 // %data = load [4096 x i8]* %argPtr
152 // store [4096 x i8] %data, [4096 x i8]* %buffer
153 static const unsigned MaxParallelChains = 64;
154 
155 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
156                                       const SDValue *Parts, unsigned NumParts,
157                                       MVT PartVT, EVT ValueVT, const Value *V,
158                                       Optional<CallingConv::ID> CC);
159 
160 /// getCopyFromParts - Create a value that contains the specified legal parts
161 /// combined into the value they represent.  If the parts combine to a type
162 /// larger than ValueVT then AssertOp can be used to specify whether the extra
163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164 /// (ISD::AssertSext).
165 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
166                                 const SDValue *Parts, unsigned NumParts,
167                                 MVT PartVT, EVT ValueVT, const Value *V,
168                                 Optional<CallingConv::ID> CC = None,
169                                 Optional<ISD::NodeType> AssertOp = None) {
170   // Let the target assemble the parts if it wants to
171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
172   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
173                                                    PartVT, ValueVT, CC))
174     return Val;
175 
176   if (ValueVT.isVector())
177     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
178                                   CC);
179 
180   assert(NumParts > 0 && "No parts to assemble!");
181   SDValue Val = Parts[0];
182 
183   if (NumParts > 1) {
184     // Assemble the value from multiple parts.
185     if (ValueVT.isInteger()) {
186       unsigned PartBits = PartVT.getSizeInBits();
187       unsigned ValueBits = ValueVT.getSizeInBits();
188 
189       // Assemble the power of 2 part.
190       unsigned RoundParts =
191           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
192       unsigned RoundBits = PartBits * RoundParts;
193       EVT RoundVT = RoundBits == ValueBits ?
194         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195       SDValue Lo, Hi;
196 
197       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
198 
199       if (RoundParts > 2) {
200         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
201                               PartVT, HalfVT, V);
202         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
203                               RoundParts / 2, PartVT, HalfVT, V);
204       } else {
205         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
206         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
207       }
208 
209       if (DAG.getDataLayout().isBigEndian())
210         std::swap(Lo, Hi);
211 
212       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
213 
214       if (RoundParts < NumParts) {
215         // Assemble the trailing non-power-of-2 part.
216         unsigned OddParts = NumParts - RoundParts;
217         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
218         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
219                               OddVT, V, CC);
220 
221         // Combine the round and odd parts.
222         Lo = Val;
223         if (DAG.getDataLayout().isBigEndian())
224           std::swap(Lo, Hi);
225         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
226         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
227         Hi =
228             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
229                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
230                                         TLI.getPointerTy(DAG.getDataLayout())));
231         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
232         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
233       }
234     } else if (PartVT.isFloatingPoint()) {
235       // FP split into multiple FP parts (for ppcf128)
236       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
237              "Unexpected split");
238       SDValue Lo, Hi;
239       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
240       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
241       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
242         std::swap(Lo, Hi);
243       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
244     } else {
245       // FP split into integer parts (soft fp)
246       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
247              !PartVT.isVector() && "Unexpected split");
248       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
249       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
250     }
251   }
252 
253   // There is now one part, held in Val.  Correct it to match ValueVT.
254   // PartEVT is the type of the register class that holds the value.
255   // ValueVT is the type of the inline asm operation.
256   EVT PartEVT = Val.getValueType();
257 
258   if (PartEVT == ValueVT)
259     return Val;
260 
261   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
262       ValueVT.bitsLT(PartEVT)) {
263     // For an FP value in an integer part, we need to truncate to the right
264     // width first.
265     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
266     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
267   }
268 
269   // Handle types that have the same size.
270   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
271     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
272 
273   // Handle types with different sizes.
274   if (PartEVT.isInteger() && ValueVT.isInteger()) {
275     if (ValueVT.bitsLT(PartEVT)) {
276       // For a truncate, see if we have any information to
277       // indicate whether the truncated bits will always be
278       // zero or sign-extension.
279       if (AssertOp.hasValue())
280         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
281                           DAG.getValueType(ValueVT));
282       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
283     }
284     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
285   }
286 
287   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
288     // FP_ROUND's are always exact here.
289     if (ValueVT.bitsLT(Val.getValueType()))
290       return DAG.getNode(
291           ISD::FP_ROUND, DL, ValueVT, Val,
292           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
293 
294     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
295   }
296 
297   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
298   // then truncating.
299   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
300       ValueVT.bitsLT(PartEVT)) {
301     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
302     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
303   }
304 
305   report_fatal_error("Unknown mismatch in getCopyFromParts!");
306 }
307 
308 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
309                                               const Twine &ErrMsg) {
310   const Instruction *I = dyn_cast_or_null<Instruction>(V);
311   if (!V)
312     return Ctx.emitError(ErrMsg);
313 
314   const char *AsmError = ", possible invalid constraint for vector type";
315   if (const CallInst *CI = dyn_cast<CallInst>(I))
316     if (CI->isInlineAsm())
317       return Ctx.emitError(I, ErrMsg + AsmError);
318 
319   return Ctx.emitError(I, ErrMsg);
320 }
321 
322 /// getCopyFromPartsVector - Create a value that contains the specified legal
323 /// parts combined into the value they represent.  If the parts combine to a
324 /// type larger than ValueVT then AssertOp can be used to specify whether the
325 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
326 /// ValueVT (ISD::AssertSext).
327 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
328                                       const SDValue *Parts, unsigned NumParts,
329                                       MVT PartVT, EVT ValueVT, const Value *V,
330                                       Optional<CallingConv::ID> CallConv) {
331   assert(ValueVT.isVector() && "Not a vector value");
332   assert(NumParts > 0 && "No parts to assemble!");
333   const bool IsABIRegCopy = CallConv.hasValue();
334 
335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
336   SDValue Val = Parts[0];
337 
338   // Handle a multi-element vector.
339   if (NumParts > 1) {
340     EVT IntermediateVT;
341     MVT RegisterVT;
342     unsigned NumIntermediates;
343     unsigned NumRegs;
344 
345     if (IsABIRegCopy) {
346       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
347           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
348           NumIntermediates, RegisterVT);
349     } else {
350       NumRegs =
351           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
352                                      NumIntermediates, RegisterVT);
353     }
354 
355     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
356     NumParts = NumRegs; // Silence a compiler warning.
357     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
358     assert(RegisterVT.getSizeInBits() ==
359            Parts[0].getSimpleValueType().getSizeInBits() &&
360            "Part type sizes don't match!");
361 
362     // Assemble the parts into intermediate operands.
363     SmallVector<SDValue, 8> Ops(NumIntermediates);
364     if (NumIntermediates == NumParts) {
365       // If the register was not expanded, truncate or copy the value,
366       // as appropriate.
367       for (unsigned i = 0; i != NumParts; ++i)
368         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
369                                   PartVT, IntermediateVT, V, CallConv);
370     } else if (NumParts > 0) {
371       // If the intermediate type was expanded, build the intermediate
372       // operands from the parts.
373       assert(NumParts % NumIntermediates == 0 &&
374              "Must expand into a divisible number of parts!");
375       unsigned Factor = NumParts / NumIntermediates;
376       for (unsigned i = 0; i != NumIntermediates; ++i)
377         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
378                                   PartVT, IntermediateVT, V, CallConv);
379     }
380 
381     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
382     // intermediate operands.
383     EVT BuiltVectorTy =
384         IntermediateVT.isVector()
385             ? EVT::getVectorVT(
386                   *DAG.getContext(), IntermediateVT.getScalarType(),
387                   IntermediateVT.getVectorElementCount() * NumParts)
388             : EVT::getVectorVT(*DAG.getContext(),
389                                IntermediateVT.getScalarType(),
390                                NumIntermediates);
391     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
392                                                 : ISD::BUILD_VECTOR,
393                       DL, BuiltVectorTy, Ops);
394   }
395 
396   // There is now one part, held in Val.  Correct it to match ValueVT.
397   EVT PartEVT = Val.getValueType();
398 
399   if (PartEVT == ValueVT)
400     return Val;
401 
402   if (PartEVT.isVector()) {
403     // Vector/Vector bitcast.
404     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
405       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
406 
407     // If the element type of the source/dest vectors are the same, but the
408     // parts vector has more elements than the value vector, then we have a
409     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
410     // elements we want.
411     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
412       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
413               ValueVT.getVectorElementCount().getKnownMinValue()) &&
414              (PartEVT.getVectorElementCount().isScalable() ==
415               ValueVT.getVectorElementCount().isScalable()) &&
416              "Cannot narrow, it would be a lossy transformation");
417       PartEVT =
418           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
419                            ValueVT.getVectorElementCount());
420       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
421                         DAG.getVectorIdxConstant(0, DL));
422       if (PartEVT == ValueVT)
423         return Val;
424     }
425 
426     // Promoted vector extract
427     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
428   }
429 
430   // Trivial bitcast if the types are the same size and the destination
431   // vector type is legal.
432   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
433       TLI.isTypeLegal(ValueVT))
434     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
435 
436   if (ValueVT.getVectorNumElements() != 1) {
437      // Certain ABIs require that vectors are passed as integers. For vectors
438      // are the same size, this is an obvious bitcast.
439      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
440        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
441      } else if (ValueVT.bitsLT(PartEVT)) {
442        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
443        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
444        // Drop the extra bits.
445        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
446        return DAG.getBitcast(ValueVT, Val);
447      }
448 
449      diagnosePossiblyInvalidConstraint(
450          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
451      return DAG.getUNDEF(ValueVT);
452   }
453 
454   // Handle cases such as i8 -> <1 x i1>
455   EVT ValueSVT = ValueVT.getVectorElementType();
456   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
457     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
458       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
459     else
460       Val = ValueVT.isFloatingPoint()
461                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
462                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
463   }
464 
465   return DAG.getBuildVector(ValueVT, DL, Val);
466 }
467 
468 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
469                                  SDValue Val, SDValue *Parts, unsigned NumParts,
470                                  MVT PartVT, const Value *V,
471                                  Optional<CallingConv::ID> CallConv);
472 
473 /// getCopyToParts - Create a series of nodes that contain the specified value
474 /// split into legal parts.  If the parts contain more bits than Val, then, for
475 /// integers, ExtendKind can be used to specify how to generate the extra bits.
476 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
477                            SDValue *Parts, unsigned NumParts, MVT PartVT,
478                            const Value *V,
479                            Optional<CallingConv::ID> CallConv = None,
480                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
481   // Let the target split the parts if it wants to
482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
483   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
484                                       CallConv))
485     return;
486   EVT ValueVT = Val.getValueType();
487 
488   // Handle the vector case separately.
489   if (ValueVT.isVector())
490     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
491                                 CallConv);
492 
493   unsigned PartBits = PartVT.getSizeInBits();
494   unsigned OrigNumParts = NumParts;
495   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
496          "Copying to an illegal type!");
497 
498   if (NumParts == 0)
499     return;
500 
501   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
502   EVT PartEVT = PartVT;
503   if (PartEVT == ValueVT) {
504     assert(NumParts == 1 && "No-op copy with multiple parts!");
505     Parts[0] = Val;
506     return;
507   }
508 
509   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
510     // If the parts cover more bits than the value has, promote the value.
511     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
512       assert(NumParts == 1 && "Do not know what to promote to!");
513       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
514     } else {
515       if (ValueVT.isFloatingPoint()) {
516         // FP values need to be bitcast, then extended if they are being put
517         // into a larger container.
518         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
519         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
520       }
521       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
522              ValueVT.isInteger() &&
523              "Unknown mismatch!");
524       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
525       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
526       if (PartVT == MVT::x86mmx)
527         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
528     }
529   } else if (PartBits == ValueVT.getSizeInBits()) {
530     // Different types of the same size.
531     assert(NumParts == 1 && PartEVT != ValueVT);
532     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
533   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
534     // If the parts cover less bits than value has, truncate the value.
535     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
536            ValueVT.isInteger() &&
537            "Unknown mismatch!");
538     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
539     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
540     if (PartVT == MVT::x86mmx)
541       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
542   }
543 
544   // The value may have changed - recompute ValueVT.
545   ValueVT = Val.getValueType();
546   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
547          "Failed to tile the value with PartVT!");
548 
549   if (NumParts == 1) {
550     if (PartEVT != ValueVT) {
551       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
552                                         "scalar-to-vector conversion failed");
553       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554     }
555 
556     Parts[0] = Val;
557     return;
558   }
559 
560   // Expand the value into multiple parts.
561   if (NumParts & (NumParts - 1)) {
562     // The number of parts is not a power of 2.  Split off and copy the tail.
563     assert(PartVT.isInteger() && ValueVT.isInteger() &&
564            "Do not know what to expand to!");
565     unsigned RoundParts = 1 << Log2_32(NumParts);
566     unsigned RoundBits = RoundParts * PartBits;
567     unsigned OddParts = NumParts - RoundParts;
568     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
569       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
570 
571     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
572                    CallConv);
573 
574     if (DAG.getDataLayout().isBigEndian())
575       // The odd parts were reversed by getCopyToParts - unreverse them.
576       std::reverse(Parts + RoundParts, Parts + NumParts);
577 
578     NumParts = RoundParts;
579     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
580     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
581   }
582 
583   // The number of parts is a power of 2.  Repeatedly bisect the value using
584   // EXTRACT_ELEMENT.
585   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
586                          EVT::getIntegerVT(*DAG.getContext(),
587                                            ValueVT.getSizeInBits()),
588                          Val);
589 
590   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
591     for (unsigned i = 0; i < NumParts; i += StepSize) {
592       unsigned ThisBits = StepSize * PartBits / 2;
593       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
594       SDValue &Part0 = Parts[i];
595       SDValue &Part1 = Parts[i+StepSize/2];
596 
597       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
598                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
599       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
600                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
601 
602       if (ThisBits == PartBits && ThisVT != PartVT) {
603         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
604         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
605       }
606     }
607   }
608 
609   if (DAG.getDataLayout().isBigEndian())
610     std::reverse(Parts, Parts + OrigNumParts);
611 }
612 
613 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
614                                      const SDLoc &DL, EVT PartVT) {
615   if (!PartVT.isVector())
616     return SDValue();
617 
618   EVT ValueVT = Val.getValueType();
619   ElementCount PartNumElts = PartVT.getVectorElementCount();
620   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
621 
622   // We only support widening vectors with equivalent element types and
623   // fixed/scalable properties. If a target needs to widen a fixed-length type
624   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
625   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
626       PartNumElts.isScalable() != ValueNumElts.isScalable() ||
627       PartVT.getVectorElementType() != ValueVT.getVectorElementType())
628     return SDValue();
629 
630   // Widening a scalable vector to another scalable vector is done by inserting
631   // the vector into a larger undef one.
632   if (PartNumElts.isScalable())
633     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
634                        Val, DAG.getVectorIdxConstant(0, DL));
635 
636   EVT ElementVT = PartVT.getVectorElementType();
637   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
638   // undef elements.
639   SmallVector<SDValue, 16> Ops;
640   DAG.ExtractVectorElements(Val, Ops);
641   SDValue EltUndef = DAG.getUNDEF(ElementVT);
642   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
643 
644   // FIXME: Use CONCAT for 2x -> 4x.
645   return DAG.getBuildVector(PartVT, DL, Ops);
646 }
647 
648 /// getCopyToPartsVector - Create a series of nodes that contain the specified
649 /// value split into legal parts.
650 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
651                                  SDValue Val, SDValue *Parts, unsigned NumParts,
652                                  MVT PartVT, const Value *V,
653                                  Optional<CallingConv::ID> CallConv) {
654   EVT ValueVT = Val.getValueType();
655   assert(ValueVT.isVector() && "Not a vector");
656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
657   const bool IsABIRegCopy = CallConv.hasValue();
658 
659   if (NumParts == 1) {
660     EVT PartEVT = PartVT;
661     if (PartEVT == ValueVT) {
662       // Nothing to do.
663     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
664       // Bitconvert vector->vector case.
665       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
666     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
667       Val = Widened;
668     } else if (PartVT.isVector() &&
669                PartEVT.getVectorElementType().bitsGE(
670                    ValueVT.getVectorElementType()) &&
671                PartEVT.getVectorElementCount() ==
672                    ValueVT.getVectorElementCount()) {
673 
674       // Promoted vector extract
675       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
676     } else if (PartEVT.isVector() &&
677                PartEVT.getVectorElementType() !=
678                    ValueVT.getVectorElementType() &&
679                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
680                    TargetLowering::TypeWidenVector) {
681       // Combination of widening and promotion.
682       EVT WidenVT =
683           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
684                            PartVT.getVectorElementCount());
685       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
686       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
687     } else {
688       if (ValueVT.getVectorElementCount().isScalar()) {
689         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
690                           DAG.getVectorIdxConstant(0, DL));
691       } else {
692         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
693         assert(PartVT.getFixedSizeInBits() > ValueSize &&
694                "lossy conversion of vector to scalar type");
695         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
696         Val = DAG.getBitcast(IntermediateType, Val);
697         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
698       }
699     }
700 
701     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
702     Parts[0] = Val;
703     return;
704   }
705 
706   // Handle a multi-element vector.
707   EVT IntermediateVT;
708   MVT RegisterVT;
709   unsigned NumIntermediates;
710   unsigned NumRegs;
711   if (IsABIRegCopy) {
712     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
713         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
714         NumIntermediates, RegisterVT);
715   } else {
716     NumRegs =
717         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
718                                    NumIntermediates, RegisterVT);
719   }
720 
721   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
722   NumParts = NumRegs; // Silence a compiler warning.
723   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
724 
725   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
726          "Mixing scalable and fixed vectors when copying in parts");
727 
728   Optional<ElementCount> DestEltCnt;
729 
730   if (IntermediateVT.isVector())
731     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
732   else
733     DestEltCnt = ElementCount::getFixed(NumIntermediates);
734 
735   EVT BuiltVectorTy = EVT::getVectorVT(
736       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
737 
738   if (ValueVT == BuiltVectorTy) {
739     // Nothing to do.
740   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
741     // Bitconvert vector->vector case.
742     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
743   } else {
744     if (BuiltVectorTy.getVectorElementType().bitsGT(
745             ValueVT.getVectorElementType())) {
746       // Integer promotion.
747       ValueVT = EVT::getVectorVT(*DAG.getContext(),
748                                  BuiltVectorTy.getVectorElementType(),
749                                  ValueVT.getVectorElementCount());
750       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
751     }
752 
753     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
754       Val = Widened;
755     }
756   }
757 
758   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
759 
760   // Split the vector into intermediate operands.
761   SmallVector<SDValue, 8> Ops(NumIntermediates);
762   for (unsigned i = 0; i != NumIntermediates; ++i) {
763     if (IntermediateVT.isVector()) {
764       // This does something sensible for scalable vectors - see the
765       // definition of EXTRACT_SUBVECTOR for further details.
766       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
767       Ops[i] =
768           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
769                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
770     } else {
771       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
772                            DAG.getVectorIdxConstant(i, DL));
773     }
774   }
775 
776   // Split the intermediate operands into legal parts.
777   if (NumParts == NumIntermediates) {
778     // If the register was not expanded, promote or copy the value,
779     // as appropriate.
780     for (unsigned i = 0; i != NumParts; ++i)
781       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
782   } else if (NumParts > 0) {
783     // If the intermediate type was expanded, split each the value into
784     // legal parts.
785     assert(NumIntermediates != 0 && "division by zero");
786     assert(NumParts % NumIntermediates == 0 &&
787            "Must expand into a divisible number of parts!");
788     unsigned Factor = NumParts / NumIntermediates;
789     for (unsigned i = 0; i != NumIntermediates; ++i)
790       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
791                      CallConv);
792   }
793 }
794 
795 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
796                            EVT valuevt, Optional<CallingConv::ID> CC)
797     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
798       RegCount(1, regs.size()), CallConv(CC) {}
799 
800 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
801                            const DataLayout &DL, unsigned Reg, Type *Ty,
802                            Optional<CallingConv::ID> CC) {
803   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
804 
805   CallConv = CC;
806 
807   for (EVT ValueVT : ValueVTs) {
808     unsigned NumRegs =
809         isABIMangled()
810             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
811             : TLI.getNumRegisters(Context, ValueVT);
812     MVT RegisterVT =
813         isABIMangled()
814             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
815             : TLI.getRegisterType(Context, ValueVT);
816     for (unsigned i = 0; i != NumRegs; ++i)
817       Regs.push_back(Reg + i);
818     RegVTs.push_back(RegisterVT);
819     RegCount.push_back(NumRegs);
820     Reg += NumRegs;
821   }
822 }
823 
824 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
825                                       FunctionLoweringInfo &FuncInfo,
826                                       const SDLoc &dl, SDValue &Chain,
827                                       SDValue *Flag, const Value *V) const {
828   // A Value with type {} or [0 x %t] needs no registers.
829   if (ValueVTs.empty())
830     return SDValue();
831 
832   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
833 
834   // Assemble the legal parts into the final values.
835   SmallVector<SDValue, 4> Values(ValueVTs.size());
836   SmallVector<SDValue, 8> Parts;
837   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
838     // Copy the legal parts from the registers.
839     EVT ValueVT = ValueVTs[Value];
840     unsigned NumRegs = RegCount[Value];
841     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
842                                           *DAG.getContext(),
843                                           CallConv.getValue(), RegVTs[Value])
844                                     : RegVTs[Value];
845 
846     Parts.resize(NumRegs);
847     for (unsigned i = 0; i != NumRegs; ++i) {
848       SDValue P;
849       if (!Flag) {
850         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
851       } else {
852         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
853         *Flag = P.getValue(2);
854       }
855 
856       Chain = P.getValue(1);
857       Parts[i] = P;
858 
859       // If the source register was virtual and if we know something about it,
860       // add an assert node.
861       if (!Register::isVirtualRegister(Regs[Part + i]) ||
862           !RegisterVT.isInteger())
863         continue;
864 
865       const FunctionLoweringInfo::LiveOutInfo *LOI =
866         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
867       if (!LOI)
868         continue;
869 
870       unsigned RegSize = RegisterVT.getScalarSizeInBits();
871       unsigned NumSignBits = LOI->NumSignBits;
872       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
873 
874       if (NumZeroBits == RegSize) {
875         // The current value is a zero.
876         // Explicitly express that as it would be easier for
877         // optimizations to kick in.
878         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
879         continue;
880       }
881 
882       // FIXME: We capture more information than the dag can represent.  For
883       // now, just use the tightest assertzext/assertsext possible.
884       bool isSExt;
885       EVT FromVT(MVT::Other);
886       if (NumZeroBits) {
887         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
888         isSExt = false;
889       } else if (NumSignBits > 1) {
890         FromVT =
891             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
892         isSExt = true;
893       } else {
894         continue;
895       }
896       // Add an assertion node.
897       assert(FromVT != MVT::Other);
898       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
899                              RegisterVT, P, DAG.getValueType(FromVT));
900     }
901 
902     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
903                                      RegisterVT, ValueVT, V, CallConv);
904     Part += NumRegs;
905     Parts.clear();
906   }
907 
908   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
909 }
910 
911 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
912                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
913                                  const Value *V,
914                                  ISD::NodeType PreferredExtendType) const {
915   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
916   ISD::NodeType ExtendKind = PreferredExtendType;
917 
918   // Get the list of the values's legal parts.
919   unsigned NumRegs = Regs.size();
920   SmallVector<SDValue, 8> Parts(NumRegs);
921   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
922     unsigned NumParts = RegCount[Value];
923 
924     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
925                                           *DAG.getContext(),
926                                           CallConv.getValue(), RegVTs[Value])
927                                     : RegVTs[Value];
928 
929     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
930       ExtendKind = ISD::ZERO_EXTEND;
931 
932     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
933                    NumParts, RegisterVT, V, CallConv, ExtendKind);
934     Part += NumParts;
935   }
936 
937   // Copy the parts into the registers.
938   SmallVector<SDValue, 8> Chains(NumRegs);
939   for (unsigned i = 0; i != NumRegs; ++i) {
940     SDValue Part;
941     if (!Flag) {
942       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
943     } else {
944       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
945       *Flag = Part.getValue(1);
946     }
947 
948     Chains[i] = Part.getValue(0);
949   }
950 
951   if (NumRegs == 1 || Flag)
952     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
953     // flagged to it. That is the CopyToReg nodes and the user are considered
954     // a single scheduling unit. If we create a TokenFactor and return it as
955     // chain, then the TokenFactor is both a predecessor (operand) of the
956     // user as well as a successor (the TF operands are flagged to the user).
957     // c1, f1 = CopyToReg
958     // c2, f2 = CopyToReg
959     // c3     = TokenFactor c1, c2
960     // ...
961     //        = op c3, ..., f2
962     Chain = Chains[NumRegs-1];
963   else
964     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
965 }
966 
967 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
968                                         unsigned MatchingIdx, const SDLoc &dl,
969                                         SelectionDAG &DAG,
970                                         std::vector<SDValue> &Ops) const {
971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
972 
973   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
974   if (HasMatching)
975     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
976   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
977     // Put the register class of the virtual registers in the flag word.  That
978     // way, later passes can recompute register class constraints for inline
979     // assembly as well as normal instructions.
980     // Don't do this for tied operands that can use the regclass information
981     // from the def.
982     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
983     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
984     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
985   }
986 
987   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
988   Ops.push_back(Res);
989 
990   if (Code == InlineAsm::Kind_Clobber) {
991     // Clobbers should always have a 1:1 mapping with registers, and may
992     // reference registers that have illegal (e.g. vector) types. Hence, we
993     // shouldn't try to apply any sort of splitting logic to them.
994     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
995            "No 1:1 mapping from clobbers to regs?");
996     Register SP = TLI.getStackPointerRegisterToSaveRestore();
997     (void)SP;
998     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
999       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1000       assert(
1001           (Regs[I] != SP ||
1002            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1003           "If we clobbered the stack pointer, MFI should know about it.");
1004     }
1005     return;
1006   }
1007 
1008   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1009     MVT RegisterVT = RegVTs[Value];
1010     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1011                                            RegisterVT);
1012     for (unsigned i = 0; i != NumRegs; ++i) {
1013       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1014       unsigned TheReg = Regs[Reg++];
1015       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1016     }
1017   }
1018 }
1019 
1020 SmallVector<std::pair<unsigned, TypeSize>, 4>
1021 RegsForValue::getRegsAndSizes() const {
1022   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1023   unsigned I = 0;
1024   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1025     unsigned RegCount = std::get<0>(CountAndVT);
1026     MVT RegisterVT = std::get<1>(CountAndVT);
1027     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1028     for (unsigned E = I + RegCount; I != E; ++I)
1029       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1030   }
1031   return OutVec;
1032 }
1033 
1034 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1035                                const TargetLibraryInfo *li) {
1036   AA = aa;
1037   GFI = gfi;
1038   LibInfo = li;
1039   Context = DAG.getContext();
1040   LPadToCallSiteMap.clear();
1041   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1042 }
1043 
1044 void SelectionDAGBuilder::clear() {
1045   NodeMap.clear();
1046   UnusedArgNodeMap.clear();
1047   PendingLoads.clear();
1048   PendingExports.clear();
1049   PendingConstrainedFP.clear();
1050   PendingConstrainedFPStrict.clear();
1051   CurInst = nullptr;
1052   HasTailCall = false;
1053   SDNodeOrder = LowestSDNodeOrder;
1054   StatepointLowering.clear();
1055 }
1056 
1057 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1058   DanglingDebugInfoMap.clear();
1059 }
1060 
1061 // Update DAG root to include dependencies on Pending chains.
1062 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1063   SDValue Root = DAG.getRoot();
1064 
1065   if (Pending.empty())
1066     return Root;
1067 
1068   // Add current root to PendingChains, unless we already indirectly
1069   // depend on it.
1070   if (Root.getOpcode() != ISD::EntryToken) {
1071     unsigned i = 0, e = Pending.size();
1072     for (; i != e; ++i) {
1073       assert(Pending[i].getNode()->getNumOperands() > 1);
1074       if (Pending[i].getNode()->getOperand(0) == Root)
1075         break;  // Don't add the root if we already indirectly depend on it.
1076     }
1077 
1078     if (i == e)
1079       Pending.push_back(Root);
1080   }
1081 
1082   if (Pending.size() == 1)
1083     Root = Pending[0];
1084   else
1085     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1086 
1087   DAG.setRoot(Root);
1088   Pending.clear();
1089   return Root;
1090 }
1091 
1092 SDValue SelectionDAGBuilder::getMemoryRoot() {
1093   return updateRoot(PendingLoads);
1094 }
1095 
1096 SDValue SelectionDAGBuilder::getRoot() {
1097   // Chain up all pending constrained intrinsics together with all
1098   // pending loads, by simply appending them to PendingLoads and
1099   // then calling getMemoryRoot().
1100   PendingLoads.reserve(PendingLoads.size() +
1101                        PendingConstrainedFP.size() +
1102                        PendingConstrainedFPStrict.size());
1103   PendingLoads.append(PendingConstrainedFP.begin(),
1104                       PendingConstrainedFP.end());
1105   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1106                       PendingConstrainedFPStrict.end());
1107   PendingConstrainedFP.clear();
1108   PendingConstrainedFPStrict.clear();
1109   return getMemoryRoot();
1110 }
1111 
1112 SDValue SelectionDAGBuilder::getControlRoot() {
1113   // We need to emit pending fpexcept.strict constrained intrinsics,
1114   // so append them to the PendingExports list.
1115   PendingExports.append(PendingConstrainedFPStrict.begin(),
1116                         PendingConstrainedFPStrict.end());
1117   PendingConstrainedFPStrict.clear();
1118   return updateRoot(PendingExports);
1119 }
1120 
1121 void SelectionDAGBuilder::visit(const Instruction &I) {
1122   // Set up outgoing PHI node register values before emitting the terminator.
1123   if (I.isTerminator()) {
1124     HandlePHINodesInSuccessorBlocks(I.getParent());
1125   }
1126 
1127   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1128   if (!isa<DbgInfoIntrinsic>(I))
1129     ++SDNodeOrder;
1130 
1131   CurInst = &I;
1132 
1133   visit(I.getOpcode(), I);
1134 
1135   if (!I.isTerminator() && !HasTailCall &&
1136       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1137     CopyToExportRegsIfNeeded(&I);
1138 
1139   CurInst = nullptr;
1140 }
1141 
1142 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1143   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1144 }
1145 
1146 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1147   // Note: this doesn't use InstVisitor, because it has to work with
1148   // ConstantExpr's in addition to instructions.
1149   switch (Opcode) {
1150   default: llvm_unreachable("Unknown instruction type encountered!");
1151     // Build the switch statement using the Instruction.def file.
1152 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1153     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1154 #include "llvm/IR/Instruction.def"
1155   }
1156 }
1157 
1158 void SelectionDAGBuilder::addDanglingDebugInfo(const DbgValueInst *DI,
1159                                                DebugLoc DL, unsigned Order) {
1160   // We treat variadic dbg_values differently at this stage.
1161   if (DI->hasArgList()) {
1162     // For variadic dbg_values we will now insert an undef.
1163     // FIXME: We can potentially recover these!
1164     SmallVector<SDDbgOperand, 2> Locs;
1165     for (const Value *V : DI->getValues()) {
1166       auto Undef = UndefValue::get(V->getType());
1167       Locs.push_back(SDDbgOperand::fromConst(Undef));
1168     }
1169     SDDbgValue *SDV = DAG.getDbgValueList(
1170         DI->getVariable(), DI->getExpression(), Locs, {},
1171         /*IsIndirect=*/false, DL, Order, /*IsVariadic=*/true);
1172     DAG.AddDbgValue(SDV, /*isParameter=*/false);
1173   } else {
1174     // TODO: Dangling debug info will eventually either be resolved or produce
1175     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1176     // between the original dbg.value location and its resolved DBG_VALUE,
1177     // which we should ideally fill with an extra Undef DBG_VALUE.
1178     assert(DI->getNumVariableLocationOps() == 1 &&
1179            "DbgValueInst without an ArgList should have a single location "
1180            "operand.");
1181     DanglingDebugInfoMap[DI->getValue(0)].emplace_back(DI, DL, Order);
1182   }
1183 }
1184 
1185 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1186                                                 const DIExpression *Expr) {
1187   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1188     const DbgValueInst *DI = DDI.getDI();
1189     DIVariable *DanglingVariable = DI->getVariable();
1190     DIExpression *DanglingExpr = DI->getExpression();
1191     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1192       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1193       return true;
1194     }
1195     return false;
1196   };
1197 
1198   for (auto &DDIMI : DanglingDebugInfoMap) {
1199     DanglingDebugInfoVector &DDIV = DDIMI.second;
1200 
1201     // If debug info is to be dropped, run it through final checks to see
1202     // whether it can be salvaged.
1203     for (auto &DDI : DDIV)
1204       if (isMatchingDbgValue(DDI))
1205         salvageUnresolvedDbgValue(DDI);
1206 
1207     erase_if(DDIV, isMatchingDbgValue);
1208   }
1209 }
1210 
1211 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1212 // generate the debug data structures now that we've seen its definition.
1213 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1214                                                    SDValue Val) {
1215   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1216   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1217     return;
1218 
1219   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1220   for (auto &DDI : DDIV) {
1221     const DbgValueInst *DI = DDI.getDI();
1222     assert(!DI->hasArgList() && "Not implemented for variadic dbg_values");
1223     assert(DI && "Ill-formed DanglingDebugInfo");
1224     DebugLoc dl = DDI.getdl();
1225     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1226     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1227     DILocalVariable *Variable = DI->getVariable();
1228     DIExpression *Expr = DI->getExpression();
1229     assert(Variable->isValidLocationForIntrinsic(dl) &&
1230            "Expected inlined-at fields to agree");
1231     SDDbgValue *SDV;
1232     if (Val.getNode()) {
1233       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1234       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1235       // we couldn't resolve it directly when examining the DbgValue intrinsic
1236       // in the first place we should not be more successful here). Unless we
1237       // have some test case that prove this to be correct we should avoid
1238       // calling EmitFuncArgumentDbgValue here.
1239       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1240         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1241                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1242         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1243         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1244         // inserted after the definition of Val when emitting the instructions
1245         // after ISel. An alternative could be to teach
1246         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1247         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1248                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1249                    << ValSDNodeOrder << "\n");
1250         SDV = getDbgValue(Val, Variable, Expr, dl,
1251                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1252         DAG.AddDbgValue(SDV, false);
1253       } else
1254         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1255                           << "in EmitFuncArgumentDbgValue\n");
1256     } else {
1257       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1258       auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1259       auto SDV =
1260           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1261       DAG.AddDbgValue(SDV, false);
1262     }
1263   }
1264   DDIV.clear();
1265 }
1266 
1267 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1268   // TODO: For the variadic implementation, instead of only checking the fail
1269   // state of `handleDebugValue`, we need know specifically which values were
1270   // invalid, so that we attempt to salvage only those values when processing
1271   // a DIArgList.
1272   assert(!DDI.getDI()->hasArgList() &&
1273          "Not implemented for variadic dbg_values");
1274   Value *V = DDI.getDI()->getValue(0);
1275   DILocalVariable *Var = DDI.getDI()->getVariable();
1276   DIExpression *Expr = DDI.getDI()->getExpression();
1277   DebugLoc DL = DDI.getdl();
1278   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1279   unsigned SDOrder = DDI.getSDNodeOrder();
1280   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1281   // that DW_OP_stack_value is desired.
1282   assert(isa<DbgValueInst>(DDI.getDI()));
1283   bool StackValue = true;
1284 
1285   // Can this Value can be encoded without any further work?
1286   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder, /*IsVariadic=*/false))
1287     return;
1288 
1289   // Attempt to salvage back through as many instructions as possible. Bail if
1290   // a non-instruction is seen, such as a constant expression or global
1291   // variable. FIXME: Further work could recover those too.
1292   while (isa<Instruction>(V)) {
1293     Instruction &VAsInst = *cast<Instruction>(V);
1294     // Temporary "0", awaiting real implementation.
1295     SmallVector<uint64_t, 16> Ops;
1296     SmallVector<Value *, 4> AdditionalValues;
1297     V = salvageDebugInfoImpl(VAsInst, Expr->getNumLocationOperands(), Ops,
1298                              AdditionalValues);
1299     // If we cannot salvage any further, and haven't yet found a suitable debug
1300     // expression, bail out.
1301     if (!V)
1302       break;
1303 
1304     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1305     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1306     // here for variadic dbg_values, remove that condition.
1307     if (!AdditionalValues.empty())
1308       break;
1309 
1310     // New value and expr now represent this debuginfo.
1311     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1312 
1313     // Some kind of simplification occurred: check whether the operand of the
1314     // salvaged debug expression can be encoded in this DAG.
1315     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder,
1316                          /*IsVariadic=*/false)) {
1317       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1318                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1319       return;
1320     }
1321   }
1322 
1323   // This was the final opportunity to salvage this debug information, and it
1324   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1325   // any earlier variable location.
1326   auto Undef = UndefValue::get(DDI.getDI()->getValue(0)->getType());
1327   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1328   DAG.AddDbgValue(SDV, false);
1329 
1330   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1331                     << "\n");
1332   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1333                     << "\n");
1334 }
1335 
1336 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1337                                            DILocalVariable *Var,
1338                                            DIExpression *Expr, DebugLoc dl,
1339                                            DebugLoc InstDL, unsigned Order,
1340                                            bool IsVariadic) {
1341   if (Values.empty())
1342     return true;
1343   SmallVector<SDDbgOperand> LocationOps;
1344   SmallVector<SDNode *> Dependencies;
1345   for (const Value *V : Values) {
1346     // Constant value.
1347     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1348         isa<ConstantPointerNull>(V)) {
1349       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1350       continue;
1351     }
1352 
1353     // If the Value is a frame index, we can create a FrameIndex debug value
1354     // without relying on the DAG at all.
1355     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1356       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1357       if (SI != FuncInfo.StaticAllocaMap.end()) {
1358         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1359         continue;
1360       }
1361     }
1362 
1363     // Do not use getValue() in here; we don't want to generate code at
1364     // this point if it hasn't been done yet.
1365     SDValue N = NodeMap[V];
1366     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1367       N = UnusedArgNodeMap[V];
1368     if (N.getNode()) {
1369       // Only emit func arg dbg value for non-variadic dbg.values for now.
1370       if (!IsVariadic && EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1371         return true;
1372       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1373         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1374         // describe stack slot locations.
1375         //
1376         // Consider "int x = 0; int *px = &x;". There are two kinds of
1377         // interesting debug values here after optimization:
1378         //
1379         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1380         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1381         //
1382         // Both describe the direct values of their associated variables.
1383         Dependencies.push_back(N.getNode());
1384         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1385         continue;
1386       }
1387       LocationOps.emplace_back(
1388           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1389       continue;
1390     }
1391 
1392     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1393     // Special rules apply for the first dbg.values of parameter variables in a
1394     // function. Identify them by the fact they reference Argument Values, that
1395     // they're parameters, and they are parameters of the current function. We
1396     // need to let them dangle until they get an SDNode.
1397     bool IsParamOfFunc =
1398         isa<Argument>(V) && Var->isParameter() && !InstDL.getInlinedAt();
1399     if (IsParamOfFunc)
1400       return false;
1401 
1402     // The value is not used in this block yet (or it would have an SDNode).
1403     // We still want the value to appear for the user if possible -- if it has
1404     // an associated VReg, we can refer to that instead.
1405     auto VMI = FuncInfo.ValueMap.find(V);
1406     if (VMI != FuncInfo.ValueMap.end()) {
1407       unsigned Reg = VMI->second;
1408       // If this is a PHI node, it may be split up into several MI PHI nodes
1409       // (in FunctionLoweringInfo::set).
1410       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1411                        V->getType(), None);
1412       if (RFV.occupiesMultipleRegs()) {
1413         // FIXME: We could potentially support variadic dbg_values here.
1414         if (IsVariadic)
1415           return false;
1416         unsigned Offset = 0;
1417         unsigned BitsToDescribe = 0;
1418         if (auto VarSize = Var->getSizeInBits())
1419           BitsToDescribe = *VarSize;
1420         if (auto Fragment = Expr->getFragmentInfo())
1421           BitsToDescribe = Fragment->SizeInBits;
1422         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1423           // Bail out if all bits are described already.
1424           if (Offset >= BitsToDescribe)
1425             break;
1426           // TODO: handle scalable vectors.
1427           unsigned RegisterSize = RegAndSize.second;
1428           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1429                                       ? BitsToDescribe - Offset
1430                                       : RegisterSize;
1431           auto FragmentExpr = DIExpression::createFragmentExpression(
1432               Expr, Offset, FragmentSize);
1433           if (!FragmentExpr)
1434             continue;
1435           SDDbgValue *SDV = DAG.getVRegDbgValue(
1436               Var, *FragmentExpr, RegAndSize.first, false, dl, SDNodeOrder);
1437           DAG.AddDbgValue(SDV, false);
1438           Offset += RegisterSize;
1439         }
1440         return true;
1441       }
1442       // We can use simple vreg locations for variadic dbg_values as well.
1443       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1444       continue;
1445     }
1446     // We failed to create a SDDbgOperand for V.
1447     return false;
1448   }
1449 
1450   // We have created a SDDbgOperand for each Value in Values.
1451   // Should use Order instead of SDNodeOrder?
1452   assert(!LocationOps.empty());
1453   SDDbgValue *SDV =
1454       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1455                           /*IsIndirect=*/false, dl, SDNodeOrder, IsVariadic);
1456   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1457   return true;
1458 }
1459 
1460 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1461   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1462   for (auto &Pair : DanglingDebugInfoMap)
1463     for (auto &DDI : Pair.second)
1464       salvageUnresolvedDbgValue(DDI);
1465   clearDanglingDebugInfo();
1466 }
1467 
1468 /// getCopyFromRegs - If there was virtual register allocated for the value V
1469 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1470 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1471   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1472   SDValue Result;
1473 
1474   if (It != FuncInfo.ValueMap.end()) {
1475     Register InReg = It->second;
1476 
1477     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1478                      DAG.getDataLayout(), InReg, Ty,
1479                      None); // This is not an ABI copy.
1480     SDValue Chain = DAG.getEntryNode();
1481     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1482                                  V);
1483     resolveDanglingDebugInfo(V, Result);
1484   }
1485 
1486   return Result;
1487 }
1488 
1489 /// getValue - Return an SDValue for the given Value.
1490 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1491   // If we already have an SDValue for this value, use it. It's important
1492   // to do this first, so that we don't create a CopyFromReg if we already
1493   // have a regular SDValue.
1494   SDValue &N = NodeMap[V];
1495   if (N.getNode()) return N;
1496 
1497   // If there's a virtual register allocated and initialized for this
1498   // value, use it.
1499   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1500     return copyFromReg;
1501 
1502   // Otherwise create a new SDValue and remember it.
1503   SDValue Val = getValueImpl(V);
1504   NodeMap[V] = Val;
1505   resolveDanglingDebugInfo(V, Val);
1506   return Val;
1507 }
1508 
1509 /// getNonRegisterValue - Return an SDValue for the given Value, but
1510 /// don't look in FuncInfo.ValueMap for a virtual register.
1511 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1512   // If we already have an SDValue for this value, use it.
1513   SDValue &N = NodeMap[V];
1514   if (N.getNode()) {
1515     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1516       // Remove the debug location from the node as the node is about to be used
1517       // in a location which may differ from the original debug location.  This
1518       // is relevant to Constant and ConstantFP nodes because they can appear
1519       // as constant expressions inside PHI nodes.
1520       N->setDebugLoc(DebugLoc());
1521     }
1522     return N;
1523   }
1524 
1525   // Otherwise create a new SDValue and remember it.
1526   SDValue Val = getValueImpl(V);
1527   NodeMap[V] = Val;
1528   resolveDanglingDebugInfo(V, Val);
1529   return Val;
1530 }
1531 
1532 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1533 /// Create an SDValue for the given value.
1534 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1535   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1536 
1537   if (const Constant *C = dyn_cast<Constant>(V)) {
1538     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1539 
1540     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1541       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1542 
1543     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1544       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1545 
1546     if (isa<ConstantPointerNull>(C)) {
1547       unsigned AS = V->getType()->getPointerAddressSpace();
1548       return DAG.getConstant(0, getCurSDLoc(),
1549                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1550     }
1551 
1552     if (match(C, m_VScale(DAG.getDataLayout())))
1553       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1554 
1555     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1556       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1557 
1558     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1559       return DAG.getUNDEF(VT);
1560 
1561     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1562       visit(CE->getOpcode(), *CE);
1563       SDValue N1 = NodeMap[V];
1564       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1565       return N1;
1566     }
1567 
1568     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1569       SmallVector<SDValue, 4> Constants;
1570       for (const Use &U : C->operands()) {
1571         SDNode *Val = getValue(U).getNode();
1572         // If the operand is an empty aggregate, there are no values.
1573         if (!Val) continue;
1574         // Add each leaf value from the operand to the Constants list
1575         // to form a flattened list of all the values.
1576         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1577           Constants.push_back(SDValue(Val, i));
1578       }
1579 
1580       return DAG.getMergeValues(Constants, getCurSDLoc());
1581     }
1582 
1583     if (const ConstantDataSequential *CDS =
1584           dyn_cast<ConstantDataSequential>(C)) {
1585       SmallVector<SDValue, 4> Ops;
1586       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1587         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1588         // Add each leaf value from the operand to the Constants list
1589         // to form a flattened list of all the values.
1590         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1591           Ops.push_back(SDValue(Val, i));
1592       }
1593 
1594       if (isa<ArrayType>(CDS->getType()))
1595         return DAG.getMergeValues(Ops, getCurSDLoc());
1596       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1597     }
1598 
1599     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1600       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1601              "Unknown struct or array constant!");
1602 
1603       SmallVector<EVT, 4> ValueVTs;
1604       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1605       unsigned NumElts = ValueVTs.size();
1606       if (NumElts == 0)
1607         return SDValue(); // empty struct
1608       SmallVector<SDValue, 4> Constants(NumElts);
1609       for (unsigned i = 0; i != NumElts; ++i) {
1610         EVT EltVT = ValueVTs[i];
1611         if (isa<UndefValue>(C))
1612           Constants[i] = DAG.getUNDEF(EltVT);
1613         else if (EltVT.isFloatingPoint())
1614           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1615         else
1616           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1617       }
1618 
1619       return DAG.getMergeValues(Constants, getCurSDLoc());
1620     }
1621 
1622     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1623       return DAG.getBlockAddress(BA, VT);
1624 
1625     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1626       return getValue(Equiv->getGlobalValue());
1627 
1628     VectorType *VecTy = cast<VectorType>(V->getType());
1629 
1630     // Now that we know the number and type of the elements, get that number of
1631     // elements into the Ops array based on what kind of constant it is.
1632     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1633       SmallVector<SDValue, 16> Ops;
1634       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1635       for (unsigned i = 0; i != NumElements; ++i)
1636         Ops.push_back(getValue(CV->getOperand(i)));
1637 
1638       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1639     } else if (isa<ConstantAggregateZero>(C)) {
1640       EVT EltVT =
1641           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1642 
1643       SDValue Op;
1644       if (EltVT.isFloatingPoint())
1645         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1646       else
1647         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1648 
1649       if (isa<ScalableVectorType>(VecTy))
1650         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1651       else {
1652         SmallVector<SDValue, 16> Ops;
1653         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1654         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1655       }
1656     }
1657     llvm_unreachable("Unknown vector constant");
1658   }
1659 
1660   // If this is a static alloca, generate it as the frameindex instead of
1661   // computation.
1662   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1663     DenseMap<const AllocaInst*, int>::iterator SI =
1664       FuncInfo.StaticAllocaMap.find(AI);
1665     if (SI != FuncInfo.StaticAllocaMap.end())
1666       return DAG.getFrameIndex(SI->second,
1667                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1668   }
1669 
1670   // If this is an instruction which fast-isel has deferred, select it now.
1671   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1672     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1673 
1674     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1675                      Inst->getType(), None);
1676     SDValue Chain = DAG.getEntryNode();
1677     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1678   }
1679 
1680   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1681     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1682   }
1683   llvm_unreachable("Can't get register for value!");
1684 }
1685 
1686 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1687   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1688   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1689   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1690   bool IsSEH = isAsynchronousEHPersonality(Pers);
1691   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1692   if (!IsSEH)
1693     CatchPadMBB->setIsEHScopeEntry();
1694   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1695   if (IsMSVCCXX || IsCoreCLR)
1696     CatchPadMBB->setIsEHFuncletEntry();
1697 }
1698 
1699 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1700   // Update machine-CFG edge.
1701   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1702   FuncInfo.MBB->addSuccessor(TargetMBB);
1703   TargetMBB->setIsEHCatchretTarget(true);
1704   DAG.getMachineFunction().setHasEHCatchret(true);
1705 
1706   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1707   bool IsSEH = isAsynchronousEHPersonality(Pers);
1708   if (IsSEH) {
1709     // If this is not a fall-through branch or optimizations are switched off,
1710     // emit the branch.
1711     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1712         TM.getOptLevel() == CodeGenOpt::None)
1713       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1714                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1715     return;
1716   }
1717 
1718   // Figure out the funclet membership for the catchret's successor.
1719   // This will be used by the FuncletLayout pass to determine how to order the
1720   // BB's.
1721   // A 'catchret' returns to the outer scope's color.
1722   Value *ParentPad = I.getCatchSwitchParentPad();
1723   const BasicBlock *SuccessorColor;
1724   if (isa<ConstantTokenNone>(ParentPad))
1725     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1726   else
1727     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1728   assert(SuccessorColor && "No parent funclet for catchret!");
1729   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1730   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1731 
1732   // Create the terminator node.
1733   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1734                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1735                             DAG.getBasicBlock(SuccessorColorMBB));
1736   DAG.setRoot(Ret);
1737 }
1738 
1739 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1740   // Don't emit any special code for the cleanuppad instruction. It just marks
1741   // the start of an EH scope/funclet.
1742   FuncInfo.MBB->setIsEHScopeEntry();
1743   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1744   if (Pers != EHPersonality::Wasm_CXX) {
1745     FuncInfo.MBB->setIsEHFuncletEntry();
1746     FuncInfo.MBB->setIsCleanupFuncletEntry();
1747   }
1748 }
1749 
1750 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1751 // not match, it is OK to add only the first unwind destination catchpad to the
1752 // successors, because there will be at least one invoke instruction within the
1753 // catch scope that points to the next unwind destination, if one exists, so
1754 // CFGSort cannot mess up with BB sorting order.
1755 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1756 // call within them, and catchpads only consisting of 'catch (...)' have a
1757 // '__cxa_end_catch' call within them, both of which generate invokes in case
1758 // the next unwind destination exists, i.e., the next unwind destination is not
1759 // the caller.)
1760 //
1761 // Having at most one EH pad successor is also simpler and helps later
1762 // transformations.
1763 //
1764 // For example,
1765 // current:
1766 //   invoke void @foo to ... unwind label %catch.dispatch
1767 // catch.dispatch:
1768 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1769 // catch.start:
1770 //   ...
1771 //   ... in this BB or some other child BB dominated by this BB there will be an
1772 //   invoke that points to 'next' BB as an unwind destination
1773 //
1774 // next: ; We don't need to add this to 'current' BB's successor
1775 //   ...
1776 static void findWasmUnwindDestinations(
1777     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1778     BranchProbability Prob,
1779     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1780         &UnwindDests) {
1781   while (EHPadBB) {
1782     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1783     if (isa<CleanupPadInst>(Pad)) {
1784       // Stop on cleanup pads.
1785       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1786       UnwindDests.back().first->setIsEHScopeEntry();
1787       break;
1788     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1789       // Add the catchpad handlers to the possible destinations. We don't
1790       // continue to the unwind destination of the catchswitch for wasm.
1791       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1792         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1793         UnwindDests.back().first->setIsEHScopeEntry();
1794       }
1795       break;
1796     } else {
1797       continue;
1798     }
1799   }
1800 }
1801 
1802 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1803 /// many places it could ultimately go. In the IR, we have a single unwind
1804 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1805 /// This function skips over imaginary basic blocks that hold catchswitch
1806 /// instructions, and finds all the "real" machine
1807 /// basic block destinations. As those destinations may not be successors of
1808 /// EHPadBB, here we also calculate the edge probability to those destinations.
1809 /// The passed-in Prob is the edge probability to EHPadBB.
1810 static void findUnwindDestinations(
1811     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1812     BranchProbability Prob,
1813     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1814         &UnwindDests) {
1815   EHPersonality Personality =
1816     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1817   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1818   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1819   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1820   bool IsSEH = isAsynchronousEHPersonality(Personality);
1821 
1822   if (IsWasmCXX) {
1823     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1824     assert(UnwindDests.size() <= 1 &&
1825            "There should be at most one unwind destination for wasm");
1826     return;
1827   }
1828 
1829   while (EHPadBB) {
1830     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1831     BasicBlock *NewEHPadBB = nullptr;
1832     if (isa<LandingPadInst>(Pad)) {
1833       // Stop on landingpads. They are not funclets.
1834       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1835       break;
1836     } else if (isa<CleanupPadInst>(Pad)) {
1837       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1838       // personalities.
1839       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1840       UnwindDests.back().first->setIsEHScopeEntry();
1841       UnwindDests.back().first->setIsEHFuncletEntry();
1842       break;
1843     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1844       // Add the catchpad handlers to the possible destinations.
1845       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1846         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1847         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1848         if (IsMSVCCXX || IsCoreCLR)
1849           UnwindDests.back().first->setIsEHFuncletEntry();
1850         if (!IsSEH)
1851           UnwindDests.back().first->setIsEHScopeEntry();
1852       }
1853       NewEHPadBB = CatchSwitch->getUnwindDest();
1854     } else {
1855       continue;
1856     }
1857 
1858     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1859     if (BPI && NewEHPadBB)
1860       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1861     EHPadBB = NewEHPadBB;
1862   }
1863 }
1864 
1865 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1866   // Update successor info.
1867   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1868   auto UnwindDest = I.getUnwindDest();
1869   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1870   BranchProbability UnwindDestProb =
1871       (BPI && UnwindDest)
1872           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1873           : BranchProbability::getZero();
1874   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1875   for (auto &UnwindDest : UnwindDests) {
1876     UnwindDest.first->setIsEHPad();
1877     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1878   }
1879   FuncInfo.MBB->normalizeSuccProbs();
1880 
1881   // Create the terminator node.
1882   SDValue Ret =
1883       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1884   DAG.setRoot(Ret);
1885 }
1886 
1887 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1888   report_fatal_error("visitCatchSwitch not yet implemented!");
1889 }
1890 
1891 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1893   auto &DL = DAG.getDataLayout();
1894   SDValue Chain = getControlRoot();
1895   SmallVector<ISD::OutputArg, 8> Outs;
1896   SmallVector<SDValue, 8> OutVals;
1897 
1898   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1899   // lower
1900   //
1901   //   %val = call <ty> @llvm.experimental.deoptimize()
1902   //   ret <ty> %val
1903   //
1904   // differently.
1905   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1906     LowerDeoptimizingReturn();
1907     return;
1908   }
1909 
1910   if (!FuncInfo.CanLowerReturn) {
1911     unsigned DemoteReg = FuncInfo.DemoteRegister;
1912     const Function *F = I.getParent()->getParent();
1913 
1914     // Emit a store of the return value through the virtual register.
1915     // Leave Outs empty so that LowerReturn won't try to load return
1916     // registers the usual way.
1917     SmallVector<EVT, 1> PtrValueVTs;
1918     ComputeValueVTs(TLI, DL,
1919                     F->getReturnType()->getPointerTo(
1920                         DAG.getDataLayout().getAllocaAddrSpace()),
1921                     PtrValueVTs);
1922 
1923     SDValue RetPtr =
1924         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
1925     SDValue RetOp = getValue(I.getOperand(0));
1926 
1927     SmallVector<EVT, 4> ValueVTs, MemVTs;
1928     SmallVector<uint64_t, 4> Offsets;
1929     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1930                     &Offsets);
1931     unsigned NumValues = ValueVTs.size();
1932 
1933     SmallVector<SDValue, 4> Chains(NumValues);
1934     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1935     for (unsigned i = 0; i != NumValues; ++i) {
1936       // An aggregate return value cannot wrap around the address space, so
1937       // offsets to its parts don't wrap either.
1938       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1939                                            TypeSize::Fixed(Offsets[i]));
1940 
1941       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1942       if (MemVTs[i] != ValueVTs[i])
1943         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1944       Chains[i] = DAG.getStore(
1945           Chain, getCurSDLoc(), Val,
1946           // FIXME: better loc info would be nice.
1947           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1948           commonAlignment(BaseAlign, Offsets[i]));
1949     }
1950 
1951     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1952                         MVT::Other, Chains);
1953   } else if (I.getNumOperands() != 0) {
1954     SmallVector<EVT, 4> ValueVTs;
1955     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1956     unsigned NumValues = ValueVTs.size();
1957     if (NumValues) {
1958       SDValue RetOp = getValue(I.getOperand(0));
1959 
1960       const Function *F = I.getParent()->getParent();
1961 
1962       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1963           I.getOperand(0)->getType(), F->getCallingConv(),
1964           /*IsVarArg*/ false, DL);
1965 
1966       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1967       if (F->getAttributes().hasRetAttr(Attribute::SExt))
1968         ExtendKind = ISD::SIGN_EXTEND;
1969       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
1970         ExtendKind = ISD::ZERO_EXTEND;
1971 
1972       LLVMContext &Context = F->getContext();
1973       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
1974 
1975       for (unsigned j = 0; j != NumValues; ++j) {
1976         EVT VT = ValueVTs[j];
1977 
1978         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1979           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1980 
1981         CallingConv::ID CC = F->getCallingConv();
1982 
1983         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1984         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1985         SmallVector<SDValue, 4> Parts(NumParts);
1986         getCopyToParts(DAG, getCurSDLoc(),
1987                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1988                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1989 
1990         // 'inreg' on function refers to return value
1991         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1992         if (RetInReg)
1993           Flags.setInReg();
1994 
1995         if (I.getOperand(0)->getType()->isPointerTy()) {
1996           Flags.setPointer();
1997           Flags.setPointerAddrSpace(
1998               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1999         }
2000 
2001         if (NeedsRegBlock) {
2002           Flags.setInConsecutiveRegs();
2003           if (j == NumValues - 1)
2004             Flags.setInConsecutiveRegsLast();
2005         }
2006 
2007         // Propagate extension type if any
2008         if (ExtendKind == ISD::SIGN_EXTEND)
2009           Flags.setSExt();
2010         else if (ExtendKind == ISD::ZERO_EXTEND)
2011           Flags.setZExt();
2012 
2013         for (unsigned i = 0; i < NumParts; ++i) {
2014           Outs.push_back(ISD::OutputArg(Flags,
2015                                         Parts[i].getValueType().getSimpleVT(),
2016                                         VT, /*isfixed=*/true, 0, 0));
2017           OutVals.push_back(Parts[i]);
2018         }
2019       }
2020     }
2021   }
2022 
2023   // Push in swifterror virtual register as the last element of Outs. This makes
2024   // sure swifterror virtual register will be returned in the swifterror
2025   // physical register.
2026   const Function *F = I.getParent()->getParent();
2027   if (TLI.supportSwiftError() &&
2028       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2029     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2030     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2031     Flags.setSwiftError();
2032     Outs.push_back(ISD::OutputArg(
2033         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2034         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2035     // Create SDNode for the swifterror virtual register.
2036     OutVals.push_back(
2037         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2038                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2039                         EVT(TLI.getPointerTy(DL))));
2040   }
2041 
2042   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2043   CallingConv::ID CallConv =
2044     DAG.getMachineFunction().getFunction().getCallingConv();
2045   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2046       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2047 
2048   // Verify that the target's LowerReturn behaved as expected.
2049   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2050          "LowerReturn didn't return a valid chain!");
2051 
2052   // Update the DAG with the new chain value resulting from return lowering.
2053   DAG.setRoot(Chain);
2054 }
2055 
2056 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2057 /// created for it, emit nodes to copy the value into the virtual
2058 /// registers.
2059 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2060   // Skip empty types
2061   if (V->getType()->isEmptyTy())
2062     return;
2063 
2064   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2065   if (VMI != FuncInfo.ValueMap.end()) {
2066     assert(!V->use_empty() && "Unused value assigned virtual registers!");
2067     CopyValueToVirtualRegister(V, VMI->second);
2068   }
2069 }
2070 
2071 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2072 /// the current basic block, add it to ValueMap now so that we'll get a
2073 /// CopyTo/FromReg.
2074 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2075   // No need to export constants.
2076   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2077 
2078   // Already exported?
2079   if (FuncInfo.isExportedInst(V)) return;
2080 
2081   unsigned Reg = FuncInfo.InitializeRegForValue(V);
2082   CopyValueToVirtualRegister(V, Reg);
2083 }
2084 
2085 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2086                                                      const BasicBlock *FromBB) {
2087   // The operands of the setcc have to be in this block.  We don't know
2088   // how to export them from some other block.
2089   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2090     // Can export from current BB.
2091     if (VI->getParent() == FromBB)
2092       return true;
2093 
2094     // Is already exported, noop.
2095     return FuncInfo.isExportedInst(V);
2096   }
2097 
2098   // If this is an argument, we can export it if the BB is the entry block or
2099   // if it is already exported.
2100   if (isa<Argument>(V)) {
2101     if (FromBB->isEntryBlock())
2102       return true;
2103 
2104     // Otherwise, can only export this if it is already exported.
2105     return FuncInfo.isExportedInst(V);
2106   }
2107 
2108   // Otherwise, constants can always be exported.
2109   return true;
2110 }
2111 
2112 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2113 BranchProbability
2114 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2115                                         const MachineBasicBlock *Dst) const {
2116   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2117   const BasicBlock *SrcBB = Src->getBasicBlock();
2118   const BasicBlock *DstBB = Dst->getBasicBlock();
2119   if (!BPI) {
2120     // If BPI is not available, set the default probability as 1 / N, where N is
2121     // the number of successors.
2122     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2123     return BranchProbability(1, SuccSize);
2124   }
2125   return BPI->getEdgeProbability(SrcBB, DstBB);
2126 }
2127 
2128 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2129                                                MachineBasicBlock *Dst,
2130                                                BranchProbability Prob) {
2131   if (!FuncInfo.BPI)
2132     Src->addSuccessorWithoutProb(Dst);
2133   else {
2134     if (Prob.isUnknown())
2135       Prob = getEdgeProbability(Src, Dst);
2136     Src->addSuccessor(Dst, Prob);
2137   }
2138 }
2139 
2140 static bool InBlock(const Value *V, const BasicBlock *BB) {
2141   if (const Instruction *I = dyn_cast<Instruction>(V))
2142     return I->getParent() == BB;
2143   return true;
2144 }
2145 
2146 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2147 /// This function emits a branch and is used at the leaves of an OR or an
2148 /// AND operator tree.
2149 void
2150 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2151                                                   MachineBasicBlock *TBB,
2152                                                   MachineBasicBlock *FBB,
2153                                                   MachineBasicBlock *CurBB,
2154                                                   MachineBasicBlock *SwitchBB,
2155                                                   BranchProbability TProb,
2156                                                   BranchProbability FProb,
2157                                                   bool InvertCond) {
2158   const BasicBlock *BB = CurBB->getBasicBlock();
2159 
2160   // If the leaf of the tree is a comparison, merge the condition into
2161   // the caseblock.
2162   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2163     // The operands of the cmp have to be in this block.  We don't know
2164     // how to export them from some other block.  If this is the first block
2165     // of the sequence, no exporting is needed.
2166     if (CurBB == SwitchBB ||
2167         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2168          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2169       ISD::CondCode Condition;
2170       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2171         ICmpInst::Predicate Pred =
2172             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2173         Condition = getICmpCondCode(Pred);
2174       } else {
2175         const FCmpInst *FC = cast<FCmpInst>(Cond);
2176         FCmpInst::Predicate Pred =
2177             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2178         Condition = getFCmpCondCode(Pred);
2179         if (TM.Options.NoNaNsFPMath)
2180           Condition = getFCmpCodeWithoutNaN(Condition);
2181       }
2182 
2183       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2184                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2185       SL->SwitchCases.push_back(CB);
2186       return;
2187     }
2188   }
2189 
2190   // Create a CaseBlock record representing this branch.
2191   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2192   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2193                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2194   SL->SwitchCases.push_back(CB);
2195 }
2196 
2197 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2198                                                MachineBasicBlock *TBB,
2199                                                MachineBasicBlock *FBB,
2200                                                MachineBasicBlock *CurBB,
2201                                                MachineBasicBlock *SwitchBB,
2202                                                Instruction::BinaryOps Opc,
2203                                                BranchProbability TProb,
2204                                                BranchProbability FProb,
2205                                                bool InvertCond) {
2206   // Skip over not part of the tree and remember to invert op and operands at
2207   // next level.
2208   Value *NotCond;
2209   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2210       InBlock(NotCond, CurBB->getBasicBlock())) {
2211     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2212                          !InvertCond);
2213     return;
2214   }
2215 
2216   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2217   const Value *BOpOp0, *BOpOp1;
2218   // Compute the effective opcode for Cond, taking into account whether it needs
2219   // to be inverted, e.g.
2220   //   and (not (or A, B)), C
2221   // gets lowered as
2222   //   and (and (not A, not B), C)
2223   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2224   if (BOp) {
2225     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2226                ? Instruction::And
2227                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2228                       ? Instruction::Or
2229                       : (Instruction::BinaryOps)0);
2230     if (InvertCond) {
2231       if (BOpc == Instruction::And)
2232         BOpc = Instruction::Or;
2233       else if (BOpc == Instruction::Or)
2234         BOpc = Instruction::And;
2235     }
2236   }
2237 
2238   // If this node is not part of the or/and tree, emit it as a branch.
2239   // Note that all nodes in the tree should have same opcode.
2240   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2241   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2242       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2243       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2244     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2245                                  TProb, FProb, InvertCond);
2246     return;
2247   }
2248 
2249   //  Create TmpBB after CurBB.
2250   MachineFunction::iterator BBI(CurBB);
2251   MachineFunction &MF = DAG.getMachineFunction();
2252   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2253   CurBB->getParent()->insert(++BBI, TmpBB);
2254 
2255   if (Opc == Instruction::Or) {
2256     // Codegen X | Y as:
2257     // BB1:
2258     //   jmp_if_X TBB
2259     //   jmp TmpBB
2260     // TmpBB:
2261     //   jmp_if_Y TBB
2262     //   jmp FBB
2263     //
2264 
2265     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2266     // The requirement is that
2267     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2268     //     = TrueProb for original BB.
2269     // Assuming the original probabilities are A and B, one choice is to set
2270     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2271     // A/(1+B) and 2B/(1+B). This choice assumes that
2272     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2273     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2274     // TmpBB, but the math is more complicated.
2275 
2276     auto NewTrueProb = TProb / 2;
2277     auto NewFalseProb = TProb / 2 + FProb;
2278     // Emit the LHS condition.
2279     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2280                          NewFalseProb, InvertCond);
2281 
2282     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2283     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2284     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2285     // Emit the RHS condition into TmpBB.
2286     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2287                          Probs[1], InvertCond);
2288   } else {
2289     assert(Opc == Instruction::And && "Unknown merge op!");
2290     // Codegen X & Y as:
2291     // BB1:
2292     //   jmp_if_X TmpBB
2293     //   jmp FBB
2294     // TmpBB:
2295     //   jmp_if_Y TBB
2296     //   jmp FBB
2297     //
2298     //  This requires creation of TmpBB after CurBB.
2299 
2300     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2301     // The requirement is that
2302     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2303     //     = FalseProb for original BB.
2304     // Assuming the original probabilities are A and B, one choice is to set
2305     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2306     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2307     // TrueProb for BB1 * FalseProb for TmpBB.
2308 
2309     auto NewTrueProb = TProb + FProb / 2;
2310     auto NewFalseProb = FProb / 2;
2311     // Emit the LHS condition.
2312     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2313                          NewFalseProb, InvertCond);
2314 
2315     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2316     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2317     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2318     // Emit the RHS condition into TmpBB.
2319     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2320                          Probs[1], InvertCond);
2321   }
2322 }
2323 
2324 /// If the set of cases should be emitted as a series of branches, return true.
2325 /// If we should emit this as a bunch of and/or'd together conditions, return
2326 /// false.
2327 bool
2328 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2329   if (Cases.size() != 2) return true;
2330 
2331   // If this is two comparisons of the same values or'd or and'd together, they
2332   // will get folded into a single comparison, so don't emit two blocks.
2333   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2334        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2335       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2336        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2337     return false;
2338   }
2339 
2340   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2341   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2342   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2343       Cases[0].CC == Cases[1].CC &&
2344       isa<Constant>(Cases[0].CmpRHS) &&
2345       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2346     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2347       return false;
2348     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2349       return false;
2350   }
2351 
2352   return true;
2353 }
2354 
2355 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2356   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2357 
2358   // Update machine-CFG edges.
2359   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2360 
2361   if (I.isUnconditional()) {
2362     // Update machine-CFG edges.
2363     BrMBB->addSuccessor(Succ0MBB);
2364 
2365     // If this is not a fall-through branch or optimizations are switched off,
2366     // emit the branch.
2367     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2368       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2369                               MVT::Other, getControlRoot(),
2370                               DAG.getBasicBlock(Succ0MBB)));
2371 
2372     return;
2373   }
2374 
2375   // If this condition is one of the special cases we handle, do special stuff
2376   // now.
2377   const Value *CondVal = I.getCondition();
2378   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2379 
2380   // If this is a series of conditions that are or'd or and'd together, emit
2381   // this as a sequence of branches instead of setcc's with and/or operations.
2382   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2383   // unpredictable branches, and vector extracts because those jumps are likely
2384   // expensive for any target), this should improve performance.
2385   // For example, instead of something like:
2386   //     cmp A, B
2387   //     C = seteq
2388   //     cmp D, E
2389   //     F = setle
2390   //     or C, F
2391   //     jnz foo
2392   // Emit:
2393   //     cmp A, B
2394   //     je foo
2395   //     cmp D, E
2396   //     jle foo
2397   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2398   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2399       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2400     Value *Vec;
2401     const Value *BOp0, *BOp1;
2402     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2403     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2404       Opcode = Instruction::And;
2405     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2406       Opcode = Instruction::Or;
2407 
2408     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2409                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2410       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2411                            getEdgeProbability(BrMBB, Succ0MBB),
2412                            getEdgeProbability(BrMBB, Succ1MBB),
2413                            /*InvertCond=*/false);
2414       // If the compares in later blocks need to use values not currently
2415       // exported from this block, export them now.  This block should always
2416       // be the first entry.
2417       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2418 
2419       // Allow some cases to be rejected.
2420       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2421         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2422           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2423           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2424         }
2425 
2426         // Emit the branch for this block.
2427         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2428         SL->SwitchCases.erase(SL->SwitchCases.begin());
2429         return;
2430       }
2431 
2432       // Okay, we decided not to do this, remove any inserted MBB's and clear
2433       // SwitchCases.
2434       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2435         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2436 
2437       SL->SwitchCases.clear();
2438     }
2439   }
2440 
2441   // Create a CaseBlock record representing this branch.
2442   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2443                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2444 
2445   // Use visitSwitchCase to actually insert the fast branch sequence for this
2446   // cond branch.
2447   visitSwitchCase(CB, BrMBB);
2448 }
2449 
2450 /// visitSwitchCase - Emits the necessary code to represent a single node in
2451 /// the binary search tree resulting from lowering a switch instruction.
2452 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2453                                           MachineBasicBlock *SwitchBB) {
2454   SDValue Cond;
2455   SDValue CondLHS = getValue(CB.CmpLHS);
2456   SDLoc dl = CB.DL;
2457 
2458   if (CB.CC == ISD::SETTRUE) {
2459     // Branch or fall through to TrueBB.
2460     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2461     SwitchBB->normalizeSuccProbs();
2462     if (CB.TrueBB != NextBlock(SwitchBB)) {
2463       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2464                               DAG.getBasicBlock(CB.TrueBB)));
2465     }
2466     return;
2467   }
2468 
2469   auto &TLI = DAG.getTargetLoweringInfo();
2470   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2471 
2472   // Build the setcc now.
2473   if (!CB.CmpMHS) {
2474     // Fold "(X == true)" to X and "(X == false)" to !X to
2475     // handle common cases produced by branch lowering.
2476     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2477         CB.CC == ISD::SETEQ)
2478       Cond = CondLHS;
2479     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2480              CB.CC == ISD::SETEQ) {
2481       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2482       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2483     } else {
2484       SDValue CondRHS = getValue(CB.CmpRHS);
2485 
2486       // If a pointer's DAG type is larger than its memory type then the DAG
2487       // values are zero-extended. This breaks signed comparisons so truncate
2488       // back to the underlying type before doing the compare.
2489       if (CondLHS.getValueType() != MemVT) {
2490         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2491         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2492       }
2493       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2494     }
2495   } else {
2496     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2497 
2498     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2499     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2500 
2501     SDValue CmpOp = getValue(CB.CmpMHS);
2502     EVT VT = CmpOp.getValueType();
2503 
2504     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2505       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2506                           ISD::SETLE);
2507     } else {
2508       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2509                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2510       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2511                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2512     }
2513   }
2514 
2515   // Update successor info
2516   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2517   // TrueBB and FalseBB are always different unless the incoming IR is
2518   // degenerate. This only happens when running llc on weird IR.
2519   if (CB.TrueBB != CB.FalseBB)
2520     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2521   SwitchBB->normalizeSuccProbs();
2522 
2523   // If the lhs block is the next block, invert the condition so that we can
2524   // fall through to the lhs instead of the rhs block.
2525   if (CB.TrueBB == NextBlock(SwitchBB)) {
2526     std::swap(CB.TrueBB, CB.FalseBB);
2527     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2528     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2529   }
2530 
2531   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2532                                MVT::Other, getControlRoot(), Cond,
2533                                DAG.getBasicBlock(CB.TrueBB));
2534 
2535   // Insert the false branch. Do this even if it's a fall through branch,
2536   // this makes it easier to do DAG optimizations which require inverting
2537   // the branch condition.
2538   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2539                        DAG.getBasicBlock(CB.FalseBB));
2540 
2541   DAG.setRoot(BrCond);
2542 }
2543 
2544 /// visitJumpTable - Emit JumpTable node in the current MBB
2545 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2546   // Emit the code for the jump table
2547   assert(JT.Reg != -1U && "Should lower JT Header first!");
2548   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2549   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2550                                      JT.Reg, PTy);
2551   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2552   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2553                                     MVT::Other, Index.getValue(1),
2554                                     Table, Index);
2555   DAG.setRoot(BrJumpTable);
2556 }
2557 
2558 /// visitJumpTableHeader - This function emits necessary code to produce index
2559 /// in the JumpTable from switch case.
2560 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2561                                                JumpTableHeader &JTH,
2562                                                MachineBasicBlock *SwitchBB) {
2563   SDLoc dl = getCurSDLoc();
2564 
2565   // Subtract the lowest switch case value from the value being switched on.
2566   SDValue SwitchOp = getValue(JTH.SValue);
2567   EVT VT = SwitchOp.getValueType();
2568   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2569                             DAG.getConstant(JTH.First, dl, VT));
2570 
2571   // The SDNode we just created, which holds the value being switched on minus
2572   // the smallest case value, needs to be copied to a virtual register so it
2573   // can be used as an index into the jump table in a subsequent basic block.
2574   // This value may be smaller or larger than the target's pointer type, and
2575   // therefore require extension or truncating.
2576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2577   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2578 
2579   unsigned JumpTableReg =
2580       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2581   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2582                                     JumpTableReg, SwitchOp);
2583   JT.Reg = JumpTableReg;
2584 
2585   if (!JTH.FallthroughUnreachable) {
2586     // Emit the range check for the jump table, and branch to the default block
2587     // for the switch statement if the value being switched on exceeds the
2588     // largest case in the switch.
2589     SDValue CMP = DAG.getSetCC(
2590         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2591                                    Sub.getValueType()),
2592         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2593 
2594     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2595                                  MVT::Other, CopyTo, CMP,
2596                                  DAG.getBasicBlock(JT.Default));
2597 
2598     // Avoid emitting unnecessary branches to the next block.
2599     if (JT.MBB != NextBlock(SwitchBB))
2600       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2601                            DAG.getBasicBlock(JT.MBB));
2602 
2603     DAG.setRoot(BrCond);
2604   } else {
2605     // Avoid emitting unnecessary branches to the next block.
2606     if (JT.MBB != NextBlock(SwitchBB))
2607       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2608                               DAG.getBasicBlock(JT.MBB)));
2609     else
2610       DAG.setRoot(CopyTo);
2611   }
2612 }
2613 
2614 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2615 /// variable if there exists one.
2616 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2617                                  SDValue &Chain) {
2618   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2619   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2620   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2621   MachineFunction &MF = DAG.getMachineFunction();
2622   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2623   MachineSDNode *Node =
2624       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2625   if (Global) {
2626     MachinePointerInfo MPInfo(Global);
2627     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2628                  MachineMemOperand::MODereferenceable;
2629     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2630         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2631     DAG.setNodeMemRefs(Node, {MemRef});
2632   }
2633   if (PtrTy != PtrMemTy)
2634     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2635   return SDValue(Node, 0);
2636 }
2637 
2638 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2639 /// tail spliced into a stack protector check success bb.
2640 ///
2641 /// For a high level explanation of how this fits into the stack protector
2642 /// generation see the comment on the declaration of class
2643 /// StackProtectorDescriptor.
2644 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2645                                                   MachineBasicBlock *ParentBB) {
2646 
2647   // First create the loads to the guard/stack slot for the comparison.
2648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2649   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2650   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2651 
2652   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2653   int FI = MFI.getStackProtectorIndex();
2654 
2655   SDValue Guard;
2656   SDLoc dl = getCurSDLoc();
2657   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2658   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2659   Align Align =
2660       DAG.getDataLayout().getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2661 
2662   // Generate code to load the content of the guard slot.
2663   SDValue GuardVal = DAG.getLoad(
2664       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2665       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2666       MachineMemOperand::MOVolatile);
2667 
2668   if (TLI.useStackGuardXorFP())
2669     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2670 
2671   // Retrieve guard check function, nullptr if instrumentation is inlined.
2672   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2673     // The target provides a guard check function to validate the guard value.
2674     // Generate a call to that function with the content of the guard slot as
2675     // argument.
2676     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2677     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2678 
2679     TargetLowering::ArgListTy Args;
2680     TargetLowering::ArgListEntry Entry;
2681     Entry.Node = GuardVal;
2682     Entry.Ty = FnTy->getParamType(0);
2683     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
2684       Entry.IsInReg = true;
2685     Args.push_back(Entry);
2686 
2687     TargetLowering::CallLoweringInfo CLI(DAG);
2688     CLI.setDebugLoc(getCurSDLoc())
2689         .setChain(DAG.getEntryNode())
2690         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2691                    getValue(GuardCheckFn), std::move(Args));
2692 
2693     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2694     DAG.setRoot(Result.second);
2695     return;
2696   }
2697 
2698   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2699   // Otherwise, emit a volatile load to retrieve the stack guard value.
2700   SDValue Chain = DAG.getEntryNode();
2701   if (TLI.useLoadStackGuardNode()) {
2702     Guard = getLoadStackGuard(DAG, dl, Chain);
2703   } else {
2704     const Value *IRGuard = TLI.getSDagStackGuard(M);
2705     SDValue GuardPtr = getValue(IRGuard);
2706 
2707     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2708                         MachinePointerInfo(IRGuard, 0), Align,
2709                         MachineMemOperand::MOVolatile);
2710   }
2711 
2712   // Perform the comparison via a getsetcc.
2713   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2714                                                         *DAG.getContext(),
2715                                                         Guard.getValueType()),
2716                              Guard, GuardVal, ISD::SETNE);
2717 
2718   // If the guard/stackslot do not equal, branch to failure MBB.
2719   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2720                                MVT::Other, GuardVal.getOperand(0),
2721                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2722   // Otherwise branch to success MBB.
2723   SDValue Br = DAG.getNode(ISD::BR, dl,
2724                            MVT::Other, BrCond,
2725                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2726 
2727   DAG.setRoot(Br);
2728 }
2729 
2730 /// Codegen the failure basic block for a stack protector check.
2731 ///
2732 /// A failure stack protector machine basic block consists simply of a call to
2733 /// __stack_chk_fail().
2734 ///
2735 /// For a high level explanation of how this fits into the stack protector
2736 /// generation see the comment on the declaration of class
2737 /// StackProtectorDescriptor.
2738 void
2739 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2740   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2741   TargetLowering::MakeLibCallOptions CallOptions;
2742   CallOptions.setDiscardResult(true);
2743   SDValue Chain =
2744       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2745                       None, CallOptions, getCurSDLoc()).second;
2746   // On PS4, the "return address" must still be within the calling function,
2747   // even if it's at the very end, so emit an explicit TRAP here.
2748   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2749   if (TM.getTargetTriple().isPS4CPU())
2750     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2751   // WebAssembly needs an unreachable instruction after a non-returning call,
2752   // because the function return type can be different from __stack_chk_fail's
2753   // return type (void).
2754   if (TM.getTargetTriple().isWasm())
2755     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2756 
2757   DAG.setRoot(Chain);
2758 }
2759 
2760 /// visitBitTestHeader - This function emits necessary code to produce value
2761 /// suitable for "bit tests"
2762 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2763                                              MachineBasicBlock *SwitchBB) {
2764   SDLoc dl = getCurSDLoc();
2765 
2766   // Subtract the minimum value.
2767   SDValue SwitchOp = getValue(B.SValue);
2768   EVT VT = SwitchOp.getValueType();
2769   SDValue RangeSub =
2770       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2771 
2772   // Determine the type of the test operands.
2773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2774   bool UsePtrType = false;
2775   if (!TLI.isTypeLegal(VT)) {
2776     UsePtrType = true;
2777   } else {
2778     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2779       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2780         // Switch table case range are encoded into series of masks.
2781         // Just use pointer type, it's guaranteed to fit.
2782         UsePtrType = true;
2783         break;
2784       }
2785   }
2786   SDValue Sub = RangeSub;
2787   if (UsePtrType) {
2788     VT = TLI.getPointerTy(DAG.getDataLayout());
2789     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2790   }
2791 
2792   B.RegVT = VT.getSimpleVT();
2793   B.Reg = FuncInfo.CreateReg(B.RegVT);
2794   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2795 
2796   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2797 
2798   if (!B.FallthroughUnreachable)
2799     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2800   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2801   SwitchBB->normalizeSuccProbs();
2802 
2803   SDValue Root = CopyTo;
2804   if (!B.FallthroughUnreachable) {
2805     // Conditional branch to the default block.
2806     SDValue RangeCmp = DAG.getSetCC(dl,
2807         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2808                                RangeSub.getValueType()),
2809         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2810         ISD::SETUGT);
2811 
2812     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2813                        DAG.getBasicBlock(B.Default));
2814   }
2815 
2816   // Avoid emitting unnecessary branches to the next block.
2817   if (MBB != NextBlock(SwitchBB))
2818     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2819 
2820   DAG.setRoot(Root);
2821 }
2822 
2823 /// visitBitTestCase - this function produces one "bit test"
2824 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2825                                            MachineBasicBlock* NextMBB,
2826                                            BranchProbability BranchProbToNext,
2827                                            unsigned Reg,
2828                                            BitTestCase &B,
2829                                            MachineBasicBlock *SwitchBB) {
2830   SDLoc dl = getCurSDLoc();
2831   MVT VT = BB.RegVT;
2832   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2833   SDValue Cmp;
2834   unsigned PopCount = countPopulation(B.Mask);
2835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2836   if (PopCount == 1) {
2837     // Testing for a single bit; just compare the shift count with what it
2838     // would need to be to shift a 1 bit in that position.
2839     Cmp = DAG.getSetCC(
2840         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2841         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2842         ISD::SETEQ);
2843   } else if (PopCount == BB.Range) {
2844     // There is only one zero bit in the range, test for it directly.
2845     Cmp = DAG.getSetCC(
2846         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2847         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2848         ISD::SETNE);
2849   } else {
2850     // Make desired shift
2851     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2852                                     DAG.getConstant(1, dl, VT), ShiftOp);
2853 
2854     // Emit bit tests and jumps
2855     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2856                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2857     Cmp = DAG.getSetCC(
2858         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2859         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2860   }
2861 
2862   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2863   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2864   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2865   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2866   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2867   // one as they are relative probabilities (and thus work more like weights),
2868   // and hence we need to normalize them to let the sum of them become one.
2869   SwitchBB->normalizeSuccProbs();
2870 
2871   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2872                               MVT::Other, getControlRoot(),
2873                               Cmp, DAG.getBasicBlock(B.TargetBB));
2874 
2875   // Avoid emitting unnecessary branches to the next block.
2876   if (NextMBB != NextBlock(SwitchBB))
2877     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2878                         DAG.getBasicBlock(NextMBB));
2879 
2880   DAG.setRoot(BrAnd);
2881 }
2882 
2883 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2884   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2885 
2886   // Retrieve successors. Look through artificial IR level blocks like
2887   // catchswitch for successors.
2888   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2889   const BasicBlock *EHPadBB = I.getSuccessor(1);
2890 
2891   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2892   // have to do anything here to lower funclet bundles.
2893   assert(!I.hasOperandBundlesOtherThan(
2894              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2895               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2896               LLVMContext::OB_cfguardtarget,
2897               LLVMContext::OB_clang_arc_attachedcall}) &&
2898          "Cannot lower invokes with arbitrary operand bundles yet!");
2899 
2900   const Value *Callee(I.getCalledOperand());
2901   const Function *Fn = dyn_cast<Function>(Callee);
2902   if (isa<InlineAsm>(Callee))
2903     visitInlineAsm(I, EHPadBB);
2904   else if (Fn && Fn->isIntrinsic()) {
2905     switch (Fn->getIntrinsicID()) {
2906     default:
2907       llvm_unreachable("Cannot invoke this intrinsic");
2908     case Intrinsic::donothing:
2909       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2910     case Intrinsic::seh_try_begin:
2911     case Intrinsic::seh_scope_begin:
2912     case Intrinsic::seh_try_end:
2913     case Intrinsic::seh_scope_end:
2914       break;
2915     case Intrinsic::experimental_patchpoint_void:
2916     case Intrinsic::experimental_patchpoint_i64:
2917       visitPatchpoint(I, EHPadBB);
2918       break;
2919     case Intrinsic::experimental_gc_statepoint:
2920       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2921       break;
2922     case Intrinsic::wasm_rethrow: {
2923       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2924       // special because it can be invoked, so we manually lower it to a DAG
2925       // node here.
2926       SmallVector<SDValue, 8> Ops;
2927       Ops.push_back(getRoot()); // inchain
2928       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2929       Ops.push_back(
2930           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2931                                 TLI.getPointerTy(DAG.getDataLayout())));
2932       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2933       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2934       break;
2935     }
2936     }
2937   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2938     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2939     // Eventually we will support lowering the @llvm.experimental.deoptimize
2940     // intrinsic, and right now there are no plans to support other intrinsics
2941     // with deopt state.
2942     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2943   } else {
2944     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
2945   }
2946 
2947   // If the value of the invoke is used outside of its defining block, make it
2948   // available as a virtual register.
2949   // We already took care of the exported value for the statepoint instruction
2950   // during call to the LowerStatepoint.
2951   if (!isa<GCStatepointInst>(I)) {
2952     CopyToExportRegsIfNeeded(&I);
2953   }
2954 
2955   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2956   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2957   BranchProbability EHPadBBProb =
2958       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2959           : BranchProbability::getZero();
2960   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2961 
2962   // Update successor info.
2963   addSuccessorWithProb(InvokeMBB, Return);
2964   for (auto &UnwindDest : UnwindDests) {
2965     UnwindDest.first->setIsEHPad();
2966     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2967   }
2968   InvokeMBB->normalizeSuccProbs();
2969 
2970   // Drop into normal successor.
2971   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2972                           DAG.getBasicBlock(Return)));
2973 }
2974 
2975 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2976   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2977 
2978   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2979   // have to do anything here to lower funclet bundles.
2980   assert(!I.hasOperandBundlesOtherThan(
2981              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2982          "Cannot lower callbrs with arbitrary operand bundles yet!");
2983 
2984   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2985   visitInlineAsm(I);
2986   CopyToExportRegsIfNeeded(&I);
2987 
2988   // Retrieve successors.
2989   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2990 
2991   // Update successor info.
2992   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2993   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2994     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2995     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2996     Target->setIsInlineAsmBrIndirectTarget();
2997   }
2998   CallBrMBB->normalizeSuccProbs();
2999 
3000   // Drop into default successor.
3001   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3002                           MVT::Other, getControlRoot(),
3003                           DAG.getBasicBlock(Return)));
3004 }
3005 
3006 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3007   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3008 }
3009 
3010 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3011   assert(FuncInfo.MBB->isEHPad() &&
3012          "Call to landingpad not in landing pad!");
3013 
3014   // If there aren't registers to copy the values into (e.g., during SjLj
3015   // exceptions), then don't bother to create these DAG nodes.
3016   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3017   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3018   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3019       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3020     return;
3021 
3022   // If landingpad's return type is token type, we don't create DAG nodes
3023   // for its exception pointer and selector value. The extraction of exception
3024   // pointer or selector value from token type landingpads is not currently
3025   // supported.
3026   if (LP.getType()->isTokenTy())
3027     return;
3028 
3029   SmallVector<EVT, 2> ValueVTs;
3030   SDLoc dl = getCurSDLoc();
3031   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3032   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3033 
3034   // Get the two live-in registers as SDValues. The physregs have already been
3035   // copied into virtual registers.
3036   SDValue Ops[2];
3037   if (FuncInfo.ExceptionPointerVirtReg) {
3038     Ops[0] = DAG.getZExtOrTrunc(
3039         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3040                            FuncInfo.ExceptionPointerVirtReg,
3041                            TLI.getPointerTy(DAG.getDataLayout())),
3042         dl, ValueVTs[0]);
3043   } else {
3044     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3045   }
3046   Ops[1] = DAG.getZExtOrTrunc(
3047       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3048                          FuncInfo.ExceptionSelectorVirtReg,
3049                          TLI.getPointerTy(DAG.getDataLayout())),
3050       dl, ValueVTs[1]);
3051 
3052   // Merge into one.
3053   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3054                             DAG.getVTList(ValueVTs), Ops);
3055   setValue(&LP, Res);
3056 }
3057 
3058 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3059                                            MachineBasicBlock *Last) {
3060   // Update JTCases.
3061   for (JumpTableBlock &JTB : SL->JTCases)
3062     if (JTB.first.HeaderBB == First)
3063       JTB.first.HeaderBB = Last;
3064 
3065   // Update BitTestCases.
3066   for (BitTestBlock &BTB : SL->BitTestCases)
3067     if (BTB.Parent == First)
3068       BTB.Parent = Last;
3069 }
3070 
3071 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3072   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3073 
3074   // Update machine-CFG edges with unique successors.
3075   SmallSet<BasicBlock*, 32> Done;
3076   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3077     BasicBlock *BB = I.getSuccessor(i);
3078     bool Inserted = Done.insert(BB).second;
3079     if (!Inserted)
3080         continue;
3081 
3082     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3083     addSuccessorWithProb(IndirectBrMBB, Succ);
3084   }
3085   IndirectBrMBB->normalizeSuccProbs();
3086 
3087   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3088                           MVT::Other, getControlRoot(),
3089                           getValue(I.getAddress())));
3090 }
3091 
3092 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3093   if (!DAG.getTarget().Options.TrapUnreachable)
3094     return;
3095 
3096   // We may be able to ignore unreachable behind a noreturn call.
3097   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3098     const BasicBlock &BB = *I.getParent();
3099     if (&I != &BB.front()) {
3100       BasicBlock::const_iterator PredI =
3101         std::prev(BasicBlock::const_iterator(&I));
3102       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
3103         if (Call->doesNotReturn())
3104           return;
3105       }
3106     }
3107   }
3108 
3109   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3110 }
3111 
3112 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3113   SDNodeFlags Flags;
3114 
3115   SDValue Op = getValue(I.getOperand(0));
3116   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3117                                     Op, Flags);
3118   setValue(&I, UnNodeValue);
3119 }
3120 
3121 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3122   SDNodeFlags Flags;
3123   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3124     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3125     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3126   }
3127   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3128     Flags.setExact(ExactOp->isExact());
3129   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3130     Flags.copyFMF(*FPOp);
3131 
3132   SDValue Op1 = getValue(I.getOperand(0));
3133   SDValue Op2 = getValue(I.getOperand(1));
3134   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3135                                      Op1, Op2, Flags);
3136   setValue(&I, BinNodeValue);
3137 }
3138 
3139 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3140   SDValue Op1 = getValue(I.getOperand(0));
3141   SDValue Op2 = getValue(I.getOperand(1));
3142 
3143   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3144       Op1.getValueType(), DAG.getDataLayout());
3145 
3146   // Coerce the shift amount to the right type if we can.
3147   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3148     unsigned ShiftSize = ShiftTy.getSizeInBits();
3149     unsigned Op2Size = Op2.getValueSizeInBits();
3150     SDLoc DL = getCurSDLoc();
3151 
3152     // If the operand is smaller than the shift count type, promote it.
3153     if (ShiftSize > Op2Size)
3154       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3155 
3156     // If the operand is larger than the shift count type but the shift
3157     // count type has enough bits to represent any shift value, truncate
3158     // it now. This is a common case and it exposes the truncate to
3159     // optimization early.
3160     else if (ShiftSize >= Log2_32_Ceil(Op1.getValueSizeInBits()))
3161       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3162     // Otherwise we'll need to temporarily settle for some other convenient
3163     // type.  Type legalization will make adjustments once the shiftee is split.
3164     else
3165       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3166   }
3167 
3168   bool nuw = false;
3169   bool nsw = false;
3170   bool exact = false;
3171 
3172   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3173 
3174     if (const OverflowingBinaryOperator *OFBinOp =
3175             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3176       nuw = OFBinOp->hasNoUnsignedWrap();
3177       nsw = OFBinOp->hasNoSignedWrap();
3178     }
3179     if (const PossiblyExactOperator *ExactOp =
3180             dyn_cast<const PossiblyExactOperator>(&I))
3181       exact = ExactOp->isExact();
3182   }
3183   SDNodeFlags Flags;
3184   Flags.setExact(exact);
3185   Flags.setNoSignedWrap(nsw);
3186   Flags.setNoUnsignedWrap(nuw);
3187   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3188                             Flags);
3189   setValue(&I, Res);
3190 }
3191 
3192 void SelectionDAGBuilder::visitSDiv(const User &I) {
3193   SDValue Op1 = getValue(I.getOperand(0));
3194   SDValue Op2 = getValue(I.getOperand(1));
3195 
3196   SDNodeFlags Flags;
3197   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3198                  cast<PossiblyExactOperator>(&I)->isExact());
3199   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3200                            Op2, Flags));
3201 }
3202 
3203 void SelectionDAGBuilder::visitICmp(const User &I) {
3204   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3205   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3206     predicate = IC->getPredicate();
3207   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3208     predicate = ICmpInst::Predicate(IC->getPredicate());
3209   SDValue Op1 = getValue(I.getOperand(0));
3210   SDValue Op2 = getValue(I.getOperand(1));
3211   ISD::CondCode Opcode = getICmpCondCode(predicate);
3212 
3213   auto &TLI = DAG.getTargetLoweringInfo();
3214   EVT MemVT =
3215       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3216 
3217   // If a pointer's DAG type is larger than its memory type then the DAG values
3218   // are zero-extended. This breaks signed comparisons so truncate back to the
3219   // underlying type before doing the compare.
3220   if (Op1.getValueType() != MemVT) {
3221     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3222     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3223   }
3224 
3225   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3226                                                         I.getType());
3227   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3228 }
3229 
3230 void SelectionDAGBuilder::visitFCmp(const User &I) {
3231   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3232   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3233     predicate = FC->getPredicate();
3234   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3235     predicate = FCmpInst::Predicate(FC->getPredicate());
3236   SDValue Op1 = getValue(I.getOperand(0));
3237   SDValue Op2 = getValue(I.getOperand(1));
3238 
3239   ISD::CondCode Condition = getFCmpCondCode(predicate);
3240   auto *FPMO = cast<FPMathOperator>(&I);
3241   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3242     Condition = getFCmpCodeWithoutNaN(Condition);
3243 
3244   SDNodeFlags Flags;
3245   Flags.copyFMF(*FPMO);
3246   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3247 
3248   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3249                                                         I.getType());
3250   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3251 }
3252 
3253 // Check if the condition of the select has one use or two users that are both
3254 // selects with the same condition.
3255 static bool hasOnlySelectUsers(const Value *Cond) {
3256   return llvm::all_of(Cond->users(), [](const Value *V) {
3257     return isa<SelectInst>(V);
3258   });
3259 }
3260 
3261 void SelectionDAGBuilder::visitSelect(const User &I) {
3262   SmallVector<EVT, 4> ValueVTs;
3263   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3264                   ValueVTs);
3265   unsigned NumValues = ValueVTs.size();
3266   if (NumValues == 0) return;
3267 
3268   SmallVector<SDValue, 4> Values(NumValues);
3269   SDValue Cond     = getValue(I.getOperand(0));
3270   SDValue LHSVal   = getValue(I.getOperand(1));
3271   SDValue RHSVal   = getValue(I.getOperand(2));
3272   SmallVector<SDValue, 1> BaseOps(1, Cond);
3273   ISD::NodeType OpCode =
3274       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3275 
3276   bool IsUnaryAbs = false;
3277   bool Negate = false;
3278 
3279   SDNodeFlags Flags;
3280   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3281     Flags.copyFMF(*FPOp);
3282 
3283   // Min/max matching is only viable if all output VTs are the same.
3284   if (is_splat(ValueVTs)) {
3285     EVT VT = ValueVTs[0];
3286     LLVMContext &Ctx = *DAG.getContext();
3287     auto &TLI = DAG.getTargetLoweringInfo();
3288 
3289     // We care about the legality of the operation after it has been type
3290     // legalized.
3291     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3292       VT = TLI.getTypeToTransformTo(Ctx, VT);
3293 
3294     // If the vselect is legal, assume we want to leave this as a vector setcc +
3295     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3296     // min/max is legal on the scalar type.
3297     bool UseScalarMinMax = VT.isVector() &&
3298       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3299 
3300     Value *LHS, *RHS;
3301     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3302     ISD::NodeType Opc = ISD::DELETED_NODE;
3303     switch (SPR.Flavor) {
3304     case SPF_UMAX:    Opc = ISD::UMAX; break;
3305     case SPF_UMIN:    Opc = ISD::UMIN; break;
3306     case SPF_SMAX:    Opc = ISD::SMAX; break;
3307     case SPF_SMIN:    Opc = ISD::SMIN; break;
3308     case SPF_FMINNUM:
3309       switch (SPR.NaNBehavior) {
3310       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3311       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3312       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3313       case SPNB_RETURNS_ANY: {
3314         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3315           Opc = ISD::FMINNUM;
3316         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3317           Opc = ISD::FMINIMUM;
3318         else if (UseScalarMinMax)
3319           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3320             ISD::FMINNUM : ISD::FMINIMUM;
3321         break;
3322       }
3323       }
3324       break;
3325     case SPF_FMAXNUM:
3326       switch (SPR.NaNBehavior) {
3327       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3328       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3329       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3330       case SPNB_RETURNS_ANY:
3331 
3332         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3333           Opc = ISD::FMAXNUM;
3334         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3335           Opc = ISD::FMAXIMUM;
3336         else if (UseScalarMinMax)
3337           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3338             ISD::FMAXNUM : ISD::FMAXIMUM;
3339         break;
3340       }
3341       break;
3342     case SPF_NABS:
3343       Negate = true;
3344       LLVM_FALLTHROUGH;
3345     case SPF_ABS:
3346       IsUnaryAbs = true;
3347       Opc = ISD::ABS;
3348       break;
3349     default: break;
3350     }
3351 
3352     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3353         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3354          (UseScalarMinMax &&
3355           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3356         // If the underlying comparison instruction is used by any other
3357         // instruction, the consumed instructions won't be destroyed, so it is
3358         // not profitable to convert to a min/max.
3359         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3360       OpCode = Opc;
3361       LHSVal = getValue(LHS);
3362       RHSVal = getValue(RHS);
3363       BaseOps.clear();
3364     }
3365 
3366     if (IsUnaryAbs) {
3367       OpCode = Opc;
3368       LHSVal = getValue(LHS);
3369       BaseOps.clear();
3370     }
3371   }
3372 
3373   if (IsUnaryAbs) {
3374     for (unsigned i = 0; i != NumValues; ++i) {
3375       SDLoc dl = getCurSDLoc();
3376       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3377       Values[i] =
3378           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3379       if (Negate)
3380         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3381                                 Values[i]);
3382     }
3383   } else {
3384     for (unsigned i = 0; i != NumValues; ++i) {
3385       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3386       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3387       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3388       Values[i] = DAG.getNode(
3389           OpCode, getCurSDLoc(),
3390           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3391     }
3392   }
3393 
3394   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3395                            DAG.getVTList(ValueVTs), Values));
3396 }
3397 
3398 void SelectionDAGBuilder::visitTrunc(const User &I) {
3399   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3400   SDValue N = getValue(I.getOperand(0));
3401   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3402                                                         I.getType());
3403   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3404 }
3405 
3406 void SelectionDAGBuilder::visitZExt(const User &I) {
3407   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3408   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3409   SDValue N = getValue(I.getOperand(0));
3410   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3411                                                         I.getType());
3412   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3413 }
3414 
3415 void SelectionDAGBuilder::visitSExt(const User &I) {
3416   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3417   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3418   SDValue N = getValue(I.getOperand(0));
3419   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3420                                                         I.getType());
3421   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3422 }
3423 
3424 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3425   // FPTrunc is never a no-op cast, no need to check
3426   SDValue N = getValue(I.getOperand(0));
3427   SDLoc dl = getCurSDLoc();
3428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3429   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3430   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3431                            DAG.getTargetConstant(
3432                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3433 }
3434 
3435 void SelectionDAGBuilder::visitFPExt(const User &I) {
3436   // FPExt is never a no-op cast, no need to check
3437   SDValue N = getValue(I.getOperand(0));
3438   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3439                                                         I.getType());
3440   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3441 }
3442 
3443 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3444   // FPToUI is never a no-op cast, no need to check
3445   SDValue N = getValue(I.getOperand(0));
3446   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3447                                                         I.getType());
3448   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3449 }
3450 
3451 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3452   // FPToSI is never a no-op cast, no need to check
3453   SDValue N = getValue(I.getOperand(0));
3454   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3455                                                         I.getType());
3456   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3457 }
3458 
3459 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3460   // UIToFP is never a no-op cast, no need to check
3461   SDValue N = getValue(I.getOperand(0));
3462   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3463                                                         I.getType());
3464   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3465 }
3466 
3467 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3468   // SIToFP is never a no-op cast, no need to check
3469   SDValue N = getValue(I.getOperand(0));
3470   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3471                                                         I.getType());
3472   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3473 }
3474 
3475 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3476   // What to do depends on the size of the integer and the size of the pointer.
3477   // We can either truncate, zero extend, or no-op, accordingly.
3478   SDValue N = getValue(I.getOperand(0));
3479   auto &TLI = DAG.getTargetLoweringInfo();
3480   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3481                                                         I.getType());
3482   EVT PtrMemVT =
3483       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3484   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3485   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3486   setValue(&I, N);
3487 }
3488 
3489 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3490   // What to do depends on the size of the integer and the size of the pointer.
3491   // We can either truncate, zero extend, or no-op, accordingly.
3492   SDValue N = getValue(I.getOperand(0));
3493   auto &TLI = DAG.getTargetLoweringInfo();
3494   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3495   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3496   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3497   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3498   setValue(&I, N);
3499 }
3500 
3501 void SelectionDAGBuilder::visitBitCast(const User &I) {
3502   SDValue N = getValue(I.getOperand(0));
3503   SDLoc dl = getCurSDLoc();
3504   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3505                                                         I.getType());
3506 
3507   // BitCast assures us that source and destination are the same size so this is
3508   // either a BITCAST or a no-op.
3509   if (DestVT != N.getValueType())
3510     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3511                              DestVT, N)); // convert types.
3512   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3513   // might fold any kind of constant expression to an integer constant and that
3514   // is not what we are looking for. Only recognize a bitcast of a genuine
3515   // constant integer as an opaque constant.
3516   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3517     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3518                                  /*isOpaque*/true));
3519   else
3520     setValue(&I, N);            // noop cast.
3521 }
3522 
3523 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3525   const Value *SV = I.getOperand(0);
3526   SDValue N = getValue(SV);
3527   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3528 
3529   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3530   unsigned DestAS = I.getType()->getPointerAddressSpace();
3531 
3532   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3533     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3534 
3535   setValue(&I, N);
3536 }
3537 
3538 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3540   SDValue InVec = getValue(I.getOperand(0));
3541   SDValue InVal = getValue(I.getOperand(1));
3542   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3543                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3544   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3545                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3546                            InVec, InVal, InIdx));
3547 }
3548 
3549 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3551   SDValue InVec = getValue(I.getOperand(0));
3552   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3553                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3554   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3555                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3556                            InVec, InIdx));
3557 }
3558 
3559 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3560   SDValue Src1 = getValue(I.getOperand(0));
3561   SDValue Src2 = getValue(I.getOperand(1));
3562   ArrayRef<int> Mask;
3563   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3564     Mask = SVI->getShuffleMask();
3565   else
3566     Mask = cast<ConstantExpr>(I).getShuffleMask();
3567   SDLoc DL = getCurSDLoc();
3568   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3569   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3570   EVT SrcVT = Src1.getValueType();
3571 
3572   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3573       VT.isScalableVector()) {
3574     // Canonical splat form of first element of first input vector.
3575     SDValue FirstElt =
3576         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3577                     DAG.getVectorIdxConstant(0, DL));
3578     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3579     return;
3580   }
3581 
3582   // For now, we only handle splats for scalable vectors.
3583   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3584   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3585   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3586 
3587   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3588   unsigned MaskNumElts = Mask.size();
3589 
3590   if (SrcNumElts == MaskNumElts) {
3591     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3592     return;
3593   }
3594 
3595   // Normalize the shuffle vector since mask and vector length don't match.
3596   if (SrcNumElts < MaskNumElts) {
3597     // Mask is longer than the source vectors. We can use concatenate vector to
3598     // make the mask and vectors lengths match.
3599 
3600     if (MaskNumElts % SrcNumElts == 0) {
3601       // Mask length is a multiple of the source vector length.
3602       // Check if the shuffle is some kind of concatenation of the input
3603       // vectors.
3604       unsigned NumConcat = MaskNumElts / SrcNumElts;
3605       bool IsConcat = true;
3606       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3607       for (unsigned i = 0; i != MaskNumElts; ++i) {
3608         int Idx = Mask[i];
3609         if (Idx < 0)
3610           continue;
3611         // Ensure the indices in each SrcVT sized piece are sequential and that
3612         // the same source is used for the whole piece.
3613         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3614             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3615              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3616           IsConcat = false;
3617           break;
3618         }
3619         // Remember which source this index came from.
3620         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3621       }
3622 
3623       // The shuffle is concatenating multiple vectors together. Just emit
3624       // a CONCAT_VECTORS operation.
3625       if (IsConcat) {
3626         SmallVector<SDValue, 8> ConcatOps;
3627         for (auto Src : ConcatSrcs) {
3628           if (Src < 0)
3629             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3630           else if (Src == 0)
3631             ConcatOps.push_back(Src1);
3632           else
3633             ConcatOps.push_back(Src2);
3634         }
3635         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3636         return;
3637       }
3638     }
3639 
3640     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3641     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3642     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3643                                     PaddedMaskNumElts);
3644 
3645     // Pad both vectors with undefs to make them the same length as the mask.
3646     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3647 
3648     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3649     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3650     MOps1[0] = Src1;
3651     MOps2[0] = Src2;
3652 
3653     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3654     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3655 
3656     // Readjust mask for new input vector length.
3657     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3658     for (unsigned i = 0; i != MaskNumElts; ++i) {
3659       int Idx = Mask[i];
3660       if (Idx >= (int)SrcNumElts)
3661         Idx -= SrcNumElts - PaddedMaskNumElts;
3662       MappedOps[i] = Idx;
3663     }
3664 
3665     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3666 
3667     // If the concatenated vector was padded, extract a subvector with the
3668     // correct number of elements.
3669     if (MaskNumElts != PaddedMaskNumElts)
3670       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3671                            DAG.getVectorIdxConstant(0, DL));
3672 
3673     setValue(&I, Result);
3674     return;
3675   }
3676 
3677   if (SrcNumElts > MaskNumElts) {
3678     // Analyze the access pattern of the vector to see if we can extract
3679     // two subvectors and do the shuffle.
3680     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3681     bool CanExtract = true;
3682     for (int Idx : Mask) {
3683       unsigned Input = 0;
3684       if (Idx < 0)
3685         continue;
3686 
3687       if (Idx >= (int)SrcNumElts) {
3688         Input = 1;
3689         Idx -= SrcNumElts;
3690       }
3691 
3692       // If all the indices come from the same MaskNumElts sized portion of
3693       // the sources we can use extract. Also make sure the extract wouldn't
3694       // extract past the end of the source.
3695       int NewStartIdx = alignDown(Idx, MaskNumElts);
3696       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3697           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3698         CanExtract = false;
3699       // Make sure we always update StartIdx as we use it to track if all
3700       // elements are undef.
3701       StartIdx[Input] = NewStartIdx;
3702     }
3703 
3704     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3705       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3706       return;
3707     }
3708     if (CanExtract) {
3709       // Extract appropriate subvector and generate a vector shuffle
3710       for (unsigned Input = 0; Input < 2; ++Input) {
3711         SDValue &Src = Input == 0 ? Src1 : Src2;
3712         if (StartIdx[Input] < 0)
3713           Src = DAG.getUNDEF(VT);
3714         else {
3715           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3716                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3717         }
3718       }
3719 
3720       // Calculate new mask.
3721       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3722       for (int &Idx : MappedOps) {
3723         if (Idx >= (int)SrcNumElts)
3724           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3725         else if (Idx >= 0)
3726           Idx -= StartIdx[0];
3727       }
3728 
3729       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3730       return;
3731     }
3732   }
3733 
3734   // We can't use either concat vectors or extract subvectors so fall back to
3735   // replacing the shuffle with extract and build vector.
3736   // to insert and build vector.
3737   EVT EltVT = VT.getVectorElementType();
3738   SmallVector<SDValue,8> Ops;
3739   for (int Idx : Mask) {
3740     SDValue Res;
3741 
3742     if (Idx < 0) {
3743       Res = DAG.getUNDEF(EltVT);
3744     } else {
3745       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3746       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3747 
3748       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3749                         DAG.getVectorIdxConstant(Idx, DL));
3750     }
3751 
3752     Ops.push_back(Res);
3753   }
3754 
3755   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3756 }
3757 
3758 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3759   ArrayRef<unsigned> Indices;
3760   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3761     Indices = IV->getIndices();
3762   else
3763     Indices = cast<ConstantExpr>(&I)->getIndices();
3764 
3765   const Value *Op0 = I.getOperand(0);
3766   const Value *Op1 = I.getOperand(1);
3767   Type *AggTy = I.getType();
3768   Type *ValTy = Op1->getType();
3769   bool IntoUndef = isa<UndefValue>(Op0);
3770   bool FromUndef = isa<UndefValue>(Op1);
3771 
3772   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3773 
3774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3775   SmallVector<EVT, 4> AggValueVTs;
3776   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3777   SmallVector<EVT, 4> ValValueVTs;
3778   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3779 
3780   unsigned NumAggValues = AggValueVTs.size();
3781   unsigned NumValValues = ValValueVTs.size();
3782   SmallVector<SDValue, 4> Values(NumAggValues);
3783 
3784   // Ignore an insertvalue that produces an empty object
3785   if (!NumAggValues) {
3786     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3787     return;
3788   }
3789 
3790   SDValue Agg = getValue(Op0);
3791   unsigned i = 0;
3792   // Copy the beginning value(s) from the original aggregate.
3793   for (; i != LinearIndex; ++i)
3794     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3795                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3796   // Copy values from the inserted value(s).
3797   if (NumValValues) {
3798     SDValue Val = getValue(Op1);
3799     for (; i != LinearIndex + NumValValues; ++i)
3800       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3801                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3802   }
3803   // Copy remaining value(s) from the original aggregate.
3804   for (; i != NumAggValues; ++i)
3805     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3806                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3807 
3808   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3809                            DAG.getVTList(AggValueVTs), Values));
3810 }
3811 
3812 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3813   ArrayRef<unsigned> Indices;
3814   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3815     Indices = EV->getIndices();
3816   else
3817     Indices = cast<ConstantExpr>(&I)->getIndices();
3818 
3819   const Value *Op0 = I.getOperand(0);
3820   Type *AggTy = Op0->getType();
3821   Type *ValTy = I.getType();
3822   bool OutOfUndef = isa<UndefValue>(Op0);
3823 
3824   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3825 
3826   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3827   SmallVector<EVT, 4> ValValueVTs;
3828   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3829 
3830   unsigned NumValValues = ValValueVTs.size();
3831 
3832   // Ignore a extractvalue that produces an empty object
3833   if (!NumValValues) {
3834     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3835     return;
3836   }
3837 
3838   SmallVector<SDValue, 4> Values(NumValValues);
3839 
3840   SDValue Agg = getValue(Op0);
3841   // Copy out the selected value(s).
3842   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3843     Values[i - LinearIndex] =
3844       OutOfUndef ?
3845         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3846         SDValue(Agg.getNode(), Agg.getResNo() + i);
3847 
3848   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3849                            DAG.getVTList(ValValueVTs), Values));
3850 }
3851 
3852 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3853   Value *Op0 = I.getOperand(0);
3854   // Note that the pointer operand may be a vector of pointers. Take the scalar
3855   // element which holds a pointer.
3856   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3857   SDValue N = getValue(Op0);
3858   SDLoc dl = getCurSDLoc();
3859   auto &TLI = DAG.getTargetLoweringInfo();
3860 
3861   // Normalize Vector GEP - all scalar operands should be converted to the
3862   // splat vector.
3863   bool IsVectorGEP = I.getType()->isVectorTy();
3864   ElementCount VectorElementCount =
3865       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3866                   : ElementCount::getFixed(0);
3867 
3868   if (IsVectorGEP && !N.getValueType().isVector()) {
3869     LLVMContext &Context = *DAG.getContext();
3870     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3871     if (VectorElementCount.isScalable())
3872       N = DAG.getSplatVector(VT, dl, N);
3873     else
3874       N = DAG.getSplatBuildVector(VT, dl, N);
3875   }
3876 
3877   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3878        GTI != E; ++GTI) {
3879     const Value *Idx = GTI.getOperand();
3880     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3881       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3882       if (Field) {
3883         // N = N + Offset
3884         uint64_t Offset =
3885             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
3886 
3887         // In an inbounds GEP with an offset that is nonnegative even when
3888         // interpreted as signed, assume there is no unsigned overflow.
3889         SDNodeFlags Flags;
3890         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3891           Flags.setNoUnsignedWrap(true);
3892 
3893         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3894                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3895       }
3896     } else {
3897       // IdxSize is the width of the arithmetic according to IR semantics.
3898       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3899       // (and fix up the result later).
3900       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3901       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3902       TypeSize ElementSize =
3903           DAG.getDataLayout().getTypeAllocSize(GTI.getIndexedType());
3904       // We intentionally mask away the high bits here; ElementSize may not
3905       // fit in IdxTy.
3906       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3907       bool ElementScalable = ElementSize.isScalable();
3908 
3909       // If this is a scalar constant or a splat vector of constants,
3910       // handle it quickly.
3911       const auto *C = dyn_cast<Constant>(Idx);
3912       if (C && isa<VectorType>(C->getType()))
3913         C = C->getSplatValue();
3914 
3915       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3916       if (CI && CI->isZero())
3917         continue;
3918       if (CI && !ElementScalable) {
3919         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3920         LLVMContext &Context = *DAG.getContext();
3921         SDValue OffsVal;
3922         if (IsVectorGEP)
3923           OffsVal = DAG.getConstant(
3924               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3925         else
3926           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3927 
3928         // In an inbounds GEP with an offset that is nonnegative even when
3929         // interpreted as signed, assume there is no unsigned overflow.
3930         SDNodeFlags Flags;
3931         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3932           Flags.setNoUnsignedWrap(true);
3933 
3934         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3935 
3936         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3937         continue;
3938       }
3939 
3940       // N = N + Idx * ElementMul;
3941       SDValue IdxN = getValue(Idx);
3942 
3943       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3944         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3945                                   VectorElementCount);
3946         if (VectorElementCount.isScalable())
3947           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3948         else
3949           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3950       }
3951 
3952       // If the index is smaller or larger than intptr_t, truncate or extend
3953       // it.
3954       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3955 
3956       if (ElementScalable) {
3957         EVT VScaleTy = N.getValueType().getScalarType();
3958         SDValue VScale = DAG.getNode(
3959             ISD::VSCALE, dl, VScaleTy,
3960             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3961         if (IsVectorGEP)
3962           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3963         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3964       } else {
3965         // If this is a multiply by a power of two, turn it into a shl
3966         // immediately.  This is a very common case.
3967         if (ElementMul != 1) {
3968           if (ElementMul.isPowerOf2()) {
3969             unsigned Amt = ElementMul.logBase2();
3970             IdxN = DAG.getNode(ISD::SHL, dl,
3971                                N.getValueType(), IdxN,
3972                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3973           } else {
3974             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3975                                             IdxN.getValueType());
3976             IdxN = DAG.getNode(ISD::MUL, dl,
3977                                N.getValueType(), IdxN, Scale);
3978           }
3979         }
3980       }
3981 
3982       N = DAG.getNode(ISD::ADD, dl,
3983                       N.getValueType(), N, IdxN);
3984     }
3985   }
3986 
3987   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3988   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3989   if (IsVectorGEP) {
3990     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3991     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3992   }
3993 
3994   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3995     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3996 
3997   setValue(&I, N);
3998 }
3999 
4000 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4001   // If this is a fixed sized alloca in the entry block of the function,
4002   // allocate it statically on the stack.
4003   if (FuncInfo.StaticAllocaMap.count(&I))
4004     return;   // getValue will auto-populate this.
4005 
4006   SDLoc dl = getCurSDLoc();
4007   Type *Ty = I.getAllocatedType();
4008   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4009   auto &DL = DAG.getDataLayout();
4010   uint64_t TySize = DL.getTypeAllocSize(Ty);
4011   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4012 
4013   SDValue AllocSize = getValue(I.getArraySize());
4014 
4015   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4016   if (AllocSize.getValueType() != IntPtr)
4017     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4018 
4019   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4020                           AllocSize,
4021                           DAG.getConstant(TySize, dl, IntPtr));
4022 
4023   // Handle alignment.  If the requested alignment is less than or equal to
4024   // the stack alignment, ignore it.  If the size is greater than or equal to
4025   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4026   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4027   if (*Alignment <= StackAlign)
4028     Alignment = None;
4029 
4030   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4031   // Round the size of the allocation up to the stack alignment size
4032   // by add SA-1 to the size. This doesn't overflow because we're computing
4033   // an address inside an alloca.
4034   SDNodeFlags Flags;
4035   Flags.setNoUnsignedWrap(true);
4036   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4037                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4038 
4039   // Mask out the low bits for alignment purposes.
4040   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4041                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4042 
4043   SDValue Ops[] = {
4044       getRoot(), AllocSize,
4045       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4046   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4047   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4048   setValue(&I, DSA);
4049   DAG.setRoot(DSA.getValue(1));
4050 
4051   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4052 }
4053 
4054 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4055   if (I.isAtomic())
4056     return visitAtomicLoad(I);
4057 
4058   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4059   const Value *SV = I.getOperand(0);
4060   if (TLI.supportSwiftError()) {
4061     // Swifterror values can come from either a function parameter with
4062     // swifterror attribute or an alloca with swifterror attribute.
4063     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4064       if (Arg->hasSwiftErrorAttr())
4065         return visitLoadFromSwiftError(I);
4066     }
4067 
4068     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4069       if (Alloca->isSwiftError())
4070         return visitLoadFromSwiftError(I);
4071     }
4072   }
4073 
4074   SDValue Ptr = getValue(SV);
4075 
4076   Type *Ty = I.getType();
4077   Align Alignment = I.getAlign();
4078 
4079   AAMDNodes AAInfo = I.getAAMetadata();
4080   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4081 
4082   SmallVector<EVT, 4> ValueVTs, MemVTs;
4083   SmallVector<uint64_t, 4> Offsets;
4084   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4085   unsigned NumValues = ValueVTs.size();
4086   if (NumValues == 0)
4087     return;
4088 
4089   bool isVolatile = I.isVolatile();
4090 
4091   SDValue Root;
4092   bool ConstantMemory = false;
4093   if (isVolatile)
4094     // Serialize volatile loads with other side effects.
4095     Root = getRoot();
4096   else if (NumValues > MaxParallelChains)
4097     Root = getMemoryRoot();
4098   else if (AA &&
4099            AA->pointsToConstantMemory(MemoryLocation(
4100                SV,
4101                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4102                AAInfo))) {
4103     // Do not serialize (non-volatile) loads of constant memory with anything.
4104     Root = DAG.getEntryNode();
4105     ConstantMemory = true;
4106   } else {
4107     // Do not serialize non-volatile loads against each other.
4108     Root = DAG.getRoot();
4109   }
4110 
4111   SDLoc dl = getCurSDLoc();
4112 
4113   if (isVolatile)
4114     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4115 
4116   // An aggregate load cannot wrap around the address space, so offsets to its
4117   // parts don't wrap either.
4118   SDNodeFlags Flags;
4119   Flags.setNoUnsignedWrap(true);
4120 
4121   SmallVector<SDValue, 4> Values(NumValues);
4122   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4123   EVT PtrVT = Ptr.getValueType();
4124 
4125   MachineMemOperand::Flags MMOFlags
4126     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4127 
4128   unsigned ChainI = 0;
4129   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4130     // Serializing loads here may result in excessive register pressure, and
4131     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4132     // could recover a bit by hoisting nodes upward in the chain by recognizing
4133     // they are side-effect free or do not alias. The optimizer should really
4134     // avoid this case by converting large object/array copies to llvm.memcpy
4135     // (MaxParallelChains should always remain as failsafe).
4136     if (ChainI == MaxParallelChains) {
4137       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4138       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4139                                   makeArrayRef(Chains.data(), ChainI));
4140       Root = Chain;
4141       ChainI = 0;
4142     }
4143     SDValue A = DAG.getNode(ISD::ADD, dl,
4144                             PtrVT, Ptr,
4145                             DAG.getConstant(Offsets[i], dl, PtrVT),
4146                             Flags);
4147 
4148     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4149                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4150                             MMOFlags, AAInfo, Ranges);
4151     Chains[ChainI] = L.getValue(1);
4152 
4153     if (MemVTs[i] != ValueVTs[i])
4154       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4155 
4156     Values[i] = L;
4157   }
4158 
4159   if (!ConstantMemory) {
4160     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4161                                 makeArrayRef(Chains.data(), ChainI));
4162     if (isVolatile)
4163       DAG.setRoot(Chain);
4164     else
4165       PendingLoads.push_back(Chain);
4166   }
4167 
4168   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4169                            DAG.getVTList(ValueVTs), Values));
4170 }
4171 
4172 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4173   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4174          "call visitStoreToSwiftError when backend supports swifterror");
4175 
4176   SmallVector<EVT, 4> ValueVTs;
4177   SmallVector<uint64_t, 4> Offsets;
4178   const Value *SrcV = I.getOperand(0);
4179   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4180                   SrcV->getType(), ValueVTs, &Offsets);
4181   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4182          "expect a single EVT for swifterror");
4183 
4184   SDValue Src = getValue(SrcV);
4185   // Create a virtual register, then update the virtual register.
4186   Register VReg =
4187       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4188   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4189   // Chain can be getRoot or getControlRoot.
4190   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4191                                       SDValue(Src.getNode(), Src.getResNo()));
4192   DAG.setRoot(CopyNode);
4193 }
4194 
4195 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4196   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4197          "call visitLoadFromSwiftError when backend supports swifterror");
4198 
4199   assert(!I.isVolatile() &&
4200          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4201          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4202          "Support volatile, non temporal, invariant for load_from_swift_error");
4203 
4204   const Value *SV = I.getOperand(0);
4205   Type *Ty = I.getType();
4206   assert(
4207       (!AA ||
4208        !AA->pointsToConstantMemory(MemoryLocation(
4209            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4210            I.getAAMetadata()))) &&
4211       "load_from_swift_error should not be constant memory");
4212 
4213   SmallVector<EVT, 4> ValueVTs;
4214   SmallVector<uint64_t, 4> Offsets;
4215   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4216                   ValueVTs, &Offsets);
4217   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4218          "expect a single EVT for swifterror");
4219 
4220   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4221   SDValue L = DAG.getCopyFromReg(
4222       getRoot(), getCurSDLoc(),
4223       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4224 
4225   setValue(&I, L);
4226 }
4227 
4228 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4229   if (I.isAtomic())
4230     return visitAtomicStore(I);
4231 
4232   const Value *SrcV = I.getOperand(0);
4233   const Value *PtrV = I.getOperand(1);
4234 
4235   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4236   if (TLI.supportSwiftError()) {
4237     // Swifterror values can come from either a function parameter with
4238     // swifterror attribute or an alloca with swifterror attribute.
4239     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4240       if (Arg->hasSwiftErrorAttr())
4241         return visitStoreToSwiftError(I);
4242     }
4243 
4244     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4245       if (Alloca->isSwiftError())
4246         return visitStoreToSwiftError(I);
4247     }
4248   }
4249 
4250   SmallVector<EVT, 4> ValueVTs, MemVTs;
4251   SmallVector<uint64_t, 4> Offsets;
4252   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4253                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4254   unsigned NumValues = ValueVTs.size();
4255   if (NumValues == 0)
4256     return;
4257 
4258   // Get the lowered operands. Note that we do this after
4259   // checking if NumResults is zero, because with zero results
4260   // the operands won't have values in the map.
4261   SDValue Src = getValue(SrcV);
4262   SDValue Ptr = getValue(PtrV);
4263 
4264   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4265   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4266   SDLoc dl = getCurSDLoc();
4267   Align Alignment = I.getAlign();
4268   AAMDNodes AAInfo = I.getAAMetadata();
4269 
4270   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4271 
4272   // An aggregate load cannot wrap around the address space, so offsets to its
4273   // parts don't wrap either.
4274   SDNodeFlags Flags;
4275   Flags.setNoUnsignedWrap(true);
4276 
4277   unsigned ChainI = 0;
4278   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4279     // See visitLoad comments.
4280     if (ChainI == MaxParallelChains) {
4281       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4282                                   makeArrayRef(Chains.data(), ChainI));
4283       Root = Chain;
4284       ChainI = 0;
4285     }
4286     SDValue Add =
4287         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4288     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4289     if (MemVTs[i] != ValueVTs[i])
4290       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4291     SDValue St =
4292         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4293                      Alignment, MMOFlags, AAInfo);
4294     Chains[ChainI] = St;
4295   }
4296 
4297   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4298                                   makeArrayRef(Chains.data(), ChainI));
4299   DAG.setRoot(StoreNode);
4300 }
4301 
4302 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4303                                            bool IsCompressing) {
4304   SDLoc sdl = getCurSDLoc();
4305 
4306   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4307                                MaybeAlign &Alignment) {
4308     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4309     Src0 = I.getArgOperand(0);
4310     Ptr = I.getArgOperand(1);
4311     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4312     Mask = I.getArgOperand(3);
4313   };
4314   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4315                                     MaybeAlign &Alignment) {
4316     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4317     Src0 = I.getArgOperand(0);
4318     Ptr = I.getArgOperand(1);
4319     Mask = I.getArgOperand(2);
4320     Alignment = None;
4321   };
4322 
4323   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4324   MaybeAlign Alignment;
4325   if (IsCompressing)
4326     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4327   else
4328     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4329 
4330   SDValue Ptr = getValue(PtrOperand);
4331   SDValue Src0 = getValue(Src0Operand);
4332   SDValue Mask = getValue(MaskOperand);
4333   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4334 
4335   EVT VT = Src0.getValueType();
4336   if (!Alignment)
4337     Alignment = DAG.getEVTAlign(VT);
4338 
4339   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4340       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4341       MemoryLocation::UnknownSize, *Alignment, I.getAAMetadata());
4342   SDValue StoreNode =
4343       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4344                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4345   DAG.setRoot(StoreNode);
4346   setValue(&I, StoreNode);
4347 }
4348 
4349 // Get a uniform base for the Gather/Scatter intrinsic.
4350 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4351 // We try to represent it as a base pointer + vector of indices.
4352 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4353 // The first operand of the GEP may be a single pointer or a vector of pointers
4354 // Example:
4355 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4356 //  or
4357 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4358 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4359 //
4360 // When the first GEP operand is a single pointer - it is the uniform base we
4361 // are looking for. If first operand of the GEP is a splat vector - we
4362 // extract the splat value and use it as a uniform base.
4363 // In all other cases the function returns 'false'.
4364 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4365                            ISD::MemIndexType &IndexType, SDValue &Scale,
4366                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4367   SelectionDAG& DAG = SDB->DAG;
4368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4369   const DataLayout &DL = DAG.getDataLayout();
4370 
4371   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4372 
4373   // Handle splat constant pointer.
4374   if (auto *C = dyn_cast<Constant>(Ptr)) {
4375     C = C->getSplatValue();
4376     if (!C)
4377       return false;
4378 
4379     Base = SDB->getValue(C);
4380 
4381     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4382     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4383     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4384     IndexType = ISD::SIGNED_SCALED;
4385     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4386     return true;
4387   }
4388 
4389   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4390   if (!GEP || GEP->getParent() != CurBB)
4391     return false;
4392 
4393   if (GEP->getNumOperands() != 2)
4394     return false;
4395 
4396   const Value *BasePtr = GEP->getPointerOperand();
4397   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4398 
4399   // Make sure the base is scalar and the index is a vector.
4400   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4401     return false;
4402 
4403   Base = SDB->getValue(BasePtr);
4404   Index = SDB->getValue(IndexVal);
4405   IndexType = ISD::SIGNED_SCALED;
4406   Scale = DAG.getTargetConstant(
4407               DL.getTypeAllocSize(GEP->getResultElementType()),
4408               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4409   return true;
4410 }
4411 
4412 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4413   SDLoc sdl = getCurSDLoc();
4414 
4415   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4416   const Value *Ptr = I.getArgOperand(1);
4417   SDValue Src0 = getValue(I.getArgOperand(0));
4418   SDValue Mask = getValue(I.getArgOperand(3));
4419   EVT VT = Src0.getValueType();
4420   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4421                         ->getMaybeAlignValue()
4422                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4423   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4424 
4425   SDValue Base;
4426   SDValue Index;
4427   ISD::MemIndexType IndexType;
4428   SDValue Scale;
4429   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4430                                     I.getParent());
4431 
4432   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4433   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4434       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4435       // TODO: Make MachineMemOperands aware of scalable
4436       // vectors.
4437       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata());
4438   if (!UniformBase) {
4439     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4440     Index = getValue(Ptr);
4441     IndexType = ISD::SIGNED_UNSCALED;
4442     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4443   }
4444 
4445   EVT IdxVT = Index.getValueType();
4446   EVT EltTy = IdxVT.getVectorElementType();
4447   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4448     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4449     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4450   }
4451 
4452   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4453   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4454                                          Ops, MMO, IndexType, false);
4455   DAG.setRoot(Scatter);
4456   setValue(&I, Scatter);
4457 }
4458 
4459 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4460   SDLoc sdl = getCurSDLoc();
4461 
4462   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4463                               MaybeAlign &Alignment) {
4464     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4465     Ptr = I.getArgOperand(0);
4466     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4467     Mask = I.getArgOperand(2);
4468     Src0 = I.getArgOperand(3);
4469   };
4470   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4471                                  MaybeAlign &Alignment) {
4472     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4473     Ptr = I.getArgOperand(0);
4474     Alignment = None;
4475     Mask = I.getArgOperand(1);
4476     Src0 = I.getArgOperand(2);
4477   };
4478 
4479   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4480   MaybeAlign Alignment;
4481   if (IsExpanding)
4482     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4483   else
4484     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4485 
4486   SDValue Ptr = getValue(PtrOperand);
4487   SDValue Src0 = getValue(Src0Operand);
4488   SDValue Mask = getValue(MaskOperand);
4489   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4490 
4491   EVT VT = Src0.getValueType();
4492   if (!Alignment)
4493     Alignment = DAG.getEVTAlign(VT);
4494 
4495   AAMDNodes AAInfo = I.getAAMetadata();
4496   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4497 
4498   // Do not serialize masked loads of constant memory with anything.
4499   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4500   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4501 
4502   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4503 
4504   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4505       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4506       MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
4507 
4508   SDValue Load =
4509       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4510                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4511   if (AddToChain)
4512     PendingLoads.push_back(Load.getValue(1));
4513   setValue(&I, Load);
4514 }
4515 
4516 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4517   SDLoc sdl = getCurSDLoc();
4518 
4519   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4520   const Value *Ptr = I.getArgOperand(0);
4521   SDValue Src0 = getValue(I.getArgOperand(3));
4522   SDValue Mask = getValue(I.getArgOperand(2));
4523 
4524   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4525   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4526   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4527                         ->getMaybeAlignValue()
4528                         .getValueOr(DAG.getEVTAlign(VT.getScalarType()));
4529 
4530   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4531 
4532   SDValue Root = DAG.getRoot();
4533   SDValue Base;
4534   SDValue Index;
4535   ISD::MemIndexType IndexType;
4536   SDValue Scale;
4537   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4538                                     I.getParent());
4539   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4540   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4541       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4542       // TODO: Make MachineMemOperands aware of scalable
4543       // vectors.
4544       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
4545 
4546   if (!UniformBase) {
4547     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4548     Index = getValue(Ptr);
4549     IndexType = ISD::SIGNED_UNSCALED;
4550     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4551   }
4552 
4553   EVT IdxVT = Index.getValueType();
4554   EVT EltTy = IdxVT.getVectorElementType();
4555   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4556     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4557     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4558   }
4559 
4560   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4561   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4562                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4563 
4564   PendingLoads.push_back(Gather.getValue(1));
4565   setValue(&I, Gather);
4566 }
4567 
4568 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4569   SDLoc dl = getCurSDLoc();
4570   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4571   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4572   SyncScope::ID SSID = I.getSyncScopeID();
4573 
4574   SDValue InChain = getRoot();
4575 
4576   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4577   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4578 
4579   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4580   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4581 
4582   MachineFunction &MF = DAG.getMachineFunction();
4583   MachineMemOperand *MMO = MF.getMachineMemOperand(
4584       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4585       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4586       FailureOrdering);
4587 
4588   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4589                                    dl, MemVT, VTs, InChain,
4590                                    getValue(I.getPointerOperand()),
4591                                    getValue(I.getCompareOperand()),
4592                                    getValue(I.getNewValOperand()), MMO);
4593 
4594   SDValue OutChain = L.getValue(2);
4595 
4596   setValue(&I, L);
4597   DAG.setRoot(OutChain);
4598 }
4599 
4600 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4601   SDLoc dl = getCurSDLoc();
4602   ISD::NodeType NT;
4603   switch (I.getOperation()) {
4604   default: llvm_unreachable("Unknown atomicrmw operation");
4605   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4606   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4607   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4608   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4609   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4610   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4611   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4612   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4613   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4614   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4615   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4616   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4617   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4618   }
4619   AtomicOrdering Ordering = I.getOrdering();
4620   SyncScope::ID SSID = I.getSyncScopeID();
4621 
4622   SDValue InChain = getRoot();
4623 
4624   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4625   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4626   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4627 
4628   MachineFunction &MF = DAG.getMachineFunction();
4629   MachineMemOperand *MMO = MF.getMachineMemOperand(
4630       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4631       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4632 
4633   SDValue L =
4634     DAG.getAtomic(NT, dl, MemVT, InChain,
4635                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4636                   MMO);
4637 
4638   SDValue OutChain = L.getValue(1);
4639 
4640   setValue(&I, L);
4641   DAG.setRoot(OutChain);
4642 }
4643 
4644 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4645   SDLoc dl = getCurSDLoc();
4646   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4647   SDValue Ops[3];
4648   Ops[0] = getRoot();
4649   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4650                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4651   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4652                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4653   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4654 }
4655 
4656 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4657   SDLoc dl = getCurSDLoc();
4658   AtomicOrdering Order = I.getOrdering();
4659   SyncScope::ID SSID = I.getSyncScopeID();
4660 
4661   SDValue InChain = getRoot();
4662 
4663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4664   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4665   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4666 
4667   if (!TLI.supportsUnalignedAtomics() &&
4668       I.getAlignment() < MemVT.getSizeInBits() / 8)
4669     report_fatal_error("Cannot generate unaligned atomic load");
4670 
4671   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4672 
4673   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4674       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4675       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4676 
4677   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4678 
4679   SDValue Ptr = getValue(I.getPointerOperand());
4680 
4681   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4682     // TODO: Once this is better exercised by tests, it should be merged with
4683     // the normal path for loads to prevent future divergence.
4684     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4685     if (MemVT != VT)
4686       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4687 
4688     setValue(&I, L);
4689     SDValue OutChain = L.getValue(1);
4690     if (!I.isUnordered())
4691       DAG.setRoot(OutChain);
4692     else
4693       PendingLoads.push_back(OutChain);
4694     return;
4695   }
4696 
4697   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4698                             Ptr, MMO);
4699 
4700   SDValue OutChain = L.getValue(1);
4701   if (MemVT != VT)
4702     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4703 
4704   setValue(&I, L);
4705   DAG.setRoot(OutChain);
4706 }
4707 
4708 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4709   SDLoc dl = getCurSDLoc();
4710 
4711   AtomicOrdering Ordering = I.getOrdering();
4712   SyncScope::ID SSID = I.getSyncScopeID();
4713 
4714   SDValue InChain = getRoot();
4715 
4716   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4717   EVT MemVT =
4718       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4719 
4720   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4721     report_fatal_error("Cannot generate unaligned atomic store");
4722 
4723   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4724 
4725   MachineFunction &MF = DAG.getMachineFunction();
4726   MachineMemOperand *MMO = MF.getMachineMemOperand(
4727       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4728       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4729 
4730   SDValue Val = getValue(I.getValueOperand());
4731   if (Val.getValueType() != MemVT)
4732     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4733   SDValue Ptr = getValue(I.getPointerOperand());
4734 
4735   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4736     // TODO: Once this is better exercised by tests, it should be merged with
4737     // the normal path for stores to prevent future divergence.
4738     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4739     DAG.setRoot(S);
4740     return;
4741   }
4742   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4743                                    Ptr, Val, MMO);
4744 
4745 
4746   DAG.setRoot(OutChain);
4747 }
4748 
4749 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4750 /// node.
4751 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4752                                                unsigned Intrinsic) {
4753   // Ignore the callsite's attributes. A specific call site may be marked with
4754   // readnone, but the lowering code will expect the chain based on the
4755   // definition.
4756   const Function *F = I.getCalledFunction();
4757   bool HasChain = !F->doesNotAccessMemory();
4758   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4759 
4760   // Build the operand list.
4761   SmallVector<SDValue, 8> Ops;
4762   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4763     if (OnlyLoad) {
4764       // We don't need to serialize loads against other loads.
4765       Ops.push_back(DAG.getRoot());
4766     } else {
4767       Ops.push_back(getRoot());
4768     }
4769   }
4770 
4771   // Info is set by getTgtMemInstrinsic
4772   TargetLowering::IntrinsicInfo Info;
4773   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4774   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4775                                                DAG.getMachineFunction(),
4776                                                Intrinsic);
4777 
4778   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4779   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4780       Info.opc == ISD::INTRINSIC_W_CHAIN)
4781     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4782                                         TLI.getPointerTy(DAG.getDataLayout())));
4783 
4784   // Add all operands of the call to the operand list.
4785   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
4786     const Value *Arg = I.getArgOperand(i);
4787     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4788       Ops.push_back(getValue(Arg));
4789       continue;
4790     }
4791 
4792     // Use TargetConstant instead of a regular constant for immarg.
4793     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
4794     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4795       assert(CI->getBitWidth() <= 64 &&
4796              "large intrinsic immediates not handled");
4797       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4798     } else {
4799       Ops.push_back(
4800           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4801     }
4802   }
4803 
4804   SmallVector<EVT, 4> ValueVTs;
4805   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4806 
4807   if (HasChain)
4808     ValueVTs.push_back(MVT::Other);
4809 
4810   SDVTList VTs = DAG.getVTList(ValueVTs);
4811 
4812   // Propagate fast-math-flags from IR to node(s).
4813   SDNodeFlags Flags;
4814   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
4815     Flags.copyFMF(*FPMO);
4816   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
4817 
4818   // Create the node.
4819   SDValue Result;
4820   if (IsTgtIntrinsic) {
4821     // This is target intrinsic that touches memory
4822     Result =
4823         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4824                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4825                                 Info.align, Info.flags, Info.size,
4826                                 I.getAAMetadata());
4827   } else if (!HasChain) {
4828     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4829   } else if (!I.getType()->isVoidTy()) {
4830     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4831   } else {
4832     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4833   }
4834 
4835   if (HasChain) {
4836     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4837     if (OnlyLoad)
4838       PendingLoads.push_back(Chain);
4839     else
4840       DAG.setRoot(Chain);
4841   }
4842 
4843   if (!I.getType()->isVoidTy()) {
4844     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4845       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4846       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4847     } else
4848       Result = lowerRangeToAssertZExt(DAG, I, Result);
4849 
4850     MaybeAlign Alignment = I.getRetAlign();
4851     if (!Alignment)
4852       Alignment = F->getAttributes().getRetAlignment();
4853     // Insert `assertalign` node if there's an alignment.
4854     if (InsertAssertAlign && Alignment) {
4855       Result =
4856           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4857     }
4858 
4859     setValue(&I, Result);
4860   }
4861 }
4862 
4863 /// GetSignificand - Get the significand and build it into a floating-point
4864 /// number with exponent of 1:
4865 ///
4866 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4867 ///
4868 /// where Op is the hexadecimal representation of floating point value.
4869 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4870   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4871                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4872   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4873                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4874   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4875 }
4876 
4877 /// GetExponent - Get the exponent:
4878 ///
4879 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4880 ///
4881 /// where Op is the hexadecimal representation of floating point value.
4882 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4883                            const TargetLowering &TLI, const SDLoc &dl) {
4884   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4885                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4886   SDValue t1 = DAG.getNode(
4887       ISD::SRL, dl, MVT::i32, t0,
4888       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4889   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4890                            DAG.getConstant(127, dl, MVT::i32));
4891   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4892 }
4893 
4894 /// getF32Constant - Get 32-bit floating point constant.
4895 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4896                               const SDLoc &dl) {
4897   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4898                            MVT::f32);
4899 }
4900 
4901 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4902                                        SelectionDAG &DAG) {
4903   // TODO: What fast-math-flags should be set on the floating-point nodes?
4904 
4905   //   IntegerPartOfX = ((int32_t)(t0);
4906   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4907 
4908   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4909   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4910   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4911 
4912   //   IntegerPartOfX <<= 23;
4913   IntegerPartOfX = DAG.getNode(
4914       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4915       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4916                                   DAG.getDataLayout())));
4917 
4918   SDValue TwoToFractionalPartOfX;
4919   if (LimitFloatPrecision <= 6) {
4920     // For floating-point precision of 6:
4921     //
4922     //   TwoToFractionalPartOfX =
4923     //     0.997535578f +
4924     //       (0.735607626f + 0.252464424f * x) * x;
4925     //
4926     // error 0.0144103317, which is 6 bits
4927     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4928                              getF32Constant(DAG, 0x3e814304, dl));
4929     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4930                              getF32Constant(DAG, 0x3f3c50c8, dl));
4931     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4932     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4933                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4934   } else if (LimitFloatPrecision <= 12) {
4935     // For floating-point precision of 12:
4936     //
4937     //   TwoToFractionalPartOfX =
4938     //     0.999892986f +
4939     //       (0.696457318f +
4940     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4941     //
4942     // error 0.000107046256, which is 13 to 14 bits
4943     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4944                              getF32Constant(DAG, 0x3da235e3, dl));
4945     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4946                              getF32Constant(DAG, 0x3e65b8f3, dl));
4947     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4948     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4949                              getF32Constant(DAG, 0x3f324b07, dl));
4950     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4951     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4952                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4953   } else { // LimitFloatPrecision <= 18
4954     // For floating-point precision of 18:
4955     //
4956     //   TwoToFractionalPartOfX =
4957     //     0.999999982f +
4958     //       (0.693148872f +
4959     //         (0.240227044f +
4960     //           (0.554906021e-1f +
4961     //             (0.961591928e-2f +
4962     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4963     // error 2.47208000*10^(-7), which is better than 18 bits
4964     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4965                              getF32Constant(DAG, 0x3924b03e, dl));
4966     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4967                              getF32Constant(DAG, 0x3ab24b87, dl));
4968     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4969     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4970                              getF32Constant(DAG, 0x3c1d8c17, dl));
4971     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4972     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4973                              getF32Constant(DAG, 0x3d634a1d, dl));
4974     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4975     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4976                              getF32Constant(DAG, 0x3e75fe14, dl));
4977     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4978     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4979                               getF32Constant(DAG, 0x3f317234, dl));
4980     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4981     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4982                                          getF32Constant(DAG, 0x3f800000, dl));
4983   }
4984 
4985   // Add the exponent into the result in integer domain.
4986   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4987   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4988                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4989 }
4990 
4991 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4992 /// limited-precision mode.
4993 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4994                          const TargetLowering &TLI, SDNodeFlags Flags) {
4995   if (Op.getValueType() == MVT::f32 &&
4996       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4997 
4998     // Put the exponent in the right bit position for later addition to the
4999     // final result:
5000     //
5001     // t0 = Op * log2(e)
5002 
5003     // TODO: What fast-math-flags should be set here?
5004     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5005                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5006     return getLimitedPrecisionExp2(t0, dl, DAG);
5007   }
5008 
5009   // No special expansion.
5010   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5011 }
5012 
5013 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5014 /// limited-precision mode.
5015 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5016                          const TargetLowering &TLI, SDNodeFlags Flags) {
5017   // TODO: What fast-math-flags should be set on the floating-point nodes?
5018 
5019   if (Op.getValueType() == MVT::f32 &&
5020       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5021     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5022 
5023     // Scale the exponent by log(2).
5024     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5025     SDValue LogOfExponent =
5026         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5027                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5028 
5029     // Get the significand and build it into a floating-point number with
5030     // exponent of 1.
5031     SDValue X = GetSignificand(DAG, Op1, dl);
5032 
5033     SDValue LogOfMantissa;
5034     if (LimitFloatPrecision <= 6) {
5035       // For floating-point precision of 6:
5036       //
5037       //   LogofMantissa =
5038       //     -1.1609546f +
5039       //       (1.4034025f - 0.23903021f * x) * x;
5040       //
5041       // error 0.0034276066, which is better than 8 bits
5042       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5043                                getF32Constant(DAG, 0xbe74c456, dl));
5044       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5045                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5046       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5047       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5048                                   getF32Constant(DAG, 0x3f949a29, dl));
5049     } else if (LimitFloatPrecision <= 12) {
5050       // For floating-point precision of 12:
5051       //
5052       //   LogOfMantissa =
5053       //     -1.7417939f +
5054       //       (2.8212026f +
5055       //         (-1.4699568f +
5056       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5057       //
5058       // error 0.000061011436, which is 14 bits
5059       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5060                                getF32Constant(DAG, 0xbd67b6d6, dl));
5061       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5062                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5063       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5064       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5065                                getF32Constant(DAG, 0x3fbc278b, dl));
5066       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5067       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5068                                getF32Constant(DAG, 0x40348e95, dl));
5069       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5070       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5071                                   getF32Constant(DAG, 0x3fdef31a, dl));
5072     } else { // LimitFloatPrecision <= 18
5073       // For floating-point precision of 18:
5074       //
5075       //   LogOfMantissa =
5076       //     -2.1072184f +
5077       //       (4.2372794f +
5078       //         (-3.7029485f +
5079       //           (2.2781945f +
5080       //             (-0.87823314f +
5081       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5082       //
5083       // error 0.0000023660568, which is better than 18 bits
5084       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5085                                getF32Constant(DAG, 0xbc91e5ac, dl));
5086       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5087                                getF32Constant(DAG, 0x3e4350aa, dl));
5088       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5089       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5090                                getF32Constant(DAG, 0x3f60d3e3, dl));
5091       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5092       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5093                                getF32Constant(DAG, 0x4011cdf0, dl));
5094       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5095       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5096                                getF32Constant(DAG, 0x406cfd1c, dl));
5097       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5098       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5099                                getF32Constant(DAG, 0x408797cb, dl));
5100       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5101       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5102                                   getF32Constant(DAG, 0x4006dcab, dl));
5103     }
5104 
5105     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5106   }
5107 
5108   // No special expansion.
5109   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5110 }
5111 
5112 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5113 /// limited-precision mode.
5114 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5115                           const TargetLowering &TLI, SDNodeFlags Flags) {
5116   // TODO: What fast-math-flags should be set on the floating-point nodes?
5117 
5118   if (Op.getValueType() == MVT::f32 &&
5119       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5120     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5121 
5122     // Get the exponent.
5123     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5124 
5125     // Get the significand and build it into a floating-point number with
5126     // exponent of 1.
5127     SDValue X = GetSignificand(DAG, Op1, dl);
5128 
5129     // Different possible minimax approximations of significand in
5130     // floating-point for various degrees of accuracy over [1,2].
5131     SDValue Log2ofMantissa;
5132     if (LimitFloatPrecision <= 6) {
5133       // For floating-point precision of 6:
5134       //
5135       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5136       //
5137       // error 0.0049451742, which is more than 7 bits
5138       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5139                                getF32Constant(DAG, 0xbeb08fe0, dl));
5140       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5141                                getF32Constant(DAG, 0x40019463, dl));
5142       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5143       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5144                                    getF32Constant(DAG, 0x3fd6633d, dl));
5145     } else if (LimitFloatPrecision <= 12) {
5146       // For floating-point precision of 12:
5147       //
5148       //   Log2ofMantissa =
5149       //     -2.51285454f +
5150       //       (4.07009056f +
5151       //         (-2.12067489f +
5152       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5153       //
5154       // error 0.0000876136000, which is better than 13 bits
5155       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5156                                getF32Constant(DAG, 0xbda7262e, dl));
5157       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5158                                getF32Constant(DAG, 0x3f25280b, dl));
5159       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5160       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5161                                getF32Constant(DAG, 0x4007b923, dl));
5162       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5163       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5164                                getF32Constant(DAG, 0x40823e2f, dl));
5165       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5166       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5167                                    getF32Constant(DAG, 0x4020d29c, dl));
5168     } else { // LimitFloatPrecision <= 18
5169       // For floating-point precision of 18:
5170       //
5171       //   Log2ofMantissa =
5172       //     -3.0400495f +
5173       //       (6.1129976f +
5174       //         (-5.3420409f +
5175       //           (3.2865683f +
5176       //             (-1.2669343f +
5177       //               (0.27515199f -
5178       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5179       //
5180       // error 0.0000018516, which is better than 18 bits
5181       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5182                                getF32Constant(DAG, 0xbcd2769e, dl));
5183       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5184                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5185       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5186       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5187                                getF32Constant(DAG, 0x3fa22ae7, dl));
5188       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5189       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5190                                getF32Constant(DAG, 0x40525723, dl));
5191       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5192       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5193                                getF32Constant(DAG, 0x40aaf200, dl));
5194       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5195       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5196                                getF32Constant(DAG, 0x40c39dad, dl));
5197       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5198       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5199                                    getF32Constant(DAG, 0x4042902c, dl));
5200     }
5201 
5202     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5203   }
5204 
5205   // No special expansion.
5206   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5207 }
5208 
5209 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5210 /// limited-precision mode.
5211 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5212                            const TargetLowering &TLI, SDNodeFlags Flags) {
5213   // TODO: What fast-math-flags should be set on the floating-point nodes?
5214 
5215   if (Op.getValueType() == MVT::f32 &&
5216       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5217     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5218 
5219     // Scale the exponent by log10(2) [0.30102999f].
5220     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5221     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5222                                         getF32Constant(DAG, 0x3e9a209a, dl));
5223 
5224     // Get the significand and build it into a floating-point number with
5225     // exponent of 1.
5226     SDValue X = GetSignificand(DAG, Op1, dl);
5227 
5228     SDValue Log10ofMantissa;
5229     if (LimitFloatPrecision <= 6) {
5230       // For floating-point precision of 6:
5231       //
5232       //   Log10ofMantissa =
5233       //     -0.50419619f +
5234       //       (0.60948995f - 0.10380950f * x) * x;
5235       //
5236       // error 0.0014886165, which is 6 bits
5237       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5238                                getF32Constant(DAG, 0xbdd49a13, dl));
5239       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5240                                getF32Constant(DAG, 0x3f1c0789, dl));
5241       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5242       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5243                                     getF32Constant(DAG, 0x3f011300, dl));
5244     } else if (LimitFloatPrecision <= 12) {
5245       // For floating-point precision of 12:
5246       //
5247       //   Log10ofMantissa =
5248       //     -0.64831180f +
5249       //       (0.91751397f +
5250       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5251       //
5252       // error 0.00019228036, which is better than 12 bits
5253       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5254                                getF32Constant(DAG, 0x3d431f31, dl));
5255       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5256                                getF32Constant(DAG, 0x3ea21fb2, dl));
5257       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5258       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5259                                getF32Constant(DAG, 0x3f6ae232, dl));
5260       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5261       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5262                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5263     } else { // LimitFloatPrecision <= 18
5264       // For floating-point precision of 18:
5265       //
5266       //   Log10ofMantissa =
5267       //     -0.84299375f +
5268       //       (1.5327582f +
5269       //         (-1.0688956f +
5270       //           (0.49102474f +
5271       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5272       //
5273       // error 0.0000037995730, which is better than 18 bits
5274       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5275                                getF32Constant(DAG, 0x3c5d51ce, dl));
5276       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5277                                getF32Constant(DAG, 0x3e00685a, dl));
5278       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5279       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5280                                getF32Constant(DAG, 0x3efb6798, dl));
5281       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5282       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5283                                getF32Constant(DAG, 0x3f88d192, dl));
5284       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5285       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5286                                getF32Constant(DAG, 0x3fc4316c, dl));
5287       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5288       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5289                                     getF32Constant(DAG, 0x3f57ce70, dl));
5290     }
5291 
5292     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5293   }
5294 
5295   // No special expansion.
5296   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5297 }
5298 
5299 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5300 /// limited-precision mode.
5301 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5302                           const TargetLowering &TLI, SDNodeFlags Flags) {
5303   if (Op.getValueType() == MVT::f32 &&
5304       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5305     return getLimitedPrecisionExp2(Op, dl, DAG);
5306 
5307   // No special expansion.
5308   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5309 }
5310 
5311 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5312 /// limited-precision mode with x == 10.0f.
5313 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5314                          SelectionDAG &DAG, const TargetLowering &TLI,
5315                          SDNodeFlags Flags) {
5316   bool IsExp10 = false;
5317   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5318       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5319     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5320       APFloat Ten(10.0f);
5321       IsExp10 = LHSC->isExactlyValue(Ten);
5322     }
5323   }
5324 
5325   // TODO: What fast-math-flags should be set on the FMUL node?
5326   if (IsExp10) {
5327     // Put the exponent in the right bit position for later addition to the
5328     // final result:
5329     //
5330     //   #define LOG2OF10 3.3219281f
5331     //   t0 = Op * LOG2OF10;
5332     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5333                              getF32Constant(DAG, 0x40549a78, dl));
5334     return getLimitedPrecisionExp2(t0, dl, DAG);
5335   }
5336 
5337   // No special expansion.
5338   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5339 }
5340 
5341 /// ExpandPowI - Expand a llvm.powi intrinsic.
5342 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5343                           SelectionDAG &DAG) {
5344   // If RHS is a constant, we can expand this out to a multiplication tree,
5345   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5346   // optimizing for size, we only want to do this if the expansion would produce
5347   // a small number of multiplies, otherwise we do the full expansion.
5348   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5349     // Get the exponent as a positive value.
5350     unsigned Val = RHSC->getSExtValue();
5351     if ((int)Val < 0) Val = -Val;
5352 
5353     // powi(x, 0) -> 1.0
5354     if (Val == 0)
5355       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5356 
5357     bool OptForSize = DAG.shouldOptForSize();
5358     if (!OptForSize ||
5359         // If optimizing for size, don't insert too many multiplies.
5360         // This inserts up to 5 multiplies.
5361         countPopulation(Val) + Log2_32(Val) < 7) {
5362       // We use the simple binary decomposition method to generate the multiply
5363       // sequence.  There are more optimal ways to do this (for example,
5364       // powi(x,15) generates one more multiply than it should), but this has
5365       // the benefit of being both really simple and much better than a libcall.
5366       SDValue Res;  // Logically starts equal to 1.0
5367       SDValue CurSquare = LHS;
5368       // TODO: Intrinsics should have fast-math-flags that propagate to these
5369       // nodes.
5370       while (Val) {
5371         if (Val & 1) {
5372           if (Res.getNode())
5373             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5374           else
5375             Res = CurSquare;  // 1.0*CurSquare.
5376         }
5377 
5378         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5379                                 CurSquare, CurSquare);
5380         Val >>= 1;
5381       }
5382 
5383       // If the original was negative, invert the result, producing 1/(x*x*x).
5384       if (RHSC->getSExtValue() < 0)
5385         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5386                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5387       return Res;
5388     }
5389   }
5390 
5391   // Otherwise, expand to a libcall.
5392   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5393 }
5394 
5395 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5396                             SDValue LHS, SDValue RHS, SDValue Scale,
5397                             SelectionDAG &DAG, const TargetLowering &TLI) {
5398   EVT VT = LHS.getValueType();
5399   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5400   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5401   LLVMContext &Ctx = *DAG.getContext();
5402 
5403   // If the type is legal but the operation isn't, this node might survive all
5404   // the way to operation legalization. If we end up there and we do not have
5405   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5406   // node.
5407 
5408   // Coax the legalizer into expanding the node during type legalization instead
5409   // by bumping the size by one bit. This will force it to Promote, enabling the
5410   // early expansion and avoiding the need to expand later.
5411 
5412   // We don't have to do this if Scale is 0; that can always be expanded, unless
5413   // it's a saturating signed operation. Those can experience true integer
5414   // division overflow, a case which we must avoid.
5415 
5416   // FIXME: We wouldn't have to do this (or any of the early
5417   // expansion/promotion) if it was possible to expand a libcall of an
5418   // illegal type during operation legalization. But it's not, so things
5419   // get a bit hacky.
5420   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5421   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5422       (TLI.isTypeLegal(VT) ||
5423        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5424     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5425         Opcode, VT, ScaleInt);
5426     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5427       EVT PromVT;
5428       if (VT.isScalarInteger())
5429         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5430       else if (VT.isVector()) {
5431         PromVT = VT.getVectorElementType();
5432         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5433         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5434       } else
5435         llvm_unreachable("Wrong VT for DIVFIX?");
5436       if (Signed) {
5437         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5438         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5439       } else {
5440         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5441         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5442       }
5443       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5444       // For saturating operations, we need to shift up the LHS to get the
5445       // proper saturation width, and then shift down again afterwards.
5446       if (Saturating)
5447         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5448                           DAG.getConstant(1, DL, ShiftTy));
5449       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5450       if (Saturating)
5451         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5452                           DAG.getConstant(1, DL, ShiftTy));
5453       return DAG.getZExtOrTrunc(Res, DL, VT);
5454     }
5455   }
5456 
5457   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5458 }
5459 
5460 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5461 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5462 static void
5463 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5464                      const SDValue &N) {
5465   switch (N.getOpcode()) {
5466   case ISD::CopyFromReg: {
5467     SDValue Op = N.getOperand(1);
5468     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5469                       Op.getValueType().getSizeInBits());
5470     return;
5471   }
5472   case ISD::BITCAST:
5473   case ISD::AssertZext:
5474   case ISD::AssertSext:
5475   case ISD::TRUNCATE:
5476     getUnderlyingArgRegs(Regs, N.getOperand(0));
5477     return;
5478   case ISD::BUILD_PAIR:
5479   case ISD::BUILD_VECTOR:
5480   case ISD::CONCAT_VECTORS:
5481     for (SDValue Op : N->op_values())
5482       getUnderlyingArgRegs(Regs, Op);
5483     return;
5484   default:
5485     return;
5486   }
5487 }
5488 
5489 /// If the DbgValueInst is a dbg_value of a function argument, create the
5490 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5491 /// instruction selection, they will be inserted to the entry BB.
5492 /// We don't currently support this for variadic dbg_values, as they shouldn't
5493 /// appear for function arguments or in the prologue.
5494 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5495     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5496     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5497   const Argument *Arg = dyn_cast<Argument>(V);
5498   if (!Arg)
5499     return false;
5500 
5501   MachineFunction &MF = DAG.getMachineFunction();
5502   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5503 
5504   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5505   // we've been asked to pursue.
5506   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5507                               bool Indirect) {
5508     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5509       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5510       // pointing at the VReg, which will be patched up later.
5511       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5512       auto MIB = BuildMI(MF, DL, Inst);
5513       MIB.addReg(Reg);
5514       MIB.addImm(0);
5515       MIB.addMetadata(Variable);
5516       auto *NewDIExpr = FragExpr;
5517       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5518       // the DIExpression.
5519       if (Indirect)
5520         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5521       MIB.addMetadata(NewDIExpr);
5522       return MIB;
5523     } else {
5524       // Create a completely standard DBG_VALUE.
5525       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5526       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5527     }
5528   };
5529 
5530   if (!IsDbgDeclare) {
5531     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5532     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5533     // the entry block.
5534     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5535     if (!IsInEntryBlock)
5536       return false;
5537 
5538     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5539     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5540     // variable that also is a param.
5541     //
5542     // Although, if we are at the top of the entry block already, we can still
5543     // emit using ArgDbgValue. This might catch some situations when the
5544     // dbg.value refers to an argument that isn't used in the entry block, so
5545     // any CopyToReg node would be optimized out and the only way to express
5546     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5547     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5548     // we should only emit as ArgDbgValue if the Variable is an argument to the
5549     // current function, and the dbg.value intrinsic is found in the entry
5550     // block.
5551     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5552         !DL->getInlinedAt();
5553     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5554     if (!IsInPrologue && !VariableIsFunctionInputArg)
5555       return false;
5556 
5557     // Here we assume that a function argument on IR level only can be used to
5558     // describe one input parameter on source level. If we for example have
5559     // source code like this
5560     //
5561     //    struct A { long x, y; };
5562     //    void foo(struct A a, long b) {
5563     //      ...
5564     //      b = a.x;
5565     //      ...
5566     //    }
5567     //
5568     // and IR like this
5569     //
5570     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5571     //  entry:
5572     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5573     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5574     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5575     //    ...
5576     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5577     //    ...
5578     //
5579     // then the last dbg.value is describing a parameter "b" using a value that
5580     // is an argument. But since we already has used %a1 to describe a parameter
5581     // we should not handle that last dbg.value here (that would result in an
5582     // incorrect hoisting of the DBG_VALUE to the function entry).
5583     // Notice that we allow one dbg.value per IR level argument, to accommodate
5584     // for the situation with fragments above.
5585     if (VariableIsFunctionInputArg) {
5586       unsigned ArgNo = Arg->getArgNo();
5587       if (ArgNo >= FuncInfo.DescribedArgs.size())
5588         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5589       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5590         return false;
5591       FuncInfo.DescribedArgs.set(ArgNo);
5592     }
5593   }
5594 
5595   bool IsIndirect = false;
5596   Optional<MachineOperand> Op;
5597   // Some arguments' frame index is recorded during argument lowering.
5598   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5599   if (FI != std::numeric_limits<int>::max())
5600     Op = MachineOperand::CreateFI(FI);
5601 
5602   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5603   if (!Op && N.getNode()) {
5604     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5605     Register Reg;
5606     if (ArgRegsAndSizes.size() == 1)
5607       Reg = ArgRegsAndSizes.front().first;
5608 
5609     if (Reg && Reg.isVirtual()) {
5610       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5611       Register PR = RegInfo.getLiveInPhysReg(Reg);
5612       if (PR)
5613         Reg = PR;
5614     }
5615     if (Reg) {
5616       Op = MachineOperand::CreateReg(Reg, false);
5617       IsIndirect = IsDbgDeclare;
5618     }
5619   }
5620 
5621   if (!Op && N.getNode()) {
5622     // Check if frame index is available.
5623     SDValue LCandidate = peekThroughBitcasts(N);
5624     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5625       if (FrameIndexSDNode *FINode =
5626           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5627         Op = MachineOperand::CreateFI(FINode->getIndex());
5628   }
5629 
5630   if (!Op) {
5631     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5632     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5633                                          SplitRegs) {
5634       unsigned Offset = 0;
5635       for (const auto &RegAndSize : SplitRegs) {
5636         // If the expression is already a fragment, the current register
5637         // offset+size might extend beyond the fragment. In this case, only
5638         // the register bits that are inside the fragment are relevant.
5639         int RegFragmentSizeInBits = RegAndSize.second;
5640         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5641           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5642           // The register is entirely outside the expression fragment,
5643           // so is irrelevant for debug info.
5644           if (Offset >= ExprFragmentSizeInBits)
5645             break;
5646           // The register is partially outside the expression fragment, only
5647           // the low bits within the fragment are relevant for debug info.
5648           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5649             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5650           }
5651         }
5652 
5653         auto FragmentExpr = DIExpression::createFragmentExpression(
5654             Expr, Offset, RegFragmentSizeInBits);
5655         Offset += RegAndSize.second;
5656         // If a valid fragment expression cannot be created, the variable's
5657         // correct value cannot be determined and so it is set as Undef.
5658         if (!FragmentExpr) {
5659           SDDbgValue *SDV = DAG.getConstantDbgValue(
5660               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5661           DAG.AddDbgValue(SDV, false);
5662           continue;
5663         }
5664         MachineInstr *NewMI =
5665             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr, IsDbgDeclare);
5666         FuncInfo.ArgDbgValues.push_back(NewMI);
5667       }
5668     };
5669 
5670     // Check if ValueMap has reg number.
5671     DenseMap<const Value *, Register>::const_iterator
5672       VMI = FuncInfo.ValueMap.find(V);
5673     if (VMI != FuncInfo.ValueMap.end()) {
5674       const auto &TLI = DAG.getTargetLoweringInfo();
5675       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5676                        V->getType(), None);
5677       if (RFV.occupiesMultipleRegs()) {
5678         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5679         return true;
5680       }
5681 
5682       Op = MachineOperand::CreateReg(VMI->second, false);
5683       IsIndirect = IsDbgDeclare;
5684     } else if (ArgRegsAndSizes.size() > 1) {
5685       // This was split due to the calling convention, and no virtual register
5686       // mapping exists for the value.
5687       splitMultiRegDbgValue(ArgRegsAndSizes);
5688       return true;
5689     }
5690   }
5691 
5692   if (!Op)
5693     return false;
5694 
5695   assert(Variable->isValidLocationForIntrinsic(DL) &&
5696          "Expected inlined-at fields to agree");
5697   MachineInstr *NewMI = nullptr;
5698 
5699   if (Op->isReg())
5700     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
5701   else
5702     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
5703                     Variable, Expr);
5704 
5705   FuncInfo.ArgDbgValues.push_back(NewMI);
5706   return true;
5707 }
5708 
5709 /// Return the appropriate SDDbgValue based on N.
5710 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5711                                              DILocalVariable *Variable,
5712                                              DIExpression *Expr,
5713                                              const DebugLoc &dl,
5714                                              unsigned DbgSDNodeOrder) {
5715   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5716     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5717     // stack slot locations.
5718     //
5719     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5720     // debug values here after optimization:
5721     //
5722     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5723     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5724     //
5725     // Both describe the direct values of their associated variables.
5726     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5727                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5728   }
5729   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5730                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5731 }
5732 
5733 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5734   switch (Intrinsic) {
5735   case Intrinsic::smul_fix:
5736     return ISD::SMULFIX;
5737   case Intrinsic::umul_fix:
5738     return ISD::UMULFIX;
5739   case Intrinsic::smul_fix_sat:
5740     return ISD::SMULFIXSAT;
5741   case Intrinsic::umul_fix_sat:
5742     return ISD::UMULFIXSAT;
5743   case Intrinsic::sdiv_fix:
5744     return ISD::SDIVFIX;
5745   case Intrinsic::udiv_fix:
5746     return ISD::UDIVFIX;
5747   case Intrinsic::sdiv_fix_sat:
5748     return ISD::SDIVFIXSAT;
5749   case Intrinsic::udiv_fix_sat:
5750     return ISD::UDIVFIXSAT;
5751   default:
5752     llvm_unreachable("Unhandled fixed point intrinsic");
5753   }
5754 }
5755 
5756 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5757                                            const char *FunctionName) {
5758   assert(FunctionName && "FunctionName must not be nullptr");
5759   SDValue Callee = DAG.getExternalSymbol(
5760       FunctionName,
5761       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5762   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
5763 }
5764 
5765 /// Given a @llvm.call.preallocated.setup, return the corresponding
5766 /// preallocated call.
5767 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5768   assert(cast<CallBase>(PreallocatedSetup)
5769                  ->getCalledFunction()
5770                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5771          "expected call_preallocated_setup Value");
5772   for (auto *U : PreallocatedSetup->users()) {
5773     auto *UseCall = cast<CallBase>(U);
5774     const Function *Fn = UseCall->getCalledFunction();
5775     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5776       return UseCall;
5777     }
5778   }
5779   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5780 }
5781 
5782 /// Lower the call to the specified intrinsic function.
5783 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5784                                              unsigned Intrinsic) {
5785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5786   SDLoc sdl = getCurSDLoc();
5787   DebugLoc dl = getCurDebugLoc();
5788   SDValue Res;
5789 
5790   SDNodeFlags Flags;
5791   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5792     Flags.copyFMF(*FPOp);
5793 
5794   switch (Intrinsic) {
5795   default:
5796     // By default, turn this into a target intrinsic node.
5797     visitTargetIntrinsic(I, Intrinsic);
5798     return;
5799   case Intrinsic::vscale: {
5800     match(&I, m_VScale(DAG.getDataLayout()));
5801     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5802     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
5803     return;
5804   }
5805   case Intrinsic::vastart:  visitVAStart(I); return;
5806   case Intrinsic::vaend:    visitVAEnd(I); return;
5807   case Intrinsic::vacopy:   visitVACopy(I); return;
5808   case Intrinsic::returnaddress:
5809     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5810                              TLI.getPointerTy(DAG.getDataLayout()),
5811                              getValue(I.getArgOperand(0))));
5812     return;
5813   case Intrinsic::addressofreturnaddress:
5814     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5815                              TLI.getPointerTy(DAG.getDataLayout())));
5816     return;
5817   case Intrinsic::sponentry:
5818     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5819                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5820     return;
5821   case Intrinsic::frameaddress:
5822     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5823                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5824                              getValue(I.getArgOperand(0))));
5825     return;
5826   case Intrinsic::read_volatile_register:
5827   case Intrinsic::read_register: {
5828     Value *Reg = I.getArgOperand(0);
5829     SDValue Chain = getRoot();
5830     SDValue RegName =
5831         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5832     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5833     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5834       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5835     setValue(&I, Res);
5836     DAG.setRoot(Res.getValue(1));
5837     return;
5838   }
5839   case Intrinsic::write_register: {
5840     Value *Reg = I.getArgOperand(0);
5841     Value *RegValue = I.getArgOperand(1);
5842     SDValue Chain = getRoot();
5843     SDValue RegName =
5844         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5845     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5846                             RegName, getValue(RegValue)));
5847     return;
5848   }
5849   case Intrinsic::memcpy: {
5850     const auto &MCI = cast<MemCpyInst>(I);
5851     SDValue Op1 = getValue(I.getArgOperand(0));
5852     SDValue Op2 = getValue(I.getArgOperand(1));
5853     SDValue Op3 = getValue(I.getArgOperand(2));
5854     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5855     Align DstAlign = MCI.getDestAlign().valueOrOne();
5856     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5857     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5858     bool isVol = MCI.isVolatile();
5859     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5860     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5861     // node.
5862     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5863     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5864                                /* AlwaysInline */ false, isTC,
5865                                MachinePointerInfo(I.getArgOperand(0)),
5866                                MachinePointerInfo(I.getArgOperand(1)),
5867                                I.getAAMetadata());
5868     updateDAGForMaybeTailCall(MC);
5869     return;
5870   }
5871   case Intrinsic::memcpy_inline: {
5872     const auto &MCI = cast<MemCpyInlineInst>(I);
5873     SDValue Dst = getValue(I.getArgOperand(0));
5874     SDValue Src = getValue(I.getArgOperand(1));
5875     SDValue Size = getValue(I.getArgOperand(2));
5876     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5877     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5878     Align DstAlign = MCI.getDestAlign().valueOrOne();
5879     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5880     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5881     bool isVol = MCI.isVolatile();
5882     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5883     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5884     // node.
5885     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5886                                /* AlwaysInline */ true, isTC,
5887                                MachinePointerInfo(I.getArgOperand(0)),
5888                                MachinePointerInfo(I.getArgOperand(1)),
5889                                I.getAAMetadata());
5890     updateDAGForMaybeTailCall(MC);
5891     return;
5892   }
5893   case Intrinsic::memset: {
5894     const auto &MSI = cast<MemSetInst>(I);
5895     SDValue Op1 = getValue(I.getArgOperand(0));
5896     SDValue Op2 = getValue(I.getArgOperand(1));
5897     SDValue Op3 = getValue(I.getArgOperand(2));
5898     // @llvm.memset defines 0 and 1 to both mean no alignment.
5899     Align Alignment = MSI.getDestAlign().valueOrOne();
5900     bool isVol = MSI.isVolatile();
5901     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5902     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5903     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5904                                MachinePointerInfo(I.getArgOperand(0)),
5905                                I.getAAMetadata());
5906     updateDAGForMaybeTailCall(MS);
5907     return;
5908   }
5909   case Intrinsic::memmove: {
5910     const auto &MMI = cast<MemMoveInst>(I);
5911     SDValue Op1 = getValue(I.getArgOperand(0));
5912     SDValue Op2 = getValue(I.getArgOperand(1));
5913     SDValue Op3 = getValue(I.getArgOperand(2));
5914     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5915     Align DstAlign = MMI.getDestAlign().valueOrOne();
5916     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5917     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5918     bool isVol = MMI.isVolatile();
5919     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5920     // FIXME: Support passing different dest/src alignments to the memmove DAG
5921     // node.
5922     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5923     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5924                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5925                                 MachinePointerInfo(I.getArgOperand(1)),
5926                                 I.getAAMetadata());
5927     updateDAGForMaybeTailCall(MM);
5928     return;
5929   }
5930   case Intrinsic::memcpy_element_unordered_atomic: {
5931     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5932     SDValue Dst = getValue(MI.getRawDest());
5933     SDValue Src = getValue(MI.getRawSource());
5934     SDValue Length = getValue(MI.getLength());
5935 
5936     unsigned DstAlign = MI.getDestAlignment();
5937     unsigned SrcAlign = MI.getSourceAlignment();
5938     Type *LengthTy = MI.getLength()->getType();
5939     unsigned ElemSz = MI.getElementSizeInBytes();
5940     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5941     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5942                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5943                                      MachinePointerInfo(MI.getRawDest()),
5944                                      MachinePointerInfo(MI.getRawSource()));
5945     updateDAGForMaybeTailCall(MC);
5946     return;
5947   }
5948   case Intrinsic::memmove_element_unordered_atomic: {
5949     auto &MI = cast<AtomicMemMoveInst>(I);
5950     SDValue Dst = getValue(MI.getRawDest());
5951     SDValue Src = getValue(MI.getRawSource());
5952     SDValue Length = getValue(MI.getLength());
5953 
5954     unsigned DstAlign = MI.getDestAlignment();
5955     unsigned SrcAlign = MI.getSourceAlignment();
5956     Type *LengthTy = MI.getLength()->getType();
5957     unsigned ElemSz = MI.getElementSizeInBytes();
5958     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5959     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5960                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5961                                       MachinePointerInfo(MI.getRawDest()),
5962                                       MachinePointerInfo(MI.getRawSource()));
5963     updateDAGForMaybeTailCall(MC);
5964     return;
5965   }
5966   case Intrinsic::memset_element_unordered_atomic: {
5967     auto &MI = cast<AtomicMemSetInst>(I);
5968     SDValue Dst = getValue(MI.getRawDest());
5969     SDValue Val = getValue(MI.getValue());
5970     SDValue Length = getValue(MI.getLength());
5971 
5972     unsigned DstAlign = MI.getDestAlignment();
5973     Type *LengthTy = MI.getLength()->getType();
5974     unsigned ElemSz = MI.getElementSizeInBytes();
5975     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5976     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5977                                      LengthTy, ElemSz, isTC,
5978                                      MachinePointerInfo(MI.getRawDest()));
5979     updateDAGForMaybeTailCall(MC);
5980     return;
5981   }
5982   case Intrinsic::call_preallocated_setup: {
5983     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5984     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5985     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5986                               getRoot(), SrcValue);
5987     setValue(&I, Res);
5988     DAG.setRoot(Res);
5989     return;
5990   }
5991   case Intrinsic::call_preallocated_arg: {
5992     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5993     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5994     SDValue Ops[3];
5995     Ops[0] = getRoot();
5996     Ops[1] = SrcValue;
5997     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5998                                    MVT::i32); // arg index
5999     SDValue Res = DAG.getNode(
6000         ISD::PREALLOCATED_ARG, sdl,
6001         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6002     setValue(&I, Res);
6003     DAG.setRoot(Res.getValue(1));
6004     return;
6005   }
6006   case Intrinsic::dbg_addr:
6007   case Intrinsic::dbg_declare: {
6008     // Assume dbg.addr and dbg.declare can not currently use DIArgList, i.e.
6009     // they are non-variadic.
6010     const auto &DI = cast<DbgVariableIntrinsic>(I);
6011     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6012     DILocalVariable *Variable = DI.getVariable();
6013     DIExpression *Expression = DI.getExpression();
6014     dropDanglingDebugInfo(Variable, Expression);
6015     assert(Variable && "Missing variable");
6016     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
6017                       << "\n");
6018     // Check if address has undef value.
6019     const Value *Address = DI.getVariableLocationOp(0);
6020     if (!Address || isa<UndefValue>(Address) ||
6021         (Address->use_empty() && !isa<Argument>(Address))) {
6022       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6023                         << " (bad/undef/unused-arg address)\n");
6024       return;
6025     }
6026 
6027     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6028 
6029     // Check if this variable can be described by a frame index, typically
6030     // either as a static alloca or a byval parameter.
6031     int FI = std::numeric_limits<int>::max();
6032     if (const auto *AI =
6033             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6034       if (AI->isStaticAlloca()) {
6035         auto I = FuncInfo.StaticAllocaMap.find(AI);
6036         if (I != FuncInfo.StaticAllocaMap.end())
6037           FI = I->second;
6038       }
6039     } else if (const auto *Arg = dyn_cast<Argument>(
6040                    Address->stripInBoundsConstantOffsets())) {
6041       FI = FuncInfo.getArgumentFrameIndex(Arg);
6042     }
6043 
6044     // llvm.dbg.addr is control dependent and always generates indirect
6045     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6046     // the MachineFunction variable table.
6047     if (FI != std::numeric_limits<int>::max()) {
6048       if (Intrinsic == Intrinsic::dbg_addr) {
6049         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6050             Variable, Expression, FI, getRoot().getNode(), /*IsIndirect*/ true,
6051             dl, SDNodeOrder);
6052         DAG.AddDbgValue(SDV, isParameter);
6053       } else {
6054         LLVM_DEBUG(dbgs() << "Skipping " << DI
6055                           << " (variable info stashed in MF side table)\n");
6056       }
6057       return;
6058     }
6059 
6060     SDValue &N = NodeMap[Address];
6061     if (!N.getNode() && isa<Argument>(Address))
6062       // Check unused arguments map.
6063       N = UnusedArgNodeMap[Address];
6064     SDDbgValue *SDV;
6065     if (N.getNode()) {
6066       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6067         Address = BCI->getOperand(0);
6068       // Parameters are handled specially.
6069       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6070       if (isParameter && FINode) {
6071         // Byval parameter. We have a frame index at this point.
6072         SDV =
6073             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6074                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6075       } else if (isa<Argument>(Address)) {
6076         // Address is an argument, so try to emit its dbg value using
6077         // virtual register info from the FuncInfo.ValueMap.
6078         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6079         return;
6080       } else {
6081         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6082                               true, dl, SDNodeOrder);
6083       }
6084       DAG.AddDbgValue(SDV, isParameter);
6085     } else {
6086       // If Address is an argument then try to emit its dbg value using
6087       // virtual register info from the FuncInfo.ValueMap.
6088       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6089                                     N)) {
6090         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6091                           << " (could not emit func-arg dbg_value)\n");
6092       }
6093     }
6094     return;
6095   }
6096   case Intrinsic::dbg_label: {
6097     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6098     DILabel *Label = DI.getLabel();
6099     assert(Label && "Missing label");
6100 
6101     SDDbgLabel *SDV;
6102     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6103     DAG.AddDbgLabel(SDV);
6104     return;
6105   }
6106   case Intrinsic::dbg_value: {
6107     const DbgValueInst &DI = cast<DbgValueInst>(I);
6108     assert(DI.getVariable() && "Missing variable");
6109 
6110     DILocalVariable *Variable = DI.getVariable();
6111     DIExpression *Expression = DI.getExpression();
6112     dropDanglingDebugInfo(Variable, Expression);
6113     SmallVector<Value *, 4> Values(DI.getValues());
6114     if (Values.empty())
6115       return;
6116 
6117     if (llvm::is_contained(Values, nullptr))
6118       return;
6119 
6120     bool IsVariadic = DI.hasArgList();
6121     if (!handleDebugValue(Values, Variable, Expression, dl, DI.getDebugLoc(),
6122                           SDNodeOrder, IsVariadic))
6123       addDanglingDebugInfo(&DI, dl, SDNodeOrder);
6124     return;
6125   }
6126 
6127   case Intrinsic::eh_typeid_for: {
6128     // Find the type id for the given typeinfo.
6129     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6130     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6131     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6132     setValue(&I, Res);
6133     return;
6134   }
6135 
6136   case Intrinsic::eh_return_i32:
6137   case Intrinsic::eh_return_i64:
6138     DAG.getMachineFunction().setCallsEHReturn(true);
6139     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6140                             MVT::Other,
6141                             getControlRoot(),
6142                             getValue(I.getArgOperand(0)),
6143                             getValue(I.getArgOperand(1))));
6144     return;
6145   case Intrinsic::eh_unwind_init:
6146     DAG.getMachineFunction().setCallsUnwindInit(true);
6147     return;
6148   case Intrinsic::eh_dwarf_cfa:
6149     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6150                              TLI.getPointerTy(DAG.getDataLayout()),
6151                              getValue(I.getArgOperand(0))));
6152     return;
6153   case Intrinsic::eh_sjlj_callsite: {
6154     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6155     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6156     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6157     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6158 
6159     MMI.setCurrentCallSite(CI->getZExtValue());
6160     return;
6161   }
6162   case Intrinsic::eh_sjlj_functioncontext: {
6163     // Get and store the index of the function context.
6164     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6165     AllocaInst *FnCtx =
6166       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6167     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6168     MFI.setFunctionContextIndex(FI);
6169     return;
6170   }
6171   case Intrinsic::eh_sjlj_setjmp: {
6172     SDValue Ops[2];
6173     Ops[0] = getRoot();
6174     Ops[1] = getValue(I.getArgOperand(0));
6175     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6176                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6177     setValue(&I, Op.getValue(0));
6178     DAG.setRoot(Op.getValue(1));
6179     return;
6180   }
6181   case Intrinsic::eh_sjlj_longjmp:
6182     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6183                             getRoot(), getValue(I.getArgOperand(0))));
6184     return;
6185   case Intrinsic::eh_sjlj_setup_dispatch:
6186     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6187                             getRoot()));
6188     return;
6189   case Intrinsic::masked_gather:
6190     visitMaskedGather(I);
6191     return;
6192   case Intrinsic::masked_load:
6193     visitMaskedLoad(I);
6194     return;
6195   case Intrinsic::masked_scatter:
6196     visitMaskedScatter(I);
6197     return;
6198   case Intrinsic::masked_store:
6199     visitMaskedStore(I);
6200     return;
6201   case Intrinsic::masked_expandload:
6202     visitMaskedLoad(I, true /* IsExpanding */);
6203     return;
6204   case Intrinsic::masked_compressstore:
6205     visitMaskedStore(I, true /* IsCompressing */);
6206     return;
6207   case Intrinsic::powi:
6208     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6209                             getValue(I.getArgOperand(1)), DAG));
6210     return;
6211   case Intrinsic::log:
6212     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6213     return;
6214   case Intrinsic::log2:
6215     setValue(&I,
6216              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6217     return;
6218   case Intrinsic::log10:
6219     setValue(&I,
6220              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6221     return;
6222   case Intrinsic::exp:
6223     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6224     return;
6225   case Intrinsic::exp2:
6226     setValue(&I,
6227              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6228     return;
6229   case Intrinsic::pow:
6230     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6231                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6232     return;
6233   case Intrinsic::sqrt:
6234   case Intrinsic::fabs:
6235   case Intrinsic::sin:
6236   case Intrinsic::cos:
6237   case Intrinsic::floor:
6238   case Intrinsic::ceil:
6239   case Intrinsic::trunc:
6240   case Intrinsic::rint:
6241   case Intrinsic::nearbyint:
6242   case Intrinsic::round:
6243   case Intrinsic::roundeven:
6244   case Intrinsic::canonicalize: {
6245     unsigned Opcode;
6246     switch (Intrinsic) {
6247     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6248     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6249     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6250     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6251     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6252     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6253     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6254     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6255     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6256     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6257     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6258     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6259     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6260     }
6261 
6262     setValue(&I, DAG.getNode(Opcode, sdl,
6263                              getValue(I.getArgOperand(0)).getValueType(),
6264                              getValue(I.getArgOperand(0)), Flags));
6265     return;
6266   }
6267   case Intrinsic::lround:
6268   case Intrinsic::llround:
6269   case Intrinsic::lrint:
6270   case Intrinsic::llrint: {
6271     unsigned Opcode;
6272     switch (Intrinsic) {
6273     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6274     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6275     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6276     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6277     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6278     }
6279 
6280     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6281     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6282                              getValue(I.getArgOperand(0))));
6283     return;
6284   }
6285   case Intrinsic::minnum:
6286     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6287                              getValue(I.getArgOperand(0)).getValueType(),
6288                              getValue(I.getArgOperand(0)),
6289                              getValue(I.getArgOperand(1)), Flags));
6290     return;
6291   case Intrinsic::maxnum:
6292     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6293                              getValue(I.getArgOperand(0)).getValueType(),
6294                              getValue(I.getArgOperand(0)),
6295                              getValue(I.getArgOperand(1)), Flags));
6296     return;
6297   case Intrinsic::minimum:
6298     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6299                              getValue(I.getArgOperand(0)).getValueType(),
6300                              getValue(I.getArgOperand(0)),
6301                              getValue(I.getArgOperand(1)), Flags));
6302     return;
6303   case Intrinsic::maximum:
6304     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6305                              getValue(I.getArgOperand(0)).getValueType(),
6306                              getValue(I.getArgOperand(0)),
6307                              getValue(I.getArgOperand(1)), Flags));
6308     return;
6309   case Intrinsic::copysign:
6310     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6311                              getValue(I.getArgOperand(0)).getValueType(),
6312                              getValue(I.getArgOperand(0)),
6313                              getValue(I.getArgOperand(1)), Flags));
6314     return;
6315   case Intrinsic::arithmetic_fence: {
6316     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6317                              getValue(I.getArgOperand(0)).getValueType(),
6318                              getValue(I.getArgOperand(0)), Flags));
6319     return;
6320   }
6321   case Intrinsic::fma:
6322     setValue(&I, DAG.getNode(
6323                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6324                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6325                      getValue(I.getArgOperand(2)), Flags));
6326     return;
6327 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6328   case Intrinsic::INTRINSIC:
6329 #include "llvm/IR/ConstrainedOps.def"
6330     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6331     return;
6332 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6333 #include "llvm/IR/VPIntrinsics.def"
6334     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6335     return;
6336   case Intrinsic::fmuladd: {
6337     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6338     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6339         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6340       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6341                                getValue(I.getArgOperand(0)).getValueType(),
6342                                getValue(I.getArgOperand(0)),
6343                                getValue(I.getArgOperand(1)),
6344                                getValue(I.getArgOperand(2)), Flags));
6345     } else {
6346       // TODO: Intrinsic calls should have fast-math-flags.
6347       SDValue Mul = DAG.getNode(
6348           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6349           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6350       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6351                                 getValue(I.getArgOperand(0)).getValueType(),
6352                                 Mul, getValue(I.getArgOperand(2)), Flags);
6353       setValue(&I, Add);
6354     }
6355     return;
6356   }
6357   case Intrinsic::convert_to_fp16:
6358     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6359                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6360                                          getValue(I.getArgOperand(0)),
6361                                          DAG.getTargetConstant(0, sdl,
6362                                                                MVT::i32))));
6363     return;
6364   case Intrinsic::convert_from_fp16:
6365     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6366                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6367                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6368                                          getValue(I.getArgOperand(0)))));
6369     return;
6370   case Intrinsic::fptosi_sat: {
6371     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6372     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6373                              getValue(I.getArgOperand(0)),
6374                              DAG.getValueType(VT.getScalarType())));
6375     return;
6376   }
6377   case Intrinsic::fptoui_sat: {
6378     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6379     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6380                              getValue(I.getArgOperand(0)),
6381                              DAG.getValueType(VT.getScalarType())));
6382     return;
6383   }
6384   case Intrinsic::set_rounding:
6385     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6386                       {getRoot(), getValue(I.getArgOperand(0))});
6387     setValue(&I, Res);
6388     DAG.setRoot(Res.getValue(0));
6389     return;
6390   case Intrinsic::pcmarker: {
6391     SDValue Tmp = getValue(I.getArgOperand(0));
6392     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6393     return;
6394   }
6395   case Intrinsic::readcyclecounter: {
6396     SDValue Op = getRoot();
6397     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6398                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6399     setValue(&I, Res);
6400     DAG.setRoot(Res.getValue(1));
6401     return;
6402   }
6403   case Intrinsic::bitreverse:
6404     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6405                              getValue(I.getArgOperand(0)).getValueType(),
6406                              getValue(I.getArgOperand(0))));
6407     return;
6408   case Intrinsic::bswap:
6409     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6410                              getValue(I.getArgOperand(0)).getValueType(),
6411                              getValue(I.getArgOperand(0))));
6412     return;
6413   case Intrinsic::cttz: {
6414     SDValue Arg = getValue(I.getArgOperand(0));
6415     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6416     EVT Ty = Arg.getValueType();
6417     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6418                              sdl, Ty, Arg));
6419     return;
6420   }
6421   case Intrinsic::ctlz: {
6422     SDValue Arg = getValue(I.getArgOperand(0));
6423     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6424     EVT Ty = Arg.getValueType();
6425     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6426                              sdl, Ty, Arg));
6427     return;
6428   }
6429   case Intrinsic::ctpop: {
6430     SDValue Arg = getValue(I.getArgOperand(0));
6431     EVT Ty = Arg.getValueType();
6432     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6433     return;
6434   }
6435   case Intrinsic::fshl:
6436   case Intrinsic::fshr: {
6437     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6438     SDValue X = getValue(I.getArgOperand(0));
6439     SDValue Y = getValue(I.getArgOperand(1));
6440     SDValue Z = getValue(I.getArgOperand(2));
6441     EVT VT = X.getValueType();
6442 
6443     if (X == Y) {
6444       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6445       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6446     } else {
6447       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6448       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6449     }
6450     return;
6451   }
6452   case Intrinsic::sadd_sat: {
6453     SDValue Op1 = getValue(I.getArgOperand(0));
6454     SDValue Op2 = getValue(I.getArgOperand(1));
6455     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6456     return;
6457   }
6458   case Intrinsic::uadd_sat: {
6459     SDValue Op1 = getValue(I.getArgOperand(0));
6460     SDValue Op2 = getValue(I.getArgOperand(1));
6461     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6462     return;
6463   }
6464   case Intrinsic::ssub_sat: {
6465     SDValue Op1 = getValue(I.getArgOperand(0));
6466     SDValue Op2 = getValue(I.getArgOperand(1));
6467     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6468     return;
6469   }
6470   case Intrinsic::usub_sat: {
6471     SDValue Op1 = getValue(I.getArgOperand(0));
6472     SDValue Op2 = getValue(I.getArgOperand(1));
6473     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6474     return;
6475   }
6476   case Intrinsic::sshl_sat: {
6477     SDValue Op1 = getValue(I.getArgOperand(0));
6478     SDValue Op2 = getValue(I.getArgOperand(1));
6479     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6480     return;
6481   }
6482   case Intrinsic::ushl_sat: {
6483     SDValue Op1 = getValue(I.getArgOperand(0));
6484     SDValue Op2 = getValue(I.getArgOperand(1));
6485     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6486     return;
6487   }
6488   case Intrinsic::smul_fix:
6489   case Intrinsic::umul_fix:
6490   case Intrinsic::smul_fix_sat:
6491   case Intrinsic::umul_fix_sat: {
6492     SDValue Op1 = getValue(I.getArgOperand(0));
6493     SDValue Op2 = getValue(I.getArgOperand(1));
6494     SDValue Op3 = getValue(I.getArgOperand(2));
6495     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6496                              Op1.getValueType(), Op1, Op2, Op3));
6497     return;
6498   }
6499   case Intrinsic::sdiv_fix:
6500   case Intrinsic::udiv_fix:
6501   case Intrinsic::sdiv_fix_sat:
6502   case Intrinsic::udiv_fix_sat: {
6503     SDValue Op1 = getValue(I.getArgOperand(0));
6504     SDValue Op2 = getValue(I.getArgOperand(1));
6505     SDValue Op3 = getValue(I.getArgOperand(2));
6506     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6507                               Op1, Op2, Op3, DAG, TLI));
6508     return;
6509   }
6510   case Intrinsic::smax: {
6511     SDValue Op1 = getValue(I.getArgOperand(0));
6512     SDValue Op2 = getValue(I.getArgOperand(1));
6513     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6514     return;
6515   }
6516   case Intrinsic::smin: {
6517     SDValue Op1 = getValue(I.getArgOperand(0));
6518     SDValue Op2 = getValue(I.getArgOperand(1));
6519     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6520     return;
6521   }
6522   case Intrinsic::umax: {
6523     SDValue Op1 = getValue(I.getArgOperand(0));
6524     SDValue Op2 = getValue(I.getArgOperand(1));
6525     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6526     return;
6527   }
6528   case Intrinsic::umin: {
6529     SDValue Op1 = getValue(I.getArgOperand(0));
6530     SDValue Op2 = getValue(I.getArgOperand(1));
6531     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6532     return;
6533   }
6534   case Intrinsic::abs: {
6535     // TODO: Preserve "int min is poison" arg in SDAG?
6536     SDValue Op1 = getValue(I.getArgOperand(0));
6537     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6538     return;
6539   }
6540   case Intrinsic::stacksave: {
6541     SDValue Op = getRoot();
6542     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6543     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6544     setValue(&I, Res);
6545     DAG.setRoot(Res.getValue(1));
6546     return;
6547   }
6548   case Intrinsic::stackrestore:
6549     Res = getValue(I.getArgOperand(0));
6550     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6551     return;
6552   case Intrinsic::get_dynamic_area_offset: {
6553     SDValue Op = getRoot();
6554     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6555     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6556     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6557     // target.
6558     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6559       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6560                          " intrinsic!");
6561     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6562                       Op);
6563     DAG.setRoot(Op);
6564     setValue(&I, Res);
6565     return;
6566   }
6567   case Intrinsic::stackguard: {
6568     MachineFunction &MF = DAG.getMachineFunction();
6569     const Module &M = *MF.getFunction().getParent();
6570     SDValue Chain = getRoot();
6571     if (TLI.useLoadStackGuardNode()) {
6572       Res = getLoadStackGuard(DAG, sdl, Chain);
6573     } else {
6574       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6575       const Value *Global = TLI.getSDagStackGuard(M);
6576       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
6577       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6578                         MachinePointerInfo(Global, 0), Align,
6579                         MachineMemOperand::MOVolatile);
6580     }
6581     if (TLI.useStackGuardXorFP())
6582       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6583     DAG.setRoot(Chain);
6584     setValue(&I, Res);
6585     return;
6586   }
6587   case Intrinsic::stackprotector: {
6588     // Emit code into the DAG to store the stack guard onto the stack.
6589     MachineFunction &MF = DAG.getMachineFunction();
6590     MachineFrameInfo &MFI = MF.getFrameInfo();
6591     SDValue Src, Chain = getRoot();
6592 
6593     if (TLI.useLoadStackGuardNode())
6594       Src = getLoadStackGuard(DAG, sdl, Chain);
6595     else
6596       Src = getValue(I.getArgOperand(0));   // The guard's value.
6597 
6598     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6599 
6600     int FI = FuncInfo.StaticAllocaMap[Slot];
6601     MFI.setStackProtectorIndex(FI);
6602     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6603 
6604     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6605 
6606     // Store the stack protector onto the stack.
6607     Res = DAG.getStore(
6608         Chain, sdl, Src, FIN,
6609         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6610         MaybeAlign(), MachineMemOperand::MOVolatile);
6611     setValue(&I, Res);
6612     DAG.setRoot(Res);
6613     return;
6614   }
6615   case Intrinsic::objectsize:
6616     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6617 
6618   case Intrinsic::is_constant:
6619     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6620 
6621   case Intrinsic::annotation:
6622   case Intrinsic::ptr_annotation:
6623   case Intrinsic::launder_invariant_group:
6624   case Intrinsic::strip_invariant_group:
6625     // Drop the intrinsic, but forward the value
6626     setValue(&I, getValue(I.getOperand(0)));
6627     return;
6628 
6629   case Intrinsic::assume:
6630   case Intrinsic::experimental_noalias_scope_decl:
6631   case Intrinsic::var_annotation:
6632   case Intrinsic::sideeffect:
6633     // Discard annotate attributes, noalias scope declarations, assumptions, and
6634     // artificial side-effects.
6635     return;
6636 
6637   case Intrinsic::codeview_annotation: {
6638     // Emit a label associated with this metadata.
6639     MachineFunction &MF = DAG.getMachineFunction();
6640     MCSymbol *Label =
6641         MF.getMMI().getContext().createTempSymbol("annotation", true);
6642     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6643     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6644     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6645     DAG.setRoot(Res);
6646     return;
6647   }
6648 
6649   case Intrinsic::init_trampoline: {
6650     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6651 
6652     SDValue Ops[6];
6653     Ops[0] = getRoot();
6654     Ops[1] = getValue(I.getArgOperand(0));
6655     Ops[2] = getValue(I.getArgOperand(1));
6656     Ops[3] = getValue(I.getArgOperand(2));
6657     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6658     Ops[5] = DAG.getSrcValue(F);
6659 
6660     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6661 
6662     DAG.setRoot(Res);
6663     return;
6664   }
6665   case Intrinsic::adjust_trampoline:
6666     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6667                              TLI.getPointerTy(DAG.getDataLayout()),
6668                              getValue(I.getArgOperand(0))));
6669     return;
6670   case Intrinsic::gcroot: {
6671     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6672            "only valid in functions with gc specified, enforced by Verifier");
6673     assert(GFI && "implied by previous");
6674     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6675     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6676 
6677     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6678     GFI->addStackRoot(FI->getIndex(), TypeMap);
6679     return;
6680   }
6681   case Intrinsic::gcread:
6682   case Intrinsic::gcwrite:
6683     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6684   case Intrinsic::flt_rounds:
6685     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6686     setValue(&I, Res);
6687     DAG.setRoot(Res.getValue(1));
6688     return;
6689 
6690   case Intrinsic::expect:
6691     // Just replace __builtin_expect(exp, c) with EXP.
6692     setValue(&I, getValue(I.getArgOperand(0)));
6693     return;
6694 
6695   case Intrinsic::ubsantrap:
6696   case Intrinsic::debugtrap:
6697   case Intrinsic::trap: {
6698     StringRef TrapFuncName =
6699         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
6700     if (TrapFuncName.empty()) {
6701       switch (Intrinsic) {
6702       case Intrinsic::trap:
6703         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6704         break;
6705       case Intrinsic::debugtrap:
6706         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6707         break;
6708       case Intrinsic::ubsantrap:
6709         DAG.setRoot(DAG.getNode(
6710             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6711             DAG.getTargetConstant(
6712                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6713                 MVT::i32)));
6714         break;
6715       default: llvm_unreachable("unknown trap intrinsic");
6716       }
6717       return;
6718     }
6719     TargetLowering::ArgListTy Args;
6720     if (Intrinsic == Intrinsic::ubsantrap) {
6721       Args.push_back(TargetLoweringBase::ArgListEntry());
6722       Args[0].Val = I.getArgOperand(0);
6723       Args[0].Node = getValue(Args[0].Val);
6724       Args[0].Ty = Args[0].Val->getType();
6725     }
6726 
6727     TargetLowering::CallLoweringInfo CLI(DAG);
6728     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6729         CallingConv::C, I.getType(),
6730         DAG.getExternalSymbol(TrapFuncName.data(),
6731                               TLI.getPointerTy(DAG.getDataLayout())),
6732         std::move(Args));
6733 
6734     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6735     DAG.setRoot(Result.second);
6736     return;
6737   }
6738 
6739   case Intrinsic::uadd_with_overflow:
6740   case Intrinsic::sadd_with_overflow:
6741   case Intrinsic::usub_with_overflow:
6742   case Intrinsic::ssub_with_overflow:
6743   case Intrinsic::umul_with_overflow:
6744   case Intrinsic::smul_with_overflow: {
6745     ISD::NodeType Op;
6746     switch (Intrinsic) {
6747     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6748     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6749     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6750     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6751     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6752     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6753     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6754     }
6755     SDValue Op1 = getValue(I.getArgOperand(0));
6756     SDValue Op2 = getValue(I.getArgOperand(1));
6757 
6758     EVT ResultVT = Op1.getValueType();
6759     EVT OverflowVT = MVT::i1;
6760     if (ResultVT.isVector())
6761       OverflowVT = EVT::getVectorVT(
6762           *Context, OverflowVT, ResultVT.getVectorElementCount());
6763 
6764     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6765     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6766     return;
6767   }
6768   case Intrinsic::prefetch: {
6769     SDValue Ops[5];
6770     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6771     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6772     Ops[0] = DAG.getRoot();
6773     Ops[1] = getValue(I.getArgOperand(0));
6774     Ops[2] = getValue(I.getArgOperand(1));
6775     Ops[3] = getValue(I.getArgOperand(2));
6776     Ops[4] = getValue(I.getArgOperand(3));
6777     SDValue Result = DAG.getMemIntrinsicNode(
6778         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6779         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6780         /* align */ None, Flags);
6781 
6782     // Chain the prefetch in parallell with any pending loads, to stay out of
6783     // the way of later optimizations.
6784     PendingLoads.push_back(Result);
6785     Result = getRoot();
6786     DAG.setRoot(Result);
6787     return;
6788   }
6789   case Intrinsic::lifetime_start:
6790   case Intrinsic::lifetime_end: {
6791     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6792     // Stack coloring is not enabled in O0, discard region information.
6793     if (TM.getOptLevel() == CodeGenOpt::None)
6794       return;
6795 
6796     const int64_t ObjectSize =
6797         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6798     Value *const ObjectPtr = I.getArgOperand(1);
6799     SmallVector<const Value *, 4> Allocas;
6800     getUnderlyingObjects(ObjectPtr, Allocas);
6801 
6802     for (const Value *Alloca : Allocas) {
6803       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6804 
6805       // Could not find an Alloca.
6806       if (!LifetimeObject)
6807         continue;
6808 
6809       // First check that the Alloca is static, otherwise it won't have a
6810       // valid frame index.
6811       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6812       if (SI == FuncInfo.StaticAllocaMap.end())
6813         return;
6814 
6815       const int FrameIndex = SI->second;
6816       int64_t Offset;
6817       if (GetPointerBaseWithConstantOffset(
6818               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6819         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6820       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6821                                 Offset);
6822       DAG.setRoot(Res);
6823     }
6824     return;
6825   }
6826   case Intrinsic::pseudoprobe: {
6827     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6828     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6829     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6830     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6831     DAG.setRoot(Res);
6832     return;
6833   }
6834   case Intrinsic::invariant_start:
6835     // Discard region information.
6836     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6837     return;
6838   case Intrinsic::invariant_end:
6839     // Discard region information.
6840     return;
6841   case Intrinsic::clear_cache:
6842     /// FunctionName may be null.
6843     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6844       lowerCallToExternalSymbol(I, FunctionName);
6845     return;
6846   case Intrinsic::donothing:
6847   case Intrinsic::seh_try_begin:
6848   case Intrinsic::seh_scope_begin:
6849   case Intrinsic::seh_try_end:
6850   case Intrinsic::seh_scope_end:
6851     // ignore
6852     return;
6853   case Intrinsic::experimental_stackmap:
6854     visitStackmap(I);
6855     return;
6856   case Intrinsic::experimental_patchpoint_void:
6857   case Intrinsic::experimental_patchpoint_i64:
6858     visitPatchpoint(I);
6859     return;
6860   case Intrinsic::experimental_gc_statepoint:
6861     LowerStatepoint(cast<GCStatepointInst>(I));
6862     return;
6863   case Intrinsic::experimental_gc_result:
6864     visitGCResult(cast<GCResultInst>(I));
6865     return;
6866   case Intrinsic::experimental_gc_relocate:
6867     visitGCRelocate(cast<GCRelocateInst>(I));
6868     return;
6869   case Intrinsic::instrprof_increment:
6870     llvm_unreachable("instrprof failed to lower an increment");
6871   case Intrinsic::instrprof_value_profile:
6872     llvm_unreachable("instrprof failed to lower a value profiling call");
6873   case Intrinsic::localescape: {
6874     MachineFunction &MF = DAG.getMachineFunction();
6875     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6876 
6877     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6878     // is the same on all targets.
6879     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
6880       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6881       if (isa<ConstantPointerNull>(Arg))
6882         continue; // Skip null pointers. They represent a hole in index space.
6883       AllocaInst *Slot = cast<AllocaInst>(Arg);
6884       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6885              "can only escape static allocas");
6886       int FI = FuncInfo.StaticAllocaMap[Slot];
6887       MCSymbol *FrameAllocSym =
6888           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6889               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6890       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6891               TII->get(TargetOpcode::LOCAL_ESCAPE))
6892           .addSym(FrameAllocSym)
6893           .addFrameIndex(FI);
6894     }
6895 
6896     return;
6897   }
6898 
6899   case Intrinsic::localrecover: {
6900     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6901     MachineFunction &MF = DAG.getMachineFunction();
6902 
6903     // Get the symbol that defines the frame offset.
6904     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6905     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6906     unsigned IdxVal =
6907         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6908     MCSymbol *FrameAllocSym =
6909         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6910             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6911 
6912     Value *FP = I.getArgOperand(1);
6913     SDValue FPVal = getValue(FP);
6914     EVT PtrVT = FPVal.getValueType();
6915 
6916     // Create a MCSymbol for the label to avoid any target lowering
6917     // that would make this PC relative.
6918     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6919     SDValue OffsetVal =
6920         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6921 
6922     // Add the offset to the FP.
6923     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6924     setValue(&I, Add);
6925 
6926     return;
6927   }
6928 
6929   case Intrinsic::eh_exceptionpointer:
6930   case Intrinsic::eh_exceptioncode: {
6931     // Get the exception pointer vreg, copy from it, and resize it to fit.
6932     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6933     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6934     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6935     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6936     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
6937     if (Intrinsic == Intrinsic::eh_exceptioncode)
6938       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
6939     setValue(&I, N);
6940     return;
6941   }
6942   case Intrinsic::xray_customevent: {
6943     // Here we want to make sure that the intrinsic behaves as if it has a
6944     // specific calling convention, and only for x86_64.
6945     // FIXME: Support other platforms later.
6946     const auto &Triple = DAG.getTarget().getTargetTriple();
6947     if (Triple.getArch() != Triple::x86_64)
6948       return;
6949 
6950     SmallVector<SDValue, 8> Ops;
6951 
6952     // We want to say that we always want the arguments in registers.
6953     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6954     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6955     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6956     SDValue Chain = getRoot();
6957     Ops.push_back(LogEntryVal);
6958     Ops.push_back(StrSizeVal);
6959     Ops.push_back(Chain);
6960 
6961     // We need to enforce the calling convention for the callsite, so that
6962     // argument ordering is enforced correctly, and that register allocation can
6963     // see that some registers may be assumed clobbered and have to preserve
6964     // them across calls to the intrinsic.
6965     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6966                                            sdl, NodeTys, Ops);
6967     SDValue patchableNode = SDValue(MN, 0);
6968     DAG.setRoot(patchableNode);
6969     setValue(&I, patchableNode);
6970     return;
6971   }
6972   case Intrinsic::xray_typedevent: {
6973     // Here we want to make sure that the intrinsic behaves as if it has a
6974     // specific calling convention, and only for x86_64.
6975     // FIXME: Support other platforms later.
6976     const auto &Triple = DAG.getTarget().getTargetTriple();
6977     if (Triple.getArch() != Triple::x86_64)
6978       return;
6979 
6980     SmallVector<SDValue, 8> Ops;
6981 
6982     // We want to say that we always want the arguments in registers.
6983     // It's unclear to me how manipulating the selection DAG here forces callers
6984     // to provide arguments in registers instead of on the stack.
6985     SDValue LogTypeId = getValue(I.getArgOperand(0));
6986     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6987     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6988     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6989     SDValue Chain = getRoot();
6990     Ops.push_back(LogTypeId);
6991     Ops.push_back(LogEntryVal);
6992     Ops.push_back(StrSizeVal);
6993     Ops.push_back(Chain);
6994 
6995     // We need to enforce the calling convention for the callsite, so that
6996     // argument ordering is enforced correctly, and that register allocation can
6997     // see that some registers may be assumed clobbered and have to preserve
6998     // them across calls to the intrinsic.
6999     MachineSDNode *MN = DAG.getMachineNode(
7000         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7001     SDValue patchableNode = SDValue(MN, 0);
7002     DAG.setRoot(patchableNode);
7003     setValue(&I, patchableNode);
7004     return;
7005   }
7006   case Intrinsic::experimental_deoptimize:
7007     LowerDeoptimizeCall(&I);
7008     return;
7009   case Intrinsic::experimental_stepvector:
7010     visitStepVector(I);
7011     return;
7012   case Intrinsic::vector_reduce_fadd:
7013   case Intrinsic::vector_reduce_fmul:
7014   case Intrinsic::vector_reduce_add:
7015   case Intrinsic::vector_reduce_mul:
7016   case Intrinsic::vector_reduce_and:
7017   case Intrinsic::vector_reduce_or:
7018   case Intrinsic::vector_reduce_xor:
7019   case Intrinsic::vector_reduce_smax:
7020   case Intrinsic::vector_reduce_smin:
7021   case Intrinsic::vector_reduce_umax:
7022   case Intrinsic::vector_reduce_umin:
7023   case Intrinsic::vector_reduce_fmax:
7024   case Intrinsic::vector_reduce_fmin:
7025     visitVectorReduce(I, Intrinsic);
7026     return;
7027 
7028   case Intrinsic::icall_branch_funnel: {
7029     SmallVector<SDValue, 16> Ops;
7030     Ops.push_back(getValue(I.getArgOperand(0)));
7031 
7032     int64_t Offset;
7033     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7034         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7035     if (!Base)
7036       report_fatal_error(
7037           "llvm.icall.branch.funnel operand must be a GlobalValue");
7038     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7039 
7040     struct BranchFunnelTarget {
7041       int64_t Offset;
7042       SDValue Target;
7043     };
7044     SmallVector<BranchFunnelTarget, 8> Targets;
7045 
7046     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7047       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7048           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7049       if (ElemBase != Base)
7050         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7051                            "to the same GlobalValue");
7052 
7053       SDValue Val = getValue(I.getArgOperand(Op + 1));
7054       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7055       if (!GA)
7056         report_fatal_error(
7057             "llvm.icall.branch.funnel operand must be a GlobalValue");
7058       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7059                                      GA->getGlobal(), sdl, Val.getValueType(),
7060                                      GA->getOffset())});
7061     }
7062     llvm::sort(Targets,
7063                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7064                  return T1.Offset < T2.Offset;
7065                });
7066 
7067     for (auto &T : Targets) {
7068       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7069       Ops.push_back(T.Target);
7070     }
7071 
7072     Ops.push_back(DAG.getRoot()); // Chain
7073     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7074                                  MVT::Other, Ops),
7075               0);
7076     DAG.setRoot(N);
7077     setValue(&I, N);
7078     HasTailCall = true;
7079     return;
7080   }
7081 
7082   case Intrinsic::wasm_landingpad_index:
7083     // Information this intrinsic contained has been transferred to
7084     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7085     // delete it now.
7086     return;
7087 
7088   case Intrinsic::aarch64_settag:
7089   case Intrinsic::aarch64_settag_zero: {
7090     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7091     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7092     SDValue Val = TSI.EmitTargetCodeForSetTag(
7093         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7094         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7095         ZeroMemory);
7096     DAG.setRoot(Val);
7097     setValue(&I, Val);
7098     return;
7099   }
7100   case Intrinsic::ptrmask: {
7101     SDValue Ptr = getValue(I.getOperand(0));
7102     SDValue Const = getValue(I.getOperand(1));
7103 
7104     EVT PtrVT = Ptr.getValueType();
7105     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr,
7106                              DAG.getZExtOrTrunc(Const, sdl, PtrVT)));
7107     return;
7108   }
7109   case Intrinsic::get_active_lane_mask: {
7110     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7111     SDValue Index = getValue(I.getOperand(0));
7112     EVT ElementVT = Index.getValueType();
7113 
7114     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7115       visitTargetIntrinsic(I, Intrinsic);
7116       return;
7117     }
7118 
7119     SDValue TripCount = getValue(I.getOperand(1));
7120     auto VecTy = CCVT.changeVectorElementType(ElementVT);
7121 
7122     SDValue VectorIndex, VectorTripCount;
7123     if (VecTy.isScalableVector()) {
7124       VectorIndex = DAG.getSplatVector(VecTy, sdl, Index);
7125       VectorTripCount = DAG.getSplatVector(VecTy, sdl, TripCount);
7126     } else {
7127       VectorIndex = DAG.getSplatBuildVector(VecTy, sdl, Index);
7128       VectorTripCount = DAG.getSplatBuildVector(VecTy, sdl, TripCount);
7129     }
7130     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7131     SDValue VectorInduction = DAG.getNode(
7132         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7133     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7134                                  VectorTripCount, ISD::CondCode::SETULT);
7135     setValue(&I, SetCC);
7136     return;
7137   }
7138   case Intrinsic::experimental_vector_insert: {
7139     SDValue Vec = getValue(I.getOperand(0));
7140     SDValue SubVec = getValue(I.getOperand(1));
7141     SDValue Index = getValue(I.getOperand(2));
7142 
7143     // The intrinsic's index type is i64, but the SDNode requires an index type
7144     // suitable for the target. Convert the index as required.
7145     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7146     if (Index.getValueType() != VectorIdxTy)
7147       Index = DAG.getVectorIdxConstant(
7148           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7149 
7150     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7151     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7152                              Index));
7153     return;
7154   }
7155   case Intrinsic::experimental_vector_extract: {
7156     SDValue Vec = getValue(I.getOperand(0));
7157     SDValue Index = getValue(I.getOperand(1));
7158     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7159 
7160     // The intrinsic's index type is i64, but the SDNode requires an index type
7161     // suitable for the target. Convert the index as required.
7162     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7163     if (Index.getValueType() != VectorIdxTy)
7164       Index = DAG.getVectorIdxConstant(
7165           cast<ConstantSDNode>(Index)->getZExtValue(), sdl);
7166 
7167     setValue(&I,
7168              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7169     return;
7170   }
7171   case Intrinsic::experimental_vector_reverse:
7172     visitVectorReverse(I);
7173     return;
7174   case Intrinsic::experimental_vector_splice:
7175     visitVectorSplice(I);
7176     return;
7177   }
7178 }
7179 
7180 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7181     const ConstrainedFPIntrinsic &FPI) {
7182   SDLoc sdl = getCurSDLoc();
7183 
7184   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7185   SmallVector<EVT, 4> ValueVTs;
7186   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7187   ValueVTs.push_back(MVT::Other); // Out chain
7188 
7189   // We do not need to serialize constrained FP intrinsics against
7190   // each other or against (nonvolatile) loads, so they can be
7191   // chained like loads.
7192   SDValue Chain = DAG.getRoot();
7193   SmallVector<SDValue, 4> Opers;
7194   Opers.push_back(Chain);
7195   if (FPI.isUnaryOp()) {
7196     Opers.push_back(getValue(FPI.getArgOperand(0)));
7197   } else if (FPI.isTernaryOp()) {
7198     Opers.push_back(getValue(FPI.getArgOperand(0)));
7199     Opers.push_back(getValue(FPI.getArgOperand(1)));
7200     Opers.push_back(getValue(FPI.getArgOperand(2)));
7201   } else {
7202     Opers.push_back(getValue(FPI.getArgOperand(0)));
7203     Opers.push_back(getValue(FPI.getArgOperand(1)));
7204   }
7205 
7206   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7207     assert(Result.getNode()->getNumValues() == 2);
7208 
7209     // Push node to the appropriate list so that future instructions can be
7210     // chained up correctly.
7211     SDValue OutChain = Result.getValue(1);
7212     switch (EB) {
7213     case fp::ExceptionBehavior::ebIgnore:
7214       // The only reason why ebIgnore nodes still need to be chained is that
7215       // they might depend on the current rounding mode, and therefore must
7216       // not be moved across instruction that may change that mode.
7217       LLVM_FALLTHROUGH;
7218     case fp::ExceptionBehavior::ebMayTrap:
7219       // These must not be moved across calls or instructions that may change
7220       // floating-point exception masks.
7221       PendingConstrainedFP.push_back(OutChain);
7222       break;
7223     case fp::ExceptionBehavior::ebStrict:
7224       // These must not be moved across calls or instructions that may change
7225       // floating-point exception masks or read floating-point exception flags.
7226       // In addition, they cannot be optimized out even if unused.
7227       PendingConstrainedFPStrict.push_back(OutChain);
7228       break;
7229     }
7230   };
7231 
7232   SDVTList VTs = DAG.getVTList(ValueVTs);
7233   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7234 
7235   SDNodeFlags Flags;
7236   if (EB == fp::ExceptionBehavior::ebIgnore)
7237     Flags.setNoFPExcept(true);
7238 
7239   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7240     Flags.copyFMF(*FPOp);
7241 
7242   unsigned Opcode;
7243   switch (FPI.getIntrinsicID()) {
7244   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7245 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7246   case Intrinsic::INTRINSIC:                                                   \
7247     Opcode = ISD::STRICT_##DAGN;                                               \
7248     break;
7249 #include "llvm/IR/ConstrainedOps.def"
7250   case Intrinsic::experimental_constrained_fmuladd: {
7251     Opcode = ISD::STRICT_FMA;
7252     // Break fmuladd into fmul and fadd.
7253     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7254         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7255                                         ValueVTs[0])) {
7256       Opers.pop_back();
7257       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7258       pushOutChain(Mul, EB);
7259       Opcode = ISD::STRICT_FADD;
7260       Opers.clear();
7261       Opers.push_back(Mul.getValue(1));
7262       Opers.push_back(Mul.getValue(0));
7263       Opers.push_back(getValue(FPI.getArgOperand(2)));
7264     }
7265     break;
7266   }
7267   }
7268 
7269   // A few strict DAG nodes carry additional operands that are not
7270   // set up by the default code above.
7271   switch (Opcode) {
7272   default: break;
7273   case ISD::STRICT_FP_ROUND:
7274     Opers.push_back(
7275         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7276     break;
7277   case ISD::STRICT_FSETCC:
7278   case ISD::STRICT_FSETCCS: {
7279     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7280     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7281     if (TM.Options.NoNaNsFPMath)
7282       Condition = getFCmpCodeWithoutNaN(Condition);
7283     Opers.push_back(DAG.getCondCode(Condition));
7284     break;
7285   }
7286   }
7287 
7288   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7289   pushOutChain(Result, EB);
7290 
7291   SDValue FPResult = Result.getValue(0);
7292   setValue(&FPI, FPResult);
7293 }
7294 
7295 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7296   Optional<unsigned> ResOPC;
7297   switch (VPIntrin.getIntrinsicID()) {
7298 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7299 #define BEGIN_REGISTER_VP_SDNODE(VPSD, ...) ResOPC = ISD::VPSD;
7300 #define END_REGISTER_VP_INTRINSIC(VPID) break;
7301 #include "llvm/IR/VPIntrinsics.def"
7302   }
7303 
7304   if (!ResOPC.hasValue())
7305     llvm_unreachable(
7306         "Inconsistency: no SDNode available for this VPIntrinsic!");
7307 
7308   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
7309       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
7310     if (VPIntrin.getFastMathFlags().allowReassoc())
7311       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
7312                                                 : ISD::VP_REDUCE_FMUL;
7313   }
7314 
7315   return ResOPC.getValue();
7316 }
7317 
7318 void SelectionDAGBuilder::visitVPLoadGather(const VPIntrinsic &VPIntrin, EVT VT,
7319                                             SmallVector<SDValue, 7> &OpValues,
7320                                             bool IsGather) {
7321   SDLoc DL = getCurSDLoc();
7322   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7323   Value *PtrOperand = VPIntrin.getArgOperand(0);
7324   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7325   if (!Alignment)
7326     Alignment = DAG.getEVTAlign(VT);
7327   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7328   const MDNode *Ranges = VPIntrin.getMetadata(LLVMContext::MD_range);
7329   SDValue LD;
7330   bool AddToChain = true;
7331   if (!IsGather) {
7332     // Do not serialize variable-length loads of constant memory with
7333     // anything.
7334     MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
7335     AddToChain = !AA || !AA->pointsToConstantMemory(ML);
7336     SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
7337     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7338         MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
7339         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7340     LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
7341                        MMO, false /*IsExpanding */);
7342   } else {
7343     unsigned AS =
7344         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7345     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7346         MachinePointerInfo(AS), MachineMemOperand::MOLoad,
7347         MemoryLocation::UnknownSize, *Alignment, AAInfo, Ranges);
7348     SDValue Base, Index, Scale;
7349     ISD::MemIndexType IndexType;
7350     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7351                                       this, VPIntrin.getParent());
7352     if (!UniformBase) {
7353       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7354       Index = getValue(PtrOperand);
7355       IndexType = ISD::SIGNED_UNSCALED;
7356       Scale =
7357           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7358     }
7359     EVT IdxVT = Index.getValueType();
7360     EVT EltTy = IdxVT.getVectorElementType();
7361     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7362       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7363       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7364     }
7365     LD = DAG.getGatherVP(
7366         DAG.getVTList(VT, MVT::Other), VT, DL,
7367         {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
7368         IndexType);
7369   }
7370   if (AddToChain)
7371     PendingLoads.push_back(LD.getValue(1));
7372   setValue(&VPIntrin, LD);
7373 }
7374 
7375 void SelectionDAGBuilder::visitVPStoreScatter(const VPIntrinsic &VPIntrin,
7376                                               SmallVector<SDValue, 7> &OpValues,
7377                                               bool IsScatter) {
7378   SDLoc DL = getCurSDLoc();
7379   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7380   Value *PtrOperand = VPIntrin.getArgOperand(1);
7381   EVT VT = OpValues[0].getValueType();
7382   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
7383   if (!Alignment)
7384     Alignment = DAG.getEVTAlign(VT);
7385   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
7386   SDValue ST;
7387   if (!IsScatter) {
7388     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7389         MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
7390         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7391     ST =
7392         DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], OpValues[1],
7393                        OpValues[2], OpValues[3], MMO, false /* IsTruncating */);
7394   } else {
7395     unsigned AS =
7396         PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
7397     MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7398         MachinePointerInfo(AS), MachineMemOperand::MOStore,
7399         MemoryLocation::UnknownSize, *Alignment, AAInfo);
7400     SDValue Base, Index, Scale;
7401     ISD::MemIndexType IndexType;
7402     bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
7403                                       this, VPIntrin.getParent());
7404     if (!UniformBase) {
7405       Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
7406       Index = getValue(PtrOperand);
7407       IndexType = ISD::SIGNED_UNSCALED;
7408       Scale =
7409           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
7410     }
7411     EVT IdxVT = Index.getValueType();
7412     EVT EltTy = IdxVT.getVectorElementType();
7413     if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
7414       EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
7415       Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
7416     }
7417     ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
7418                           {getMemoryRoot(), OpValues[0], Base, Index, Scale,
7419                            OpValues[2], OpValues[3]},
7420                           MMO, IndexType);
7421   }
7422   DAG.setRoot(ST);
7423   setValue(&VPIntrin, ST);
7424 }
7425 
7426 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7427     const VPIntrinsic &VPIntrin) {
7428   SDLoc DL = getCurSDLoc();
7429   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7430 
7431   SmallVector<EVT, 4> ValueVTs;
7432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7433   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7434   SDVTList VTs = DAG.getVTList(ValueVTs);
7435 
7436   auto EVLParamPos =
7437       VPIntrinsic::getVectorLengthParamPos(VPIntrin.getIntrinsicID());
7438 
7439   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
7440   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
7441          "Unexpected target EVL type");
7442 
7443   // Request operands.
7444   SmallVector<SDValue, 7> OpValues;
7445   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
7446     auto Op = getValue(VPIntrin.getArgOperand(I));
7447     if (I == EVLParamPos)
7448       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
7449     OpValues.push_back(Op);
7450   }
7451 
7452   switch (Opcode) {
7453   default: {
7454     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7455     setValue(&VPIntrin, Result);
7456     break;
7457   }
7458   case ISD::VP_LOAD:
7459   case ISD::VP_GATHER:
7460     visitVPLoadGather(VPIntrin, ValueVTs[0], OpValues,
7461                       Opcode == ISD::VP_GATHER);
7462     break;
7463   case ISD::VP_STORE:
7464   case ISD::VP_SCATTER:
7465     visitVPStoreScatter(VPIntrin, OpValues, Opcode == ISD::VP_SCATTER);
7466     break;
7467   }
7468 }
7469 
7470 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
7471                                           const BasicBlock *EHPadBB,
7472                                           MCSymbol *&BeginLabel) {
7473   MachineFunction &MF = DAG.getMachineFunction();
7474   MachineModuleInfo &MMI = MF.getMMI();
7475 
7476   // Insert a label before the invoke call to mark the try range.  This can be
7477   // used to detect deletion of the invoke via the MachineModuleInfo.
7478   BeginLabel = MMI.getContext().createTempSymbol();
7479 
7480   // For SjLj, keep track of which landing pads go with which invokes
7481   // so as to maintain the ordering of pads in the LSDA.
7482   unsigned CallSiteIndex = MMI.getCurrentCallSite();
7483   if (CallSiteIndex) {
7484     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7485     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7486 
7487     // Now that the call site is handled, stop tracking it.
7488     MMI.setCurrentCallSite(0);
7489   }
7490 
7491   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
7492 }
7493 
7494 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
7495                                         const BasicBlock *EHPadBB,
7496                                         MCSymbol *BeginLabel) {
7497   assert(BeginLabel && "BeginLabel should've been set");
7498 
7499   MachineFunction &MF = DAG.getMachineFunction();
7500   MachineModuleInfo &MMI = MF.getMMI();
7501 
7502   // Insert a label at the end of the invoke call to mark the try range.  This
7503   // can be used to detect deletion of the invoke via the MachineModuleInfo.
7504   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7505   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
7506 
7507   // Inform MachineModuleInfo of range.
7508   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7509   // There is a platform (e.g. wasm) that uses funclet style IR but does not
7510   // actually use outlined funclets and their LSDA info style.
7511   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7512     assert(II && "II should've been set");
7513     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
7514     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
7515   } else if (!isScopedEHPersonality(Pers)) {
7516     assert(EHPadBB);
7517     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7518   }
7519 
7520   return Chain;
7521 }
7522 
7523 std::pair<SDValue, SDValue>
7524 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7525                                     const BasicBlock *EHPadBB) {
7526   MCSymbol *BeginLabel = nullptr;
7527 
7528   if (EHPadBB) {
7529     // Both PendingLoads and PendingExports must be flushed here;
7530     // this call might not return.
7531     (void)getRoot();
7532     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
7533     CLI.setChain(getRoot());
7534   }
7535 
7536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7537   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7538 
7539   assert((CLI.IsTailCall || Result.second.getNode()) &&
7540          "Non-null chain expected with non-tail call!");
7541   assert((Result.second.getNode() || !Result.first.getNode()) &&
7542          "Null value expected with tail call!");
7543 
7544   if (!Result.second.getNode()) {
7545     // As a special case, a null chain means that a tail call has been emitted
7546     // and the DAG root is already updated.
7547     HasTailCall = true;
7548 
7549     // Since there's no actual continuation from this block, nothing can be
7550     // relying on us setting vregs for them.
7551     PendingExports.clear();
7552   } else {
7553     DAG.setRoot(Result.second);
7554   }
7555 
7556   if (EHPadBB) {
7557     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
7558                            BeginLabel));
7559   }
7560 
7561   return Result;
7562 }
7563 
7564 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7565                                       bool isTailCall,
7566                                       bool isMustTailCall,
7567                                       const BasicBlock *EHPadBB) {
7568   auto &DL = DAG.getDataLayout();
7569   FunctionType *FTy = CB.getFunctionType();
7570   Type *RetTy = CB.getType();
7571 
7572   TargetLowering::ArgListTy Args;
7573   Args.reserve(CB.arg_size());
7574 
7575   const Value *SwiftErrorVal = nullptr;
7576   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7577 
7578   if (isTailCall) {
7579     // Avoid emitting tail calls in functions with the disable-tail-calls
7580     // attribute.
7581     auto *Caller = CB.getParent()->getParent();
7582     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7583         "true" && !isMustTailCall)
7584       isTailCall = false;
7585 
7586     // We can't tail call inside a function with a swifterror argument. Lowering
7587     // does not support this yet. It would have to move into the swifterror
7588     // register before the call.
7589     if (TLI.supportSwiftError() &&
7590         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7591       isTailCall = false;
7592   }
7593 
7594   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7595     TargetLowering::ArgListEntry Entry;
7596     const Value *V = *I;
7597 
7598     // Skip empty types
7599     if (V->getType()->isEmptyTy())
7600       continue;
7601 
7602     SDValue ArgNode = getValue(V);
7603     Entry.Node = ArgNode; Entry.Ty = V->getType();
7604 
7605     Entry.setAttributes(&CB, I - CB.arg_begin());
7606 
7607     // Use swifterror virtual register as input to the call.
7608     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7609       SwiftErrorVal = V;
7610       // We find the virtual register for the actual swifterror argument.
7611       // Instead of using the Value, we use the virtual register instead.
7612       Entry.Node =
7613           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7614                           EVT(TLI.getPointerTy(DL)));
7615     }
7616 
7617     Args.push_back(Entry);
7618 
7619     // If we have an explicit sret argument that is an Instruction, (i.e., it
7620     // might point to function-local memory), we can't meaningfully tail-call.
7621     if (Entry.IsSRet && isa<Instruction>(V))
7622       isTailCall = false;
7623   }
7624 
7625   // If call site has a cfguardtarget operand bundle, create and add an
7626   // additional ArgListEntry.
7627   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7628     TargetLowering::ArgListEntry Entry;
7629     Value *V = Bundle->Inputs[0];
7630     SDValue ArgNode = getValue(V);
7631     Entry.Node = ArgNode;
7632     Entry.Ty = V->getType();
7633     Entry.IsCFGuardTarget = true;
7634     Args.push_back(Entry);
7635   }
7636 
7637   // Check if target-independent constraints permit a tail call here.
7638   // Target-dependent constraints are checked within TLI->LowerCallTo.
7639   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7640     isTailCall = false;
7641 
7642   // Disable tail calls if there is an swifterror argument. Targets have not
7643   // been updated to support tail calls.
7644   if (TLI.supportSwiftError() && SwiftErrorVal)
7645     isTailCall = false;
7646 
7647   TargetLowering::CallLoweringInfo CLI(DAG);
7648   CLI.setDebugLoc(getCurSDLoc())
7649       .setChain(getRoot())
7650       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7651       .setTailCall(isTailCall)
7652       .setConvergent(CB.isConvergent())
7653       .setIsPreallocated(
7654           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7655   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7656 
7657   if (Result.first.getNode()) {
7658     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7659     setValue(&CB, Result.first);
7660   }
7661 
7662   // The last element of CLI.InVals has the SDValue for swifterror return.
7663   // Here we copy it to a virtual register and update SwiftErrorMap for
7664   // book-keeping.
7665   if (SwiftErrorVal && TLI.supportSwiftError()) {
7666     // Get the last element of InVals.
7667     SDValue Src = CLI.InVals.back();
7668     Register VReg =
7669         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7670     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7671     DAG.setRoot(CopyNode);
7672   }
7673 }
7674 
7675 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7676                              SelectionDAGBuilder &Builder) {
7677   // Check to see if this load can be trivially constant folded, e.g. if the
7678   // input is from a string literal.
7679   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7680     // Cast pointer to the type we really want to load.
7681     Type *LoadTy =
7682         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7683     if (LoadVT.isVector())
7684       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7685 
7686     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7687                                          PointerType::getUnqual(LoadTy));
7688 
7689     if (const Constant *LoadCst =
7690             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
7691                                          LoadTy, Builder.DAG.getDataLayout()))
7692       return Builder.getValue(LoadCst);
7693   }
7694 
7695   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7696   // still constant memory, the input chain can be the entry node.
7697   SDValue Root;
7698   bool ConstantMemory = false;
7699 
7700   // Do not serialize (non-volatile) loads of constant memory with anything.
7701   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7702     Root = Builder.DAG.getEntryNode();
7703     ConstantMemory = true;
7704   } else {
7705     // Do not serialize non-volatile loads against each other.
7706     Root = Builder.DAG.getRoot();
7707   }
7708 
7709   SDValue Ptr = Builder.getValue(PtrVal);
7710   SDValue LoadVal =
7711       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7712                           MachinePointerInfo(PtrVal), Align(1));
7713 
7714   if (!ConstantMemory)
7715     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7716   return LoadVal;
7717 }
7718 
7719 /// Record the value for an instruction that produces an integer result,
7720 /// converting the type where necessary.
7721 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7722                                                   SDValue Value,
7723                                                   bool IsSigned) {
7724   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7725                                                     I.getType(), true);
7726   if (IsSigned)
7727     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7728   else
7729     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7730   setValue(&I, Value);
7731 }
7732 
7733 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7734 /// true and lower it. Otherwise return false, and it will be lowered like a
7735 /// normal call.
7736 /// The caller already checked that \p I calls the appropriate LibFunc with a
7737 /// correct prototype.
7738 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7739   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7740   const Value *Size = I.getArgOperand(2);
7741   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7742   if (CSize && CSize->getZExtValue() == 0) {
7743     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7744                                                           I.getType(), true);
7745     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7746     return true;
7747   }
7748 
7749   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7750   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7751       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7752       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7753   if (Res.first.getNode()) {
7754     processIntegerCallValue(I, Res.first, true);
7755     PendingLoads.push_back(Res.second);
7756     return true;
7757   }
7758 
7759   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7760   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7761   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7762     return false;
7763 
7764   // If the target has a fast compare for the given size, it will return a
7765   // preferred load type for that size. Require that the load VT is legal and
7766   // that the target supports unaligned loads of that type. Otherwise, return
7767   // INVALID.
7768   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7769     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7770     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7771     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7772       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7773       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7774       // TODO: Check alignment of src and dest ptrs.
7775       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7776       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7777       if (!TLI.isTypeLegal(LVT) ||
7778           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7779           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7780         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7781     }
7782 
7783     return LVT;
7784   };
7785 
7786   // This turns into unaligned loads. We only do this if the target natively
7787   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7788   // we'll only produce a small number of byte loads.
7789   MVT LoadVT;
7790   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7791   switch (NumBitsToCompare) {
7792   default:
7793     return false;
7794   case 16:
7795     LoadVT = MVT::i16;
7796     break;
7797   case 32:
7798     LoadVT = MVT::i32;
7799     break;
7800   case 64:
7801   case 128:
7802   case 256:
7803     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7804     break;
7805   }
7806 
7807   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7808     return false;
7809 
7810   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7811   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7812 
7813   // Bitcast to a wide integer type if the loads are vectors.
7814   if (LoadVT.isVector()) {
7815     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7816     LoadL = DAG.getBitcast(CmpVT, LoadL);
7817     LoadR = DAG.getBitcast(CmpVT, LoadR);
7818   }
7819 
7820   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7821   processIntegerCallValue(I, Cmp, false);
7822   return true;
7823 }
7824 
7825 /// See if we can lower a memchr call into an optimized form. If so, return
7826 /// true and lower it. Otherwise return false, and it will be lowered like a
7827 /// normal call.
7828 /// The caller already checked that \p I calls the appropriate LibFunc with a
7829 /// correct prototype.
7830 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7831   const Value *Src = I.getArgOperand(0);
7832   const Value *Char = I.getArgOperand(1);
7833   const Value *Length = I.getArgOperand(2);
7834 
7835   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7836   std::pair<SDValue, SDValue> Res =
7837     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7838                                 getValue(Src), getValue(Char), getValue(Length),
7839                                 MachinePointerInfo(Src));
7840   if (Res.first.getNode()) {
7841     setValue(&I, Res.first);
7842     PendingLoads.push_back(Res.second);
7843     return true;
7844   }
7845 
7846   return false;
7847 }
7848 
7849 /// See if we can lower a mempcpy call into an optimized form. If so, return
7850 /// true and lower it. Otherwise return false, and it will be lowered like a
7851 /// normal call.
7852 /// The caller already checked that \p I calls the appropriate LibFunc with a
7853 /// correct prototype.
7854 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7855   SDValue Dst = getValue(I.getArgOperand(0));
7856   SDValue Src = getValue(I.getArgOperand(1));
7857   SDValue Size = getValue(I.getArgOperand(2));
7858 
7859   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7860   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7861   // DAG::getMemcpy needs Alignment to be defined.
7862   Align Alignment = std::min(DstAlign, SrcAlign);
7863 
7864   bool isVol = false;
7865   SDLoc sdl = getCurSDLoc();
7866 
7867   // In the mempcpy context we need to pass in a false value for isTailCall
7868   // because the return pointer needs to be adjusted by the size of
7869   // the copied memory.
7870   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7871   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7872                              /*isTailCall=*/false,
7873                              MachinePointerInfo(I.getArgOperand(0)),
7874                              MachinePointerInfo(I.getArgOperand(1)),
7875                              I.getAAMetadata());
7876   assert(MC.getNode() != nullptr &&
7877          "** memcpy should not be lowered as TailCall in mempcpy context **");
7878   DAG.setRoot(MC);
7879 
7880   // Check if Size needs to be truncated or extended.
7881   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7882 
7883   // Adjust return pointer to point just past the last dst byte.
7884   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7885                                     Dst, Size);
7886   setValue(&I, DstPlusSize);
7887   return true;
7888 }
7889 
7890 /// See if we can lower a strcpy call into an optimized form.  If so, return
7891 /// true and lower it, otherwise return false and it will be lowered like a
7892 /// normal call.
7893 /// The caller already checked that \p I calls the appropriate LibFunc with a
7894 /// correct prototype.
7895 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7896   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7897 
7898   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7899   std::pair<SDValue, SDValue> Res =
7900     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7901                                 getValue(Arg0), getValue(Arg1),
7902                                 MachinePointerInfo(Arg0),
7903                                 MachinePointerInfo(Arg1), isStpcpy);
7904   if (Res.first.getNode()) {
7905     setValue(&I, Res.first);
7906     DAG.setRoot(Res.second);
7907     return true;
7908   }
7909 
7910   return false;
7911 }
7912 
7913 /// See if we can lower a strcmp call into an optimized form.  If so, return
7914 /// true and lower it, otherwise return false and it will be lowered like a
7915 /// normal call.
7916 /// The caller already checked that \p I calls the appropriate LibFunc with a
7917 /// correct prototype.
7918 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7919   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7920 
7921   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7922   std::pair<SDValue, SDValue> Res =
7923     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7924                                 getValue(Arg0), getValue(Arg1),
7925                                 MachinePointerInfo(Arg0),
7926                                 MachinePointerInfo(Arg1));
7927   if (Res.first.getNode()) {
7928     processIntegerCallValue(I, Res.first, true);
7929     PendingLoads.push_back(Res.second);
7930     return true;
7931   }
7932 
7933   return false;
7934 }
7935 
7936 /// See if we can lower a strlen call into an optimized form.  If so, return
7937 /// true and lower it, otherwise return false and it will be lowered like a
7938 /// normal call.
7939 /// The caller already checked that \p I calls the appropriate LibFunc with a
7940 /// correct prototype.
7941 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7942   const Value *Arg0 = I.getArgOperand(0);
7943 
7944   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7945   std::pair<SDValue, SDValue> Res =
7946     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7947                                 getValue(Arg0), MachinePointerInfo(Arg0));
7948   if (Res.first.getNode()) {
7949     processIntegerCallValue(I, Res.first, false);
7950     PendingLoads.push_back(Res.second);
7951     return true;
7952   }
7953 
7954   return false;
7955 }
7956 
7957 /// See if we can lower a strnlen call into an optimized form.  If so, return
7958 /// true and lower it, otherwise return false and it will be lowered like a
7959 /// normal call.
7960 /// The caller already checked that \p I calls the appropriate LibFunc with a
7961 /// correct prototype.
7962 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7963   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7964 
7965   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7966   std::pair<SDValue, SDValue> Res =
7967     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7968                                  getValue(Arg0), getValue(Arg1),
7969                                  MachinePointerInfo(Arg0));
7970   if (Res.first.getNode()) {
7971     processIntegerCallValue(I, Res.first, false);
7972     PendingLoads.push_back(Res.second);
7973     return true;
7974   }
7975 
7976   return false;
7977 }
7978 
7979 /// See if we can lower a unary floating-point operation into an SDNode with
7980 /// the specified Opcode.  If so, return true and lower it, otherwise return
7981 /// false and it will be lowered like a normal call.
7982 /// The caller already checked that \p I calls the appropriate LibFunc with a
7983 /// correct prototype.
7984 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7985                                               unsigned Opcode) {
7986   // We already checked this call's prototype; verify it doesn't modify errno.
7987   if (!I.onlyReadsMemory())
7988     return false;
7989 
7990   SDNodeFlags Flags;
7991   Flags.copyFMF(cast<FPMathOperator>(I));
7992 
7993   SDValue Tmp = getValue(I.getArgOperand(0));
7994   setValue(&I,
7995            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7996   return true;
7997 }
7998 
7999 /// See if we can lower a binary floating-point operation into an SDNode with
8000 /// the specified Opcode. If so, return true and lower it. Otherwise return
8001 /// false, and it will be lowered like a normal call.
8002 /// The caller already checked that \p I calls the appropriate LibFunc with a
8003 /// correct prototype.
8004 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8005                                                unsigned Opcode) {
8006   // We already checked this call's prototype; verify it doesn't modify errno.
8007   if (!I.onlyReadsMemory())
8008     return false;
8009 
8010   SDNodeFlags Flags;
8011   Flags.copyFMF(cast<FPMathOperator>(I));
8012 
8013   SDValue Tmp0 = getValue(I.getArgOperand(0));
8014   SDValue Tmp1 = getValue(I.getArgOperand(1));
8015   EVT VT = Tmp0.getValueType();
8016   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8017   return true;
8018 }
8019 
8020 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8021   // Handle inline assembly differently.
8022   if (I.isInlineAsm()) {
8023     visitInlineAsm(I);
8024     return;
8025   }
8026 
8027   if (Function *F = I.getCalledFunction()) {
8028     diagnoseDontCall(I);
8029 
8030     if (F->isDeclaration()) {
8031       // Is this an LLVM intrinsic or a target-specific intrinsic?
8032       unsigned IID = F->getIntrinsicID();
8033       if (!IID)
8034         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
8035           IID = II->getIntrinsicID(F);
8036 
8037       if (IID) {
8038         visitIntrinsicCall(I, IID);
8039         return;
8040       }
8041     }
8042 
8043     // Check for well-known libc/libm calls.  If the function is internal, it
8044     // can't be a library call.  Don't do the check if marked as nobuiltin for
8045     // some reason or the call site requires strict floating point semantics.
8046     LibFunc Func;
8047     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
8048         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
8049         LibInfo->hasOptimizedCodeGen(Func)) {
8050       switch (Func) {
8051       default: break;
8052       case LibFunc_bcmp:
8053         if (visitMemCmpBCmpCall(I))
8054           return;
8055         break;
8056       case LibFunc_copysign:
8057       case LibFunc_copysignf:
8058       case LibFunc_copysignl:
8059         // We already checked this call's prototype; verify it doesn't modify
8060         // errno.
8061         if (I.onlyReadsMemory()) {
8062           SDValue LHS = getValue(I.getArgOperand(0));
8063           SDValue RHS = getValue(I.getArgOperand(1));
8064           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
8065                                    LHS.getValueType(), LHS, RHS));
8066           return;
8067         }
8068         break;
8069       case LibFunc_fabs:
8070       case LibFunc_fabsf:
8071       case LibFunc_fabsl:
8072         if (visitUnaryFloatCall(I, ISD::FABS))
8073           return;
8074         break;
8075       case LibFunc_fmin:
8076       case LibFunc_fminf:
8077       case LibFunc_fminl:
8078         if (visitBinaryFloatCall(I, ISD::FMINNUM))
8079           return;
8080         break;
8081       case LibFunc_fmax:
8082       case LibFunc_fmaxf:
8083       case LibFunc_fmaxl:
8084         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
8085           return;
8086         break;
8087       case LibFunc_sin:
8088       case LibFunc_sinf:
8089       case LibFunc_sinl:
8090         if (visitUnaryFloatCall(I, ISD::FSIN))
8091           return;
8092         break;
8093       case LibFunc_cos:
8094       case LibFunc_cosf:
8095       case LibFunc_cosl:
8096         if (visitUnaryFloatCall(I, ISD::FCOS))
8097           return;
8098         break;
8099       case LibFunc_sqrt:
8100       case LibFunc_sqrtf:
8101       case LibFunc_sqrtl:
8102       case LibFunc_sqrt_finite:
8103       case LibFunc_sqrtf_finite:
8104       case LibFunc_sqrtl_finite:
8105         if (visitUnaryFloatCall(I, ISD::FSQRT))
8106           return;
8107         break;
8108       case LibFunc_floor:
8109       case LibFunc_floorf:
8110       case LibFunc_floorl:
8111         if (visitUnaryFloatCall(I, ISD::FFLOOR))
8112           return;
8113         break;
8114       case LibFunc_nearbyint:
8115       case LibFunc_nearbyintf:
8116       case LibFunc_nearbyintl:
8117         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
8118           return;
8119         break;
8120       case LibFunc_ceil:
8121       case LibFunc_ceilf:
8122       case LibFunc_ceill:
8123         if (visitUnaryFloatCall(I, ISD::FCEIL))
8124           return;
8125         break;
8126       case LibFunc_rint:
8127       case LibFunc_rintf:
8128       case LibFunc_rintl:
8129         if (visitUnaryFloatCall(I, ISD::FRINT))
8130           return;
8131         break;
8132       case LibFunc_round:
8133       case LibFunc_roundf:
8134       case LibFunc_roundl:
8135         if (visitUnaryFloatCall(I, ISD::FROUND))
8136           return;
8137         break;
8138       case LibFunc_trunc:
8139       case LibFunc_truncf:
8140       case LibFunc_truncl:
8141         if (visitUnaryFloatCall(I, ISD::FTRUNC))
8142           return;
8143         break;
8144       case LibFunc_log2:
8145       case LibFunc_log2f:
8146       case LibFunc_log2l:
8147         if (visitUnaryFloatCall(I, ISD::FLOG2))
8148           return;
8149         break;
8150       case LibFunc_exp2:
8151       case LibFunc_exp2f:
8152       case LibFunc_exp2l:
8153         if (visitUnaryFloatCall(I, ISD::FEXP2))
8154           return;
8155         break;
8156       case LibFunc_memcmp:
8157         if (visitMemCmpBCmpCall(I))
8158           return;
8159         break;
8160       case LibFunc_mempcpy:
8161         if (visitMemPCpyCall(I))
8162           return;
8163         break;
8164       case LibFunc_memchr:
8165         if (visitMemChrCall(I))
8166           return;
8167         break;
8168       case LibFunc_strcpy:
8169         if (visitStrCpyCall(I, false))
8170           return;
8171         break;
8172       case LibFunc_stpcpy:
8173         if (visitStrCpyCall(I, true))
8174           return;
8175         break;
8176       case LibFunc_strcmp:
8177         if (visitStrCmpCall(I))
8178           return;
8179         break;
8180       case LibFunc_strlen:
8181         if (visitStrLenCall(I))
8182           return;
8183         break;
8184       case LibFunc_strnlen:
8185         if (visitStrNLenCall(I))
8186           return;
8187         break;
8188       }
8189     }
8190   }
8191 
8192   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
8193   // have to do anything here to lower funclet bundles.
8194   // CFGuardTarget bundles are lowered in LowerCallTo.
8195   assert(!I.hasOperandBundlesOtherThan(
8196              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
8197               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
8198               LLVMContext::OB_clang_arc_attachedcall}) &&
8199          "Cannot lower calls with arbitrary operand bundles!");
8200 
8201   SDValue Callee = getValue(I.getCalledOperand());
8202 
8203   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
8204     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
8205   else
8206     // Check if we can potentially perform a tail call. More detailed checking
8207     // is be done within LowerCallTo, after more information about the call is
8208     // known.
8209     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
8210 }
8211 
8212 namespace {
8213 
8214 /// AsmOperandInfo - This contains information for each constraint that we are
8215 /// lowering.
8216 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
8217 public:
8218   /// CallOperand - If this is the result output operand or a clobber
8219   /// this is null, otherwise it is the incoming operand to the CallInst.
8220   /// This gets modified as the asm is processed.
8221   SDValue CallOperand;
8222 
8223   /// AssignedRegs - If this is a register or register class operand, this
8224   /// contains the set of register corresponding to the operand.
8225   RegsForValue AssignedRegs;
8226 
8227   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
8228     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
8229   }
8230 
8231   /// Whether or not this operand accesses memory
8232   bool hasMemory(const TargetLowering &TLI) const {
8233     // Indirect operand accesses access memory.
8234     if (isIndirect)
8235       return true;
8236 
8237     for (const auto &Code : Codes)
8238       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
8239         return true;
8240 
8241     return false;
8242   }
8243 
8244   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
8245   /// corresponds to.  If there is no Value* for this operand, it returns
8246   /// MVT::Other.
8247   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
8248                            const DataLayout &DL) const {
8249     if (!CallOperandVal) return MVT::Other;
8250 
8251     if (isa<BasicBlock>(CallOperandVal))
8252       return TLI.getProgramPointerTy(DL);
8253 
8254     llvm::Type *OpTy = CallOperandVal->getType();
8255 
8256     // FIXME: code duplicated from TargetLowering::ParseConstraints().
8257     // If this is an indirect operand, the operand is a pointer to the
8258     // accessed type.
8259     if (isIndirect) {
8260       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
8261       if (!PtrTy)
8262         report_fatal_error("Indirect operand for inline asm not a pointer!");
8263       OpTy = PtrTy->getElementType();
8264     }
8265 
8266     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
8267     if (StructType *STy = dyn_cast<StructType>(OpTy))
8268       if (STy->getNumElements() == 1)
8269         OpTy = STy->getElementType(0);
8270 
8271     // If OpTy is not a single value, it may be a struct/union that we
8272     // can tile with integers.
8273     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
8274       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
8275       switch (BitSize) {
8276       default: break;
8277       case 1:
8278       case 8:
8279       case 16:
8280       case 32:
8281       case 64:
8282       case 128:
8283         OpTy = IntegerType::get(Context, BitSize);
8284         break;
8285       }
8286     }
8287 
8288     return TLI.getAsmOperandValueType(DL, OpTy, true);
8289   }
8290 };
8291 
8292 
8293 } // end anonymous namespace
8294 
8295 /// Make sure that the output operand \p OpInfo and its corresponding input
8296 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
8297 /// out).
8298 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
8299                                SDISelAsmOperandInfo &MatchingOpInfo,
8300                                SelectionDAG &DAG) {
8301   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
8302     return;
8303 
8304   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
8305   const auto &TLI = DAG.getTargetLoweringInfo();
8306 
8307   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
8308       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
8309                                        OpInfo.ConstraintVT);
8310   std::pair<unsigned, const TargetRegisterClass *> InputRC =
8311       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
8312                                        MatchingOpInfo.ConstraintVT);
8313   if ((OpInfo.ConstraintVT.isInteger() !=
8314        MatchingOpInfo.ConstraintVT.isInteger()) ||
8315       (MatchRC.second != InputRC.second)) {
8316     // FIXME: error out in a more elegant fashion
8317     report_fatal_error("Unsupported asm: input constraint"
8318                        " with a matching output constraint of"
8319                        " incompatible type!");
8320   }
8321   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8322 }
8323 
8324 /// Get a direct memory input to behave well as an indirect operand.
8325 /// This may introduce stores, hence the need for a \p Chain.
8326 /// \return The (possibly updated) chain.
8327 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8328                                         SDISelAsmOperandInfo &OpInfo,
8329                                         SelectionDAG &DAG) {
8330   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8331 
8332   // If we don't have an indirect input, put it in the constpool if we can,
8333   // otherwise spill it to a stack slot.
8334   // TODO: This isn't quite right. We need to handle these according to
8335   // the addressing mode that the constraint wants. Also, this may take
8336   // an additional register for the computation and we don't want that
8337   // either.
8338 
8339   // If the operand is a float, integer, or vector constant, spill to a
8340   // constant pool entry to get its address.
8341   const Value *OpVal = OpInfo.CallOperandVal;
8342   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8343       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8344     OpInfo.CallOperand = DAG.getConstantPool(
8345         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8346     return Chain;
8347   }
8348 
8349   // Otherwise, create a stack slot and emit a store to it before the asm.
8350   Type *Ty = OpVal->getType();
8351   auto &DL = DAG.getDataLayout();
8352   uint64_t TySize = DL.getTypeAllocSize(Ty);
8353   MachineFunction &MF = DAG.getMachineFunction();
8354   int SSFI = MF.getFrameInfo().CreateStackObject(
8355       TySize, DL.getPrefTypeAlign(Ty), false);
8356   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8357   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8358                             MachinePointerInfo::getFixedStack(MF, SSFI),
8359                             TLI.getMemValueType(DL, Ty));
8360   OpInfo.CallOperand = StackSlot;
8361 
8362   return Chain;
8363 }
8364 
8365 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8366 /// specified operand.  We prefer to assign virtual registers, to allow the
8367 /// register allocator to handle the assignment process.  However, if the asm
8368 /// uses features that we can't model on machineinstrs, we have SDISel do the
8369 /// allocation.  This produces generally horrible, but correct, code.
8370 ///
8371 ///   OpInfo describes the operand
8372 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8373 static llvm::Optional<unsigned>
8374 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8375                      SDISelAsmOperandInfo &OpInfo,
8376                      SDISelAsmOperandInfo &RefOpInfo) {
8377   LLVMContext &Context = *DAG.getContext();
8378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8379 
8380   MachineFunction &MF = DAG.getMachineFunction();
8381   SmallVector<unsigned, 4> Regs;
8382   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8383 
8384   // No work to do for memory operations.
8385   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8386     return None;
8387 
8388   // If this is a constraint for a single physreg, or a constraint for a
8389   // register class, find it.
8390   unsigned AssignedReg;
8391   const TargetRegisterClass *RC;
8392   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8393       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8394   // RC is unset only on failure. Return immediately.
8395   if (!RC)
8396     return None;
8397 
8398   // Get the actual register value type.  This is important, because the user
8399   // may have asked for (e.g.) the AX register in i32 type.  We need to
8400   // remember that AX is actually i16 to get the right extension.
8401   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8402 
8403   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
8404     // If this is an FP operand in an integer register (or visa versa), or more
8405     // generally if the operand value disagrees with the register class we plan
8406     // to stick it in, fix the operand type.
8407     //
8408     // If this is an input value, the bitcast to the new type is done now.
8409     // Bitcast for output value is done at the end of visitInlineAsm().
8410     if ((OpInfo.Type == InlineAsm::isOutput ||
8411          OpInfo.Type == InlineAsm::isInput) &&
8412         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8413       // Try to convert to the first EVT that the reg class contains.  If the
8414       // types are identical size, use a bitcast to convert (e.g. two differing
8415       // vector types).  Note: output bitcast is done at the end of
8416       // visitInlineAsm().
8417       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8418         // Exclude indirect inputs while they are unsupported because the code
8419         // to perform the load is missing and thus OpInfo.CallOperand still
8420         // refers to the input address rather than the pointed-to value.
8421         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8422           OpInfo.CallOperand =
8423               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8424         OpInfo.ConstraintVT = RegVT;
8425         // If the operand is an FP value and we want it in integer registers,
8426         // use the corresponding integer type. This turns an f64 value into
8427         // i64, which can be passed with two i32 values on a 32-bit machine.
8428       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8429         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8430         if (OpInfo.Type == InlineAsm::isInput)
8431           OpInfo.CallOperand =
8432               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8433         OpInfo.ConstraintVT = VT;
8434       }
8435     }
8436   }
8437 
8438   // No need to allocate a matching input constraint since the constraint it's
8439   // matching to has already been allocated.
8440   if (OpInfo.isMatchingInputConstraint())
8441     return None;
8442 
8443   EVT ValueVT = OpInfo.ConstraintVT;
8444   if (OpInfo.ConstraintVT == MVT::Other)
8445     ValueVT = RegVT;
8446 
8447   // Initialize NumRegs.
8448   unsigned NumRegs = 1;
8449   if (OpInfo.ConstraintVT != MVT::Other)
8450     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
8451 
8452   // If this is a constraint for a specific physical register, like {r17},
8453   // assign it now.
8454 
8455   // If this associated to a specific register, initialize iterator to correct
8456   // place. If virtual, make sure we have enough registers
8457 
8458   // Initialize iterator if necessary
8459   TargetRegisterClass::iterator I = RC->begin();
8460   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8461 
8462   // Do not check for single registers.
8463   if (AssignedReg) {
8464     I = std::find(I, RC->end(), AssignedReg);
8465     if (I == RC->end()) {
8466       // RC does not contain the selected register, which indicates a
8467       // mismatch between the register and the required type/bitwidth.
8468       return {AssignedReg};
8469     }
8470   }
8471 
8472   for (; NumRegs; --NumRegs, ++I) {
8473     assert(I != RC->end() && "Ran out of registers to allocate!");
8474     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8475     Regs.push_back(R);
8476   }
8477 
8478   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8479   return None;
8480 }
8481 
8482 static unsigned
8483 findMatchingInlineAsmOperand(unsigned OperandNo,
8484                              const std::vector<SDValue> &AsmNodeOperands) {
8485   // Scan until we find the definition we already emitted of this operand.
8486   unsigned CurOp = InlineAsm::Op_FirstOperand;
8487   for (; OperandNo; --OperandNo) {
8488     // Advance to the next operand.
8489     unsigned OpFlag =
8490         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8491     assert((InlineAsm::isRegDefKind(OpFlag) ||
8492             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8493             InlineAsm::isMemKind(OpFlag)) &&
8494            "Skipped past definitions?");
8495     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8496   }
8497   return CurOp;
8498 }
8499 
8500 namespace {
8501 
8502 class ExtraFlags {
8503   unsigned Flags = 0;
8504 
8505 public:
8506   explicit ExtraFlags(const CallBase &Call) {
8507     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8508     if (IA->hasSideEffects())
8509       Flags |= InlineAsm::Extra_HasSideEffects;
8510     if (IA->isAlignStack())
8511       Flags |= InlineAsm::Extra_IsAlignStack;
8512     if (Call.isConvergent())
8513       Flags |= InlineAsm::Extra_IsConvergent;
8514     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8515   }
8516 
8517   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8518     // Ideally, we would only check against memory constraints.  However, the
8519     // meaning of an Other constraint can be target-specific and we can't easily
8520     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8521     // for Other constraints as well.
8522     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8523         OpInfo.ConstraintType == TargetLowering::C_Other) {
8524       if (OpInfo.Type == InlineAsm::isInput)
8525         Flags |= InlineAsm::Extra_MayLoad;
8526       else if (OpInfo.Type == InlineAsm::isOutput)
8527         Flags |= InlineAsm::Extra_MayStore;
8528       else if (OpInfo.Type == InlineAsm::isClobber)
8529         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8530     }
8531   }
8532 
8533   unsigned get() const { return Flags; }
8534 };
8535 
8536 } // end anonymous namespace
8537 
8538 /// visitInlineAsm - Handle a call to an InlineAsm object.
8539 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
8540                                          const BasicBlock *EHPadBB) {
8541   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8542 
8543   /// ConstraintOperands - Information about all of the constraints.
8544   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8545 
8546   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8547   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8548       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8549 
8550   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8551   // AsmDialect, MayLoad, MayStore).
8552   bool HasSideEffect = IA->hasSideEffects();
8553   ExtraFlags ExtraInfo(Call);
8554 
8555   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8556   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8557   unsigned NumMatchingOps = 0;
8558   for (auto &T : TargetConstraints) {
8559     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8560     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8561 
8562     // Compute the value type for each operand.
8563     if (OpInfo.Type == InlineAsm::isInput ||
8564         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8565       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8566 
8567       // Process the call argument. BasicBlocks are labels, currently appearing
8568       // only in asm's.
8569       if (isa<CallBrInst>(Call) &&
8570           ArgNo - 1 >= (cast<CallBrInst>(&Call)->arg_size() -
8571                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8572                         NumMatchingOps) &&
8573           (NumMatchingOps == 0 ||
8574            ArgNo - 1 <
8575                (cast<CallBrInst>(&Call)->arg_size() - NumMatchingOps))) {
8576         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8577         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8578         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8579       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8580         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8581       } else {
8582         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8583       }
8584 
8585       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8586                                            DAG.getDataLayout());
8587       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8588     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8589       // The return value of the call is this value.  As such, there is no
8590       // corresponding argument.
8591       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8592       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8593         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8594             DAG.getDataLayout(), STy->getElementType(ResNo));
8595       } else {
8596         assert(ResNo == 0 && "Asm only has one result!");
8597         OpInfo.ConstraintVT = TLI.getAsmOperandValueType(
8598             DAG.getDataLayout(), Call.getType()).getSimpleVT();
8599       }
8600       ++ResNo;
8601     } else {
8602       OpInfo.ConstraintVT = MVT::Other;
8603     }
8604 
8605     if (OpInfo.hasMatchingInput())
8606       ++NumMatchingOps;
8607 
8608     if (!HasSideEffect)
8609       HasSideEffect = OpInfo.hasMemory(TLI);
8610 
8611     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8612     // FIXME: Could we compute this on OpInfo rather than T?
8613 
8614     // Compute the constraint code and ConstraintType to use.
8615     TLI.ComputeConstraintToUse(T, SDValue());
8616 
8617     if (T.ConstraintType == TargetLowering::C_Immediate &&
8618         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8619       // We've delayed emitting a diagnostic like the "n" constraint because
8620       // inlining could cause an integer showing up.
8621       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8622                                           "' expects an integer constant "
8623                                           "expression");
8624 
8625     ExtraInfo.update(T);
8626   }
8627 
8628   // We won't need to flush pending loads if this asm doesn't touch
8629   // memory and is nonvolatile.
8630   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8631 
8632   bool EmitEHLabels = isa<InvokeInst>(Call) && IA->canThrow();
8633   if (EmitEHLabels) {
8634     assert(EHPadBB && "InvokeInst must have an EHPadBB");
8635   }
8636   bool IsCallBr = isa<CallBrInst>(Call);
8637 
8638   if (IsCallBr || EmitEHLabels) {
8639     // If this is a callbr or invoke we need to flush pending exports since
8640     // inlineasm_br and invoke are terminators.
8641     // We need to do this before nodes are glued to the inlineasm_br node.
8642     Chain = getControlRoot();
8643   }
8644 
8645   MCSymbol *BeginLabel = nullptr;
8646   if (EmitEHLabels) {
8647     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
8648   }
8649 
8650   // Second pass over the constraints: compute which constraint option to use.
8651   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8652     // If this is an output operand with a matching input operand, look up the
8653     // matching input. If their types mismatch, e.g. one is an integer, the
8654     // other is floating point, or their sizes are different, flag it as an
8655     // error.
8656     if (OpInfo.hasMatchingInput()) {
8657       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8658       patchMatchingInput(OpInfo, Input, DAG);
8659     }
8660 
8661     // Compute the constraint code and ConstraintType to use.
8662     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8663 
8664     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8665         OpInfo.Type == InlineAsm::isClobber)
8666       continue;
8667 
8668     // If this is a memory input, and if the operand is not indirect, do what we
8669     // need to provide an address for the memory input.
8670     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8671         !OpInfo.isIndirect) {
8672       assert((OpInfo.isMultipleAlternative ||
8673               (OpInfo.Type == InlineAsm::isInput)) &&
8674              "Can only indirectify direct input operands!");
8675 
8676       // Memory operands really want the address of the value.
8677       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8678 
8679       // There is no longer a Value* corresponding to this operand.
8680       OpInfo.CallOperandVal = nullptr;
8681 
8682       // It is now an indirect operand.
8683       OpInfo.isIndirect = true;
8684     }
8685 
8686   }
8687 
8688   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8689   std::vector<SDValue> AsmNodeOperands;
8690   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8691   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8692       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8693 
8694   // If we have a !srcloc metadata node associated with it, we want to attach
8695   // this to the ultimately generated inline asm machineinstr.  To do this, we
8696   // pass in the third operand as this (potentially null) inline asm MDNode.
8697   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8698   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8699 
8700   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8701   // bits as operand 3.
8702   AsmNodeOperands.push_back(DAG.getTargetConstant(
8703       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8704 
8705   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8706   // this, assign virtual and physical registers for inputs and otput.
8707   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8708     // Assign Registers.
8709     SDISelAsmOperandInfo &RefOpInfo =
8710         OpInfo.isMatchingInputConstraint()
8711             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8712             : OpInfo;
8713     const auto RegError =
8714         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8715     if (RegError.hasValue()) {
8716       const MachineFunction &MF = DAG.getMachineFunction();
8717       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8718       const char *RegName = TRI.getName(RegError.getValue());
8719       emitInlineAsmError(Call, "register '" + Twine(RegName) +
8720                                    "' allocated for constraint '" +
8721                                    Twine(OpInfo.ConstraintCode) +
8722                                    "' does not match required type");
8723       return;
8724     }
8725 
8726     auto DetectWriteToReservedRegister = [&]() {
8727       const MachineFunction &MF = DAG.getMachineFunction();
8728       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8729       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8730         if (Register::isPhysicalRegister(Reg) &&
8731             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8732           const char *RegName = TRI.getName(Reg);
8733           emitInlineAsmError(Call, "write to reserved register '" +
8734                                        Twine(RegName) + "'");
8735           return true;
8736         }
8737       }
8738       return false;
8739     };
8740 
8741     switch (OpInfo.Type) {
8742     case InlineAsm::isOutput:
8743       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8744         unsigned ConstraintID =
8745             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8746         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8747                "Failed to convert memory constraint code to constraint id.");
8748 
8749         // Add information to the INLINEASM node to know about this output.
8750         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8751         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8752         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8753                                                         MVT::i32));
8754         AsmNodeOperands.push_back(OpInfo.CallOperand);
8755       } else {
8756         // Otherwise, this outputs to a register (directly for C_Register /
8757         // C_RegisterClass, and a target-defined fashion for
8758         // C_Immediate/C_Other). Find a register that we can use.
8759         if (OpInfo.AssignedRegs.Regs.empty()) {
8760           emitInlineAsmError(
8761               Call, "couldn't allocate output register for constraint '" +
8762                         Twine(OpInfo.ConstraintCode) + "'");
8763           return;
8764         }
8765 
8766         if (DetectWriteToReservedRegister())
8767           return;
8768 
8769         // Add information to the INLINEASM node to know that this register is
8770         // set.
8771         OpInfo.AssignedRegs.AddInlineAsmOperands(
8772             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8773                                   : InlineAsm::Kind_RegDef,
8774             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8775       }
8776       break;
8777 
8778     case InlineAsm::isInput: {
8779       SDValue InOperandVal = OpInfo.CallOperand;
8780 
8781       if (OpInfo.isMatchingInputConstraint()) {
8782         // If this is required to match an output register we have already set,
8783         // just use its register.
8784         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8785                                                   AsmNodeOperands);
8786         unsigned OpFlag =
8787           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8788         if (InlineAsm::isRegDefKind(OpFlag) ||
8789             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8790           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8791           if (OpInfo.isIndirect) {
8792             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8793             emitInlineAsmError(Call, "inline asm not supported yet: "
8794                                      "don't know how to handle tied "
8795                                      "indirect register inputs");
8796             return;
8797           }
8798 
8799           SmallVector<unsigned, 4> Regs;
8800           MachineFunction &MF = DAG.getMachineFunction();
8801           MachineRegisterInfo &MRI = MF.getRegInfo();
8802           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8803           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
8804           Register TiedReg = R->getReg();
8805           MVT RegVT = R->getSimpleValueType(0);
8806           const TargetRegisterClass *RC =
8807               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
8808               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
8809                                       : TRI.getMinimalPhysRegClass(TiedReg);
8810           unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8811           for (unsigned i = 0; i != NumRegs; ++i)
8812             Regs.push_back(MRI.createVirtualRegister(RC));
8813 
8814           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8815 
8816           SDLoc dl = getCurSDLoc();
8817           // Use the produced MatchedRegs object to
8818           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8819           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8820                                            true, OpInfo.getMatchedOperand(), dl,
8821                                            DAG, AsmNodeOperands);
8822           break;
8823         }
8824 
8825         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8826         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8827                "Unexpected number of operands");
8828         // Add information to the INLINEASM node to know about this input.
8829         // See InlineAsm.h isUseOperandTiedToDef.
8830         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8831         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8832                                                     OpInfo.getMatchedOperand());
8833         AsmNodeOperands.push_back(DAG.getTargetConstant(
8834             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8835         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8836         break;
8837       }
8838 
8839       // Treat indirect 'X' constraint as memory.
8840       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8841           OpInfo.isIndirect)
8842         OpInfo.ConstraintType = TargetLowering::C_Memory;
8843 
8844       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8845           OpInfo.ConstraintType == TargetLowering::C_Other) {
8846         std::vector<SDValue> Ops;
8847         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8848                                           Ops, DAG);
8849         if (Ops.empty()) {
8850           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8851             if (isa<ConstantSDNode>(InOperandVal)) {
8852               emitInlineAsmError(Call, "value out of range for constraint '" +
8853                                            Twine(OpInfo.ConstraintCode) + "'");
8854               return;
8855             }
8856 
8857           emitInlineAsmError(Call,
8858                              "invalid operand for inline asm constraint '" +
8859                                  Twine(OpInfo.ConstraintCode) + "'");
8860           return;
8861         }
8862 
8863         // Add information to the INLINEASM node to know about this input.
8864         unsigned ResOpType =
8865           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8866         AsmNodeOperands.push_back(DAG.getTargetConstant(
8867             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8868         llvm::append_range(AsmNodeOperands, Ops);
8869         break;
8870       }
8871 
8872       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8873         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8874         assert(InOperandVal.getValueType() ==
8875                    TLI.getPointerTy(DAG.getDataLayout()) &&
8876                "Memory operands expect pointer values");
8877 
8878         unsigned ConstraintID =
8879             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8880         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8881                "Failed to convert memory constraint code to constraint id.");
8882 
8883         // Add information to the INLINEASM node to know about this input.
8884         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8885         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8886         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8887                                                         getCurSDLoc(),
8888                                                         MVT::i32));
8889         AsmNodeOperands.push_back(InOperandVal);
8890         break;
8891       }
8892 
8893       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8894               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8895              "Unknown constraint type!");
8896 
8897       // TODO: Support this.
8898       if (OpInfo.isIndirect) {
8899         emitInlineAsmError(
8900             Call, "Don't know how to handle indirect register inputs yet "
8901                   "for constraint '" +
8902                       Twine(OpInfo.ConstraintCode) + "'");
8903         return;
8904       }
8905 
8906       // Copy the input into the appropriate registers.
8907       if (OpInfo.AssignedRegs.Regs.empty()) {
8908         emitInlineAsmError(Call,
8909                            "couldn't allocate input reg for constraint '" +
8910                                Twine(OpInfo.ConstraintCode) + "'");
8911         return;
8912       }
8913 
8914       if (DetectWriteToReservedRegister())
8915         return;
8916 
8917       SDLoc dl = getCurSDLoc();
8918 
8919       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8920                                         &Call);
8921 
8922       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8923                                                dl, DAG, AsmNodeOperands);
8924       break;
8925     }
8926     case InlineAsm::isClobber:
8927       // Add the clobbered value to the operand list, so that the register
8928       // allocator is aware that the physreg got clobbered.
8929       if (!OpInfo.AssignedRegs.Regs.empty())
8930         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8931                                                  false, 0, getCurSDLoc(), DAG,
8932                                                  AsmNodeOperands);
8933       break;
8934     }
8935   }
8936 
8937   // Finish up input operands.  Set the input chain and add the flag last.
8938   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8939   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8940 
8941   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8942   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8943                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8944   Flag = Chain.getValue(1);
8945 
8946   // Do additional work to generate outputs.
8947 
8948   SmallVector<EVT, 1> ResultVTs;
8949   SmallVector<SDValue, 1> ResultValues;
8950   SmallVector<SDValue, 8> OutChains;
8951 
8952   llvm::Type *CallResultType = Call.getType();
8953   ArrayRef<Type *> ResultTypes;
8954   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8955     ResultTypes = StructResult->elements();
8956   else if (!CallResultType->isVoidTy())
8957     ResultTypes = makeArrayRef(CallResultType);
8958 
8959   auto CurResultType = ResultTypes.begin();
8960   auto handleRegAssign = [&](SDValue V) {
8961     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8962     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8963     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8964     ++CurResultType;
8965     // If the type of the inline asm call site return value is different but has
8966     // same size as the type of the asm output bitcast it.  One example of this
8967     // is for vectors with different width / number of elements.  This can
8968     // happen for register classes that can contain multiple different value
8969     // types.  The preg or vreg allocated may not have the same VT as was
8970     // expected.
8971     //
8972     // This can also happen for a return value that disagrees with the register
8973     // class it is put in, eg. a double in a general-purpose register on a
8974     // 32-bit machine.
8975     if (ResultVT != V.getValueType() &&
8976         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8977       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8978     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8979              V.getValueType().isInteger()) {
8980       // If a result value was tied to an input value, the computed result
8981       // may have a wider width than the expected result.  Extract the
8982       // relevant portion.
8983       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8984     }
8985     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8986     ResultVTs.push_back(ResultVT);
8987     ResultValues.push_back(V);
8988   };
8989 
8990   // Deal with output operands.
8991   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8992     if (OpInfo.Type == InlineAsm::isOutput) {
8993       SDValue Val;
8994       // Skip trivial output operands.
8995       if (OpInfo.AssignedRegs.Regs.empty())
8996         continue;
8997 
8998       switch (OpInfo.ConstraintType) {
8999       case TargetLowering::C_Register:
9000       case TargetLowering::C_RegisterClass:
9001         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9002                                                   Chain, &Flag, &Call);
9003         break;
9004       case TargetLowering::C_Immediate:
9005       case TargetLowering::C_Other:
9006         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
9007                                               OpInfo, DAG);
9008         break;
9009       case TargetLowering::C_Memory:
9010         break; // Already handled.
9011       case TargetLowering::C_Unknown:
9012         assert(false && "Unexpected unknown constraint");
9013       }
9014 
9015       // Indirect output manifest as stores. Record output chains.
9016       if (OpInfo.isIndirect) {
9017         const Value *Ptr = OpInfo.CallOperandVal;
9018         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9019         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9020                                      MachinePointerInfo(Ptr));
9021         OutChains.push_back(Store);
9022       } else {
9023         // generate CopyFromRegs to associated registers.
9024         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9025         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9026           for (const SDValue &V : Val->op_values())
9027             handleRegAssign(V);
9028         } else
9029           handleRegAssign(Val);
9030       }
9031     }
9032   }
9033 
9034   // Set results.
9035   if (!ResultValues.empty()) {
9036     assert(CurResultType == ResultTypes.end() &&
9037            "Mismatch in number of ResultTypes");
9038     assert(ResultValues.size() == ResultTypes.size() &&
9039            "Mismatch in number of output operands in asm result");
9040 
9041     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
9042                             DAG.getVTList(ResultVTs), ResultValues);
9043     setValue(&Call, V);
9044   }
9045 
9046   // Collect store chains.
9047   if (!OutChains.empty())
9048     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
9049 
9050   if (EmitEHLabels) {
9051     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
9052   }
9053 
9054   // Only Update Root if inline assembly has a memory effect.
9055   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
9056       EmitEHLabels)
9057     DAG.setRoot(Chain);
9058 }
9059 
9060 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
9061                                              const Twine &Message) {
9062   LLVMContext &Ctx = *DAG.getContext();
9063   Ctx.emitError(&Call, Message);
9064 
9065   // Make sure we leave the DAG in a valid state
9066   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9067   SmallVector<EVT, 1> ValueVTs;
9068   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
9069 
9070   if (ValueVTs.empty())
9071     return;
9072 
9073   SmallVector<SDValue, 1> Ops;
9074   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
9075     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
9076 
9077   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
9078 }
9079 
9080 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
9081   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
9082                           MVT::Other, getRoot(),
9083                           getValue(I.getArgOperand(0)),
9084                           DAG.getSrcValue(I.getArgOperand(0))));
9085 }
9086 
9087 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
9088   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9089   const DataLayout &DL = DAG.getDataLayout();
9090   SDValue V = DAG.getVAArg(
9091       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
9092       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
9093       DL.getABITypeAlign(I.getType()).value());
9094   DAG.setRoot(V.getValue(1));
9095 
9096   if (I.getType()->isPointerTy())
9097     V = DAG.getPtrExtOrTrunc(
9098         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
9099   setValue(&I, V);
9100 }
9101 
9102 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
9103   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
9104                           MVT::Other, getRoot(),
9105                           getValue(I.getArgOperand(0)),
9106                           DAG.getSrcValue(I.getArgOperand(0))));
9107 }
9108 
9109 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
9110   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
9111                           MVT::Other, getRoot(),
9112                           getValue(I.getArgOperand(0)),
9113                           getValue(I.getArgOperand(1)),
9114                           DAG.getSrcValue(I.getArgOperand(0)),
9115                           DAG.getSrcValue(I.getArgOperand(1))));
9116 }
9117 
9118 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
9119                                                     const Instruction &I,
9120                                                     SDValue Op) {
9121   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
9122   if (!Range)
9123     return Op;
9124 
9125   ConstantRange CR = getConstantRangeFromMetadata(*Range);
9126   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
9127     return Op;
9128 
9129   APInt Lo = CR.getUnsignedMin();
9130   if (!Lo.isMinValue())
9131     return Op;
9132 
9133   APInt Hi = CR.getUnsignedMax();
9134   unsigned Bits = std::max(Hi.getActiveBits(),
9135                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
9136 
9137   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
9138 
9139   SDLoc SL = getCurSDLoc();
9140 
9141   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
9142                              DAG.getValueType(SmallVT));
9143   unsigned NumVals = Op.getNode()->getNumValues();
9144   if (NumVals == 1)
9145     return ZExt;
9146 
9147   SmallVector<SDValue, 4> Ops;
9148 
9149   Ops.push_back(ZExt);
9150   for (unsigned I = 1; I != NumVals; ++I)
9151     Ops.push_back(Op.getValue(I));
9152 
9153   return DAG.getMergeValues(Ops, SL);
9154 }
9155 
9156 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
9157 /// the call being lowered.
9158 ///
9159 /// This is a helper for lowering intrinsics that follow a target calling
9160 /// convention or require stack pointer adjustment. Only a subset of the
9161 /// intrinsic's operands need to participate in the calling convention.
9162 void SelectionDAGBuilder::populateCallLoweringInfo(
9163     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
9164     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
9165     bool IsPatchPoint) {
9166   TargetLowering::ArgListTy Args;
9167   Args.reserve(NumArgs);
9168 
9169   // Populate the argument list.
9170   // Attributes for args start at offset 1, after the return attribute.
9171   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
9172        ArgI != ArgE; ++ArgI) {
9173     const Value *V = Call->getOperand(ArgI);
9174 
9175     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
9176 
9177     TargetLowering::ArgListEntry Entry;
9178     Entry.Node = getValue(V);
9179     Entry.Ty = V->getType();
9180     Entry.setAttributes(Call, ArgI);
9181     Args.push_back(Entry);
9182   }
9183 
9184   CLI.setDebugLoc(getCurSDLoc())
9185       .setChain(getRoot())
9186       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
9187       .setDiscardResult(Call->use_empty())
9188       .setIsPatchPoint(IsPatchPoint)
9189       .setIsPreallocated(
9190           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
9191 }
9192 
9193 /// Add a stack map intrinsic call's live variable operands to a stackmap
9194 /// or patchpoint target node's operand list.
9195 ///
9196 /// Constants are converted to TargetConstants purely as an optimization to
9197 /// avoid constant materialization and register allocation.
9198 ///
9199 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
9200 /// generate addess computation nodes, and so FinalizeISel can convert the
9201 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
9202 /// address materialization and register allocation, but may also be required
9203 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
9204 /// alloca in the entry block, then the runtime may assume that the alloca's
9205 /// StackMap location can be read immediately after compilation and that the
9206 /// location is valid at any point during execution (this is similar to the
9207 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
9208 /// only available in a register, then the runtime would need to trap when
9209 /// execution reaches the StackMap in order to read the alloca's location.
9210 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
9211                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
9212                                 SelectionDAGBuilder &Builder) {
9213   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
9214     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
9215     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
9216       Ops.push_back(
9217         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
9218       Ops.push_back(
9219         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
9220     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
9221       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
9222       Ops.push_back(Builder.DAG.getTargetFrameIndex(
9223           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
9224     } else
9225       Ops.push_back(OpVal);
9226   }
9227 }
9228 
9229 /// Lower llvm.experimental.stackmap directly to its target opcode.
9230 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
9231   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
9232   //                                  [live variables...])
9233 
9234   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
9235 
9236   SDValue Chain, InFlag, Callee, NullPtr;
9237   SmallVector<SDValue, 32> Ops;
9238 
9239   SDLoc DL = getCurSDLoc();
9240   Callee = getValue(CI.getCalledOperand());
9241   NullPtr = DAG.getIntPtrConstant(0, DL, true);
9242 
9243   // The stackmap intrinsic only records the live variables (the arguments
9244   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
9245   // intrinsic, this won't be lowered to a function call. This means we don't
9246   // have to worry about calling conventions and target specific lowering code.
9247   // Instead we perform the call lowering right here.
9248   //
9249   // chain, flag = CALLSEQ_START(chain, 0, 0)
9250   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
9251   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
9252   //
9253   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
9254   InFlag = Chain.getValue(1);
9255 
9256   // Add the <id> and <numBytes> constants.
9257   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
9258   Ops.push_back(DAG.getTargetConstant(
9259                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
9260   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
9261   Ops.push_back(DAG.getTargetConstant(
9262                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
9263                   MVT::i32));
9264 
9265   // Push live variables for the stack map.
9266   addStackMapLiveVars(CI, 2, DL, Ops, *this);
9267 
9268   // We are not pushing any register mask info here on the operands list,
9269   // because the stackmap doesn't clobber anything.
9270 
9271   // Push the chain and the glue flag.
9272   Ops.push_back(Chain);
9273   Ops.push_back(InFlag);
9274 
9275   // Create the STACKMAP node.
9276   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9277   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
9278   Chain = SDValue(SM, 0);
9279   InFlag = Chain.getValue(1);
9280 
9281   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
9282 
9283   // Stackmaps don't generate values, so nothing goes into the NodeMap.
9284 
9285   // Set the root to the target-lowered call chain.
9286   DAG.setRoot(Chain);
9287 
9288   // Inform the Frame Information that we have a stackmap in this function.
9289   FuncInfo.MF->getFrameInfo().setHasStackMap();
9290 }
9291 
9292 /// Lower llvm.experimental.patchpoint directly to its target opcode.
9293 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
9294                                           const BasicBlock *EHPadBB) {
9295   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
9296   //                                                 i32 <numBytes>,
9297   //                                                 i8* <target>,
9298   //                                                 i32 <numArgs>,
9299   //                                                 [Args...],
9300   //                                                 [live variables...])
9301 
9302   CallingConv::ID CC = CB.getCallingConv();
9303   bool IsAnyRegCC = CC == CallingConv::AnyReg;
9304   bool HasDef = !CB.getType()->isVoidTy();
9305   SDLoc dl = getCurSDLoc();
9306   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
9307 
9308   // Handle immediate and symbolic callees.
9309   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
9310     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
9311                                    /*isTarget=*/true);
9312   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
9313     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
9314                                          SDLoc(SymbolicCallee),
9315                                          SymbolicCallee->getValueType(0));
9316 
9317   // Get the real number of arguments participating in the call <numArgs>
9318   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
9319   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
9320 
9321   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
9322   // Intrinsics include all meta-operands up to but not including CC.
9323   unsigned NumMetaOpers = PatchPointOpers::CCPos;
9324   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
9325          "Not enough arguments provided to the patchpoint intrinsic");
9326 
9327   // For AnyRegCC the arguments are lowered later on manually.
9328   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
9329   Type *ReturnTy =
9330       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
9331 
9332   TargetLowering::CallLoweringInfo CLI(DAG);
9333   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
9334                            ReturnTy, true);
9335   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
9336 
9337   SDNode *CallEnd = Result.second.getNode();
9338   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
9339     CallEnd = CallEnd->getOperand(0).getNode();
9340 
9341   /// Get a call instruction from the call sequence chain.
9342   /// Tail calls are not allowed.
9343   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9344          "Expected a callseq node.");
9345   SDNode *Call = CallEnd->getOperand(0).getNode();
9346   bool HasGlue = Call->getGluedNode();
9347 
9348   // Replace the target specific call node with the patchable intrinsic.
9349   SmallVector<SDValue, 8> Ops;
9350 
9351   // Add the <id> and <numBytes> constants.
9352   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9353   Ops.push_back(DAG.getTargetConstant(
9354                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9355   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9356   Ops.push_back(DAG.getTargetConstant(
9357                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9358                   MVT::i32));
9359 
9360   // Add the callee.
9361   Ops.push_back(Callee);
9362 
9363   // Adjust <numArgs> to account for any arguments that have been passed on the
9364   // stack instead.
9365   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9366   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9367   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9368   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9369 
9370   // Add the calling convention
9371   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9372 
9373   // Add the arguments we omitted previously. The register allocator should
9374   // place these in any free register.
9375   if (IsAnyRegCC)
9376     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9377       Ops.push_back(getValue(CB.getArgOperand(i)));
9378 
9379   // Push the arguments from the call instruction up to the register mask.
9380   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9381   Ops.append(Call->op_begin() + 2, e);
9382 
9383   // Push live variables for the stack map.
9384   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9385 
9386   // Push the register mask info.
9387   if (HasGlue)
9388     Ops.push_back(*(Call->op_end()-2));
9389   else
9390     Ops.push_back(*(Call->op_end()-1));
9391 
9392   // Push the chain (this is originally the first operand of the call, but
9393   // becomes now the last or second to last operand).
9394   Ops.push_back(*(Call->op_begin()));
9395 
9396   // Push the glue flag (last operand).
9397   if (HasGlue)
9398     Ops.push_back(*(Call->op_end()-1));
9399 
9400   SDVTList NodeTys;
9401   if (IsAnyRegCC && HasDef) {
9402     // Create the return types based on the intrinsic definition
9403     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9404     SmallVector<EVT, 3> ValueVTs;
9405     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9406     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9407 
9408     // There is always a chain and a glue type at the end
9409     ValueVTs.push_back(MVT::Other);
9410     ValueVTs.push_back(MVT::Glue);
9411     NodeTys = DAG.getVTList(ValueVTs);
9412   } else
9413     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9414 
9415   // Replace the target specific call node with a PATCHPOINT node.
9416   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9417                                          dl, NodeTys, Ops);
9418 
9419   // Update the NodeMap.
9420   if (HasDef) {
9421     if (IsAnyRegCC)
9422       setValue(&CB, SDValue(MN, 0));
9423     else
9424       setValue(&CB, Result.first);
9425   }
9426 
9427   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9428   // call sequence. Furthermore the location of the chain and glue can change
9429   // when the AnyReg calling convention is used and the intrinsic returns a
9430   // value.
9431   if (IsAnyRegCC && HasDef) {
9432     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9433     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9434     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9435   } else
9436     DAG.ReplaceAllUsesWith(Call, MN);
9437   DAG.DeleteNode(Call);
9438 
9439   // Inform the Frame Information that we have a patchpoint in this function.
9440   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9441 }
9442 
9443 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9444                                             unsigned Intrinsic) {
9445   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9446   SDValue Op1 = getValue(I.getArgOperand(0));
9447   SDValue Op2;
9448   if (I.arg_size() > 1)
9449     Op2 = getValue(I.getArgOperand(1));
9450   SDLoc dl = getCurSDLoc();
9451   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9452   SDValue Res;
9453   SDNodeFlags SDFlags;
9454   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9455     SDFlags.copyFMF(*FPMO);
9456 
9457   switch (Intrinsic) {
9458   case Intrinsic::vector_reduce_fadd:
9459     if (SDFlags.hasAllowReassociation())
9460       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9461                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9462                         SDFlags);
9463     else
9464       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9465     break;
9466   case Intrinsic::vector_reduce_fmul:
9467     if (SDFlags.hasAllowReassociation())
9468       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9469                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9470                         SDFlags);
9471     else
9472       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9473     break;
9474   case Intrinsic::vector_reduce_add:
9475     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9476     break;
9477   case Intrinsic::vector_reduce_mul:
9478     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9479     break;
9480   case Intrinsic::vector_reduce_and:
9481     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9482     break;
9483   case Intrinsic::vector_reduce_or:
9484     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9485     break;
9486   case Intrinsic::vector_reduce_xor:
9487     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9488     break;
9489   case Intrinsic::vector_reduce_smax:
9490     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9491     break;
9492   case Intrinsic::vector_reduce_smin:
9493     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9494     break;
9495   case Intrinsic::vector_reduce_umax:
9496     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9497     break;
9498   case Intrinsic::vector_reduce_umin:
9499     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9500     break;
9501   case Intrinsic::vector_reduce_fmax:
9502     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9503     break;
9504   case Intrinsic::vector_reduce_fmin:
9505     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9506     break;
9507   default:
9508     llvm_unreachable("Unhandled vector reduce intrinsic");
9509   }
9510   setValue(&I, Res);
9511 }
9512 
9513 /// Returns an AttributeList representing the attributes applied to the return
9514 /// value of the given call.
9515 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9516   SmallVector<Attribute::AttrKind, 2> Attrs;
9517   if (CLI.RetSExt)
9518     Attrs.push_back(Attribute::SExt);
9519   if (CLI.RetZExt)
9520     Attrs.push_back(Attribute::ZExt);
9521   if (CLI.IsInReg)
9522     Attrs.push_back(Attribute::InReg);
9523 
9524   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9525                             Attrs);
9526 }
9527 
9528 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9529 /// implementation, which just calls LowerCall.
9530 /// FIXME: When all targets are
9531 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9532 std::pair<SDValue, SDValue>
9533 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9534   // Handle the incoming return values from the call.
9535   CLI.Ins.clear();
9536   Type *OrigRetTy = CLI.RetTy;
9537   SmallVector<EVT, 4> RetTys;
9538   SmallVector<uint64_t, 4> Offsets;
9539   auto &DL = CLI.DAG.getDataLayout();
9540   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9541 
9542   if (CLI.IsPostTypeLegalization) {
9543     // If we are lowering a libcall after legalization, split the return type.
9544     SmallVector<EVT, 4> OldRetTys;
9545     SmallVector<uint64_t, 4> OldOffsets;
9546     RetTys.swap(OldRetTys);
9547     Offsets.swap(OldOffsets);
9548 
9549     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9550       EVT RetVT = OldRetTys[i];
9551       uint64_t Offset = OldOffsets[i];
9552       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9553       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9554       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9555       RetTys.append(NumRegs, RegisterVT);
9556       for (unsigned j = 0; j != NumRegs; ++j)
9557         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9558     }
9559   }
9560 
9561   SmallVector<ISD::OutputArg, 4> Outs;
9562   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9563 
9564   bool CanLowerReturn =
9565       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9566                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9567 
9568   SDValue DemoteStackSlot;
9569   int DemoteStackIdx = -100;
9570   if (!CanLowerReturn) {
9571     // FIXME: equivalent assert?
9572     // assert(!CS.hasInAllocaArgument() &&
9573     //        "sret demotion is incompatible with inalloca");
9574     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9575     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9576     MachineFunction &MF = CLI.DAG.getMachineFunction();
9577     DemoteStackIdx =
9578         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9579     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9580                                               DL.getAllocaAddrSpace());
9581 
9582     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9583     ArgListEntry Entry;
9584     Entry.Node = DemoteStackSlot;
9585     Entry.Ty = StackSlotPtrType;
9586     Entry.IsSExt = false;
9587     Entry.IsZExt = false;
9588     Entry.IsInReg = false;
9589     Entry.IsSRet = true;
9590     Entry.IsNest = false;
9591     Entry.IsByVal = false;
9592     Entry.IsByRef = false;
9593     Entry.IsReturned = false;
9594     Entry.IsSwiftSelf = false;
9595     Entry.IsSwiftAsync = false;
9596     Entry.IsSwiftError = false;
9597     Entry.IsCFGuardTarget = false;
9598     Entry.Alignment = Alignment;
9599     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9600     CLI.NumFixedArgs += 1;
9601     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9602 
9603     // sret demotion isn't compatible with tail-calls, since the sret argument
9604     // points into the callers stack frame.
9605     CLI.IsTailCall = false;
9606   } else {
9607     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9608         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
9609     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9610       ISD::ArgFlagsTy Flags;
9611       if (NeedsRegBlock) {
9612         Flags.setInConsecutiveRegs();
9613         if (I == RetTys.size() - 1)
9614           Flags.setInConsecutiveRegsLast();
9615       }
9616       EVT VT = RetTys[I];
9617       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9618                                                      CLI.CallConv, VT);
9619       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9620                                                        CLI.CallConv, VT);
9621       for (unsigned i = 0; i != NumRegs; ++i) {
9622         ISD::InputArg MyFlags;
9623         MyFlags.Flags = Flags;
9624         MyFlags.VT = RegisterVT;
9625         MyFlags.ArgVT = VT;
9626         MyFlags.Used = CLI.IsReturnValueUsed;
9627         if (CLI.RetTy->isPointerTy()) {
9628           MyFlags.Flags.setPointer();
9629           MyFlags.Flags.setPointerAddrSpace(
9630               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9631         }
9632         if (CLI.RetSExt)
9633           MyFlags.Flags.setSExt();
9634         if (CLI.RetZExt)
9635           MyFlags.Flags.setZExt();
9636         if (CLI.IsInReg)
9637           MyFlags.Flags.setInReg();
9638         CLI.Ins.push_back(MyFlags);
9639       }
9640     }
9641   }
9642 
9643   // We push in swifterror return as the last element of CLI.Ins.
9644   ArgListTy &Args = CLI.getArgs();
9645   if (supportSwiftError()) {
9646     for (const ArgListEntry &Arg : Args) {
9647       if (Arg.IsSwiftError) {
9648         ISD::InputArg MyFlags;
9649         MyFlags.VT = getPointerTy(DL);
9650         MyFlags.ArgVT = EVT(getPointerTy(DL));
9651         MyFlags.Flags.setSwiftError();
9652         CLI.Ins.push_back(MyFlags);
9653       }
9654     }
9655   }
9656 
9657   // Handle all of the outgoing arguments.
9658   CLI.Outs.clear();
9659   CLI.OutVals.clear();
9660   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9661     SmallVector<EVT, 4> ValueVTs;
9662     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9663     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9664     Type *FinalType = Args[i].Ty;
9665     if (Args[i].IsByVal)
9666       FinalType = Args[i].IndirectType;
9667     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9668         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
9669     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9670          ++Value) {
9671       EVT VT = ValueVTs[Value];
9672       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9673       SDValue Op = SDValue(Args[i].Node.getNode(),
9674                            Args[i].Node.getResNo() + Value);
9675       ISD::ArgFlagsTy Flags;
9676 
9677       // Certain targets (such as MIPS), may have a different ABI alignment
9678       // for a type depending on the context. Give the target a chance to
9679       // specify the alignment it wants.
9680       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9681       Flags.setOrigAlign(OriginalAlignment);
9682 
9683       if (Args[i].Ty->isPointerTy()) {
9684         Flags.setPointer();
9685         Flags.setPointerAddrSpace(
9686             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9687       }
9688       if (Args[i].IsZExt)
9689         Flags.setZExt();
9690       if (Args[i].IsSExt)
9691         Flags.setSExt();
9692       if (Args[i].IsInReg) {
9693         // If we are using vectorcall calling convention, a structure that is
9694         // passed InReg - is surely an HVA
9695         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9696             isa<StructType>(FinalType)) {
9697           // The first value of a structure is marked
9698           if (0 == Value)
9699             Flags.setHvaStart();
9700           Flags.setHva();
9701         }
9702         // Set InReg Flag
9703         Flags.setInReg();
9704       }
9705       if (Args[i].IsSRet)
9706         Flags.setSRet();
9707       if (Args[i].IsSwiftSelf)
9708         Flags.setSwiftSelf();
9709       if (Args[i].IsSwiftAsync)
9710         Flags.setSwiftAsync();
9711       if (Args[i].IsSwiftError)
9712         Flags.setSwiftError();
9713       if (Args[i].IsCFGuardTarget)
9714         Flags.setCFGuardTarget();
9715       if (Args[i].IsByVal)
9716         Flags.setByVal();
9717       if (Args[i].IsByRef)
9718         Flags.setByRef();
9719       if (Args[i].IsPreallocated) {
9720         Flags.setPreallocated();
9721         // Set the byval flag for CCAssignFn callbacks that don't know about
9722         // preallocated.  This way we can know how many bytes we should've
9723         // allocated and how many bytes a callee cleanup function will pop.  If
9724         // we port preallocated to more targets, we'll have to add custom
9725         // preallocated handling in the various CC lowering callbacks.
9726         Flags.setByVal();
9727       }
9728       if (Args[i].IsInAlloca) {
9729         Flags.setInAlloca();
9730         // Set the byval flag for CCAssignFn callbacks that don't know about
9731         // inalloca.  This way we can know how many bytes we should've allocated
9732         // and how many bytes a callee cleanup function will pop.  If we port
9733         // inalloca to more targets, we'll have to add custom inalloca handling
9734         // in the various CC lowering callbacks.
9735         Flags.setByVal();
9736       }
9737       Align MemAlign;
9738       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9739         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
9740         Flags.setByValSize(FrameSize);
9741 
9742         // info is not there but there are cases it cannot get right.
9743         if (auto MA = Args[i].Alignment)
9744           MemAlign = *MA;
9745         else
9746           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
9747       } else if (auto MA = Args[i].Alignment) {
9748         MemAlign = *MA;
9749       } else {
9750         MemAlign = OriginalAlignment;
9751       }
9752       Flags.setMemAlign(MemAlign);
9753       if (Args[i].IsNest)
9754         Flags.setNest();
9755       if (NeedsRegBlock)
9756         Flags.setInConsecutiveRegs();
9757 
9758       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9759                                                  CLI.CallConv, VT);
9760       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9761                                                         CLI.CallConv, VT);
9762       SmallVector<SDValue, 4> Parts(NumParts);
9763       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9764 
9765       if (Args[i].IsSExt)
9766         ExtendKind = ISD::SIGN_EXTEND;
9767       else if (Args[i].IsZExt)
9768         ExtendKind = ISD::ZERO_EXTEND;
9769 
9770       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9771       // for now.
9772       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9773           CanLowerReturn) {
9774         assert((CLI.RetTy == Args[i].Ty ||
9775                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9776                  CLI.RetTy->getPointerAddressSpace() ==
9777                      Args[i].Ty->getPointerAddressSpace())) &&
9778                RetTys.size() == NumValues && "unexpected use of 'returned'");
9779         // Before passing 'returned' to the target lowering code, ensure that
9780         // either the register MVT and the actual EVT are the same size or that
9781         // the return value and argument are extended in the same way; in these
9782         // cases it's safe to pass the argument register value unchanged as the
9783         // return register value (although it's at the target's option whether
9784         // to do so)
9785         // TODO: allow code generation to take advantage of partially preserved
9786         // registers rather than clobbering the entire register when the
9787         // parameter extension method is not compatible with the return
9788         // extension method
9789         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9790             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9791              CLI.RetZExt == Args[i].IsZExt))
9792           Flags.setReturned();
9793       }
9794 
9795       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9796                      CLI.CallConv, ExtendKind);
9797 
9798       for (unsigned j = 0; j != NumParts; ++j) {
9799         // if it isn't first piece, alignment must be 1
9800         // For scalable vectors the scalable part is currently handled
9801         // by individual targets, so we just use the known minimum size here.
9802         ISD::OutputArg MyFlags(
9803             Flags, Parts[j].getValueType().getSimpleVT(), VT,
9804             i < CLI.NumFixedArgs, i,
9805             j * Parts[j].getValueType().getStoreSize().getKnownMinSize());
9806         if (NumParts > 1 && j == 0)
9807           MyFlags.Flags.setSplit();
9808         else if (j != 0) {
9809           MyFlags.Flags.setOrigAlign(Align(1));
9810           if (j == NumParts - 1)
9811             MyFlags.Flags.setSplitEnd();
9812         }
9813 
9814         CLI.Outs.push_back(MyFlags);
9815         CLI.OutVals.push_back(Parts[j]);
9816       }
9817 
9818       if (NeedsRegBlock && Value == NumValues - 1)
9819         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9820     }
9821   }
9822 
9823   SmallVector<SDValue, 4> InVals;
9824   CLI.Chain = LowerCall(CLI, InVals);
9825 
9826   // Update CLI.InVals to use outside of this function.
9827   CLI.InVals = InVals;
9828 
9829   // Verify that the target's LowerCall behaved as expected.
9830   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9831          "LowerCall didn't return a valid chain!");
9832   assert((!CLI.IsTailCall || InVals.empty()) &&
9833          "LowerCall emitted a return value for a tail call!");
9834   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9835          "LowerCall didn't emit the correct number of values!");
9836 
9837   // For a tail call, the return value is merely live-out and there aren't
9838   // any nodes in the DAG representing it. Return a special value to
9839   // indicate that a tail call has been emitted and no more Instructions
9840   // should be processed in the current block.
9841   if (CLI.IsTailCall) {
9842     CLI.DAG.setRoot(CLI.Chain);
9843     return std::make_pair(SDValue(), SDValue());
9844   }
9845 
9846 #ifndef NDEBUG
9847   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9848     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9849     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9850            "LowerCall emitted a value with the wrong type!");
9851   }
9852 #endif
9853 
9854   SmallVector<SDValue, 4> ReturnValues;
9855   if (!CanLowerReturn) {
9856     // The instruction result is the result of loading from the
9857     // hidden sret parameter.
9858     SmallVector<EVT, 1> PVTs;
9859     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9860 
9861     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9862     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9863     EVT PtrVT = PVTs[0];
9864 
9865     unsigned NumValues = RetTys.size();
9866     ReturnValues.resize(NumValues);
9867     SmallVector<SDValue, 4> Chains(NumValues);
9868 
9869     // An aggregate return value cannot wrap around the address space, so
9870     // offsets to its parts don't wrap either.
9871     SDNodeFlags Flags;
9872     Flags.setNoUnsignedWrap(true);
9873 
9874     MachineFunction &MF = CLI.DAG.getMachineFunction();
9875     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9876     for (unsigned i = 0; i < NumValues; ++i) {
9877       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9878                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9879                                                         PtrVT), Flags);
9880       SDValue L = CLI.DAG.getLoad(
9881           RetTys[i], CLI.DL, CLI.Chain, Add,
9882           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9883                                             DemoteStackIdx, Offsets[i]),
9884           HiddenSRetAlign);
9885       ReturnValues[i] = L;
9886       Chains[i] = L.getValue(1);
9887     }
9888 
9889     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9890   } else {
9891     // Collect the legal value parts into potentially illegal values
9892     // that correspond to the original function's return values.
9893     Optional<ISD::NodeType> AssertOp;
9894     if (CLI.RetSExt)
9895       AssertOp = ISD::AssertSext;
9896     else if (CLI.RetZExt)
9897       AssertOp = ISD::AssertZext;
9898     unsigned CurReg = 0;
9899     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9900       EVT VT = RetTys[I];
9901       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9902                                                      CLI.CallConv, VT);
9903       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9904                                                        CLI.CallConv, VT);
9905 
9906       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9907                                               NumRegs, RegisterVT, VT, nullptr,
9908                                               CLI.CallConv, AssertOp));
9909       CurReg += NumRegs;
9910     }
9911 
9912     // For a function returning void, there is no return value. We can't create
9913     // such a node, so we just return a null return value in that case. In
9914     // that case, nothing will actually look at the value.
9915     if (ReturnValues.empty())
9916       return std::make_pair(SDValue(), CLI.Chain);
9917   }
9918 
9919   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9920                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9921   return std::make_pair(Res, CLI.Chain);
9922 }
9923 
9924 /// Places new result values for the node in Results (their number
9925 /// and types must exactly match those of the original return values of
9926 /// the node), or leaves Results empty, which indicates that the node is not
9927 /// to be custom lowered after all.
9928 void TargetLowering::LowerOperationWrapper(SDNode *N,
9929                                            SmallVectorImpl<SDValue> &Results,
9930                                            SelectionDAG &DAG) const {
9931   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9932 
9933   if (!Res.getNode())
9934     return;
9935 
9936   // If the original node has one result, take the return value from
9937   // LowerOperation as is. It might not be result number 0.
9938   if (N->getNumValues() == 1) {
9939     Results.push_back(Res);
9940     return;
9941   }
9942 
9943   // If the original node has multiple results, then the return node should
9944   // have the same number of results.
9945   assert((N->getNumValues() == Res->getNumValues()) &&
9946       "Lowering returned the wrong number of results!");
9947 
9948   // Places new result values base on N result number.
9949   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9950     Results.push_back(Res.getValue(I));
9951 }
9952 
9953 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9954   llvm_unreachable("LowerOperation not implemented for this target!");
9955 }
9956 
9957 void
9958 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9959   SDValue Op = getNonRegisterValue(V);
9960   assert((Op.getOpcode() != ISD::CopyFromReg ||
9961           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9962          "Copy from a reg to the same reg!");
9963   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9964 
9965   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9966   // If this is an InlineAsm we have to match the registers required, not the
9967   // notional registers required by the type.
9968 
9969   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9970                    None); // This is not an ABI copy.
9971   SDValue Chain = DAG.getEntryNode();
9972 
9973   ISD::NodeType ExtendType = ISD::ANY_EXTEND;
9974   auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
9975   if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
9976     ExtendType = PreferredExtendIt->second;
9977   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9978   PendingExports.push_back(Chain);
9979 }
9980 
9981 #include "llvm/CodeGen/SelectionDAGISel.h"
9982 
9983 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9984 /// entry block, return true.  This includes arguments used by switches, since
9985 /// the switch may expand into multiple basic blocks.
9986 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9987   // With FastISel active, we may be splitting blocks, so force creation
9988   // of virtual registers for all non-dead arguments.
9989   if (FastISel)
9990     return A->use_empty();
9991 
9992   const BasicBlock &Entry = A->getParent()->front();
9993   for (const User *U : A->users())
9994     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9995       return false;  // Use not in entry block.
9996 
9997   return true;
9998 }
9999 
10000 using ArgCopyElisionMapTy =
10001     DenseMap<const Argument *,
10002              std::pair<const AllocaInst *, const StoreInst *>>;
10003 
10004 /// Scan the entry block of the function in FuncInfo for arguments that look
10005 /// like copies into a local alloca. Record any copied arguments in
10006 /// ArgCopyElisionCandidates.
10007 static void
10008 findArgumentCopyElisionCandidates(const DataLayout &DL,
10009                                   FunctionLoweringInfo *FuncInfo,
10010                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10011   // Record the state of every static alloca used in the entry block. Argument
10012   // allocas are all used in the entry block, so we need approximately as many
10013   // entries as we have arguments.
10014   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10015   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10016   unsigned NumArgs = FuncInfo->Fn->arg_size();
10017   StaticAllocas.reserve(NumArgs * 2);
10018 
10019   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10020     if (!V)
10021       return nullptr;
10022     V = V->stripPointerCasts();
10023     const auto *AI = dyn_cast<AllocaInst>(V);
10024     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
10025       return nullptr;
10026     auto Iter = StaticAllocas.insert({AI, Unknown});
10027     return &Iter.first->second;
10028   };
10029 
10030   // Look for stores of arguments to static allocas. Look through bitcasts and
10031   // GEPs to handle type coercions, as long as the alloca is fully initialized
10032   // by the store. Any non-store use of an alloca escapes it and any subsequent
10033   // unanalyzed store might write it.
10034   // FIXME: Handle structs initialized with multiple stores.
10035   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
10036     // Look for stores, and handle non-store uses conservatively.
10037     const auto *SI = dyn_cast<StoreInst>(&I);
10038     if (!SI) {
10039       // We will look through cast uses, so ignore them completely.
10040       if (I.isCast())
10041         continue;
10042       // Ignore debug info and pseudo op intrinsics, they don't escape or store
10043       // to allocas.
10044       if (I.isDebugOrPseudoInst())
10045         continue;
10046       // This is an unknown instruction. Assume it escapes or writes to all
10047       // static alloca operands.
10048       for (const Use &U : I.operands()) {
10049         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
10050           *Info = StaticAllocaInfo::Clobbered;
10051       }
10052       continue;
10053     }
10054 
10055     // If the stored value is a static alloca, mark it as escaped.
10056     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
10057       *Info = StaticAllocaInfo::Clobbered;
10058 
10059     // Check if the destination is a static alloca.
10060     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
10061     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
10062     if (!Info)
10063       continue;
10064     const AllocaInst *AI = cast<AllocaInst>(Dst);
10065 
10066     // Skip allocas that have been initialized or clobbered.
10067     if (*Info != StaticAllocaInfo::Unknown)
10068       continue;
10069 
10070     // Check if the stored value is an argument, and that this store fully
10071     // initializes the alloca.
10072     // If the argument type has padding bits we can't directly forward a pointer
10073     // as the upper bits may contain garbage.
10074     // Don't elide copies from the same argument twice.
10075     const Value *Val = SI->getValueOperand()->stripPointerCasts();
10076     const auto *Arg = dyn_cast<Argument>(Val);
10077     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
10078         Arg->getType()->isEmptyTy() ||
10079         DL.getTypeStoreSize(Arg->getType()) !=
10080             DL.getTypeAllocSize(AI->getAllocatedType()) ||
10081         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
10082         ArgCopyElisionCandidates.count(Arg)) {
10083       *Info = StaticAllocaInfo::Clobbered;
10084       continue;
10085     }
10086 
10087     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
10088                       << '\n');
10089 
10090     // Mark this alloca and store for argument copy elision.
10091     *Info = StaticAllocaInfo::Elidable;
10092     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
10093 
10094     // Stop scanning if we've seen all arguments. This will happen early in -O0
10095     // builds, which is useful, because -O0 builds have large entry blocks and
10096     // many allocas.
10097     if (ArgCopyElisionCandidates.size() == NumArgs)
10098       break;
10099   }
10100 }
10101 
10102 /// Try to elide argument copies from memory into a local alloca. Succeeds if
10103 /// ArgVal is a load from a suitable fixed stack object.
10104 static void tryToElideArgumentCopy(
10105     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
10106     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
10107     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
10108     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
10109     SDValue ArgVal, bool &ArgHasUses) {
10110   // Check if this is a load from a fixed stack object.
10111   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
10112   if (!LNode)
10113     return;
10114   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
10115   if (!FINode)
10116     return;
10117 
10118   // Check that the fixed stack object is the right size and alignment.
10119   // Look at the alignment that the user wrote on the alloca instead of looking
10120   // at the stack object.
10121   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
10122   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
10123   const AllocaInst *AI = ArgCopyIter->second.first;
10124   int FixedIndex = FINode->getIndex();
10125   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
10126   int OldIndex = AllocaIndex;
10127   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
10128   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
10129     LLVM_DEBUG(
10130         dbgs() << "  argument copy elision failed due to bad fixed stack "
10131                   "object size\n");
10132     return;
10133   }
10134   Align RequiredAlignment = AI->getAlign();
10135   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
10136     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
10137                          "greater than stack argument alignment ("
10138                       << DebugStr(RequiredAlignment) << " vs "
10139                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
10140     return;
10141   }
10142 
10143   // Perform the elision. Delete the old stack object and replace its only use
10144   // in the variable info map. Mark the stack object as mutable.
10145   LLVM_DEBUG({
10146     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
10147            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
10148            << '\n';
10149   });
10150   MFI.RemoveStackObject(OldIndex);
10151   MFI.setIsImmutableObjectIndex(FixedIndex, false);
10152   AllocaIndex = FixedIndex;
10153   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
10154   Chains.push_back(ArgVal.getValue(1));
10155 
10156   // Avoid emitting code for the store implementing the copy.
10157   const StoreInst *SI = ArgCopyIter->second.second;
10158   ElidedArgCopyInstrs.insert(SI);
10159 
10160   // Check for uses of the argument again so that we can avoid exporting ArgVal
10161   // if it is't used by anything other than the store.
10162   for (const Value *U : Arg.users()) {
10163     if (U != SI) {
10164       ArgHasUses = true;
10165       break;
10166     }
10167   }
10168 }
10169 
10170 void SelectionDAGISel::LowerArguments(const Function &F) {
10171   SelectionDAG &DAG = SDB->DAG;
10172   SDLoc dl = SDB->getCurSDLoc();
10173   const DataLayout &DL = DAG.getDataLayout();
10174   SmallVector<ISD::InputArg, 16> Ins;
10175 
10176   // In Naked functions we aren't going to save any registers.
10177   if (F.hasFnAttribute(Attribute::Naked))
10178     return;
10179 
10180   if (!FuncInfo->CanLowerReturn) {
10181     // Put in an sret pointer parameter before all the other parameters.
10182     SmallVector<EVT, 1> ValueVTs;
10183     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10184                     F.getReturnType()->getPointerTo(
10185                         DAG.getDataLayout().getAllocaAddrSpace()),
10186                     ValueVTs);
10187 
10188     // NOTE: Assuming that a pointer will never break down to more than one VT
10189     // or one register.
10190     ISD::ArgFlagsTy Flags;
10191     Flags.setSRet();
10192     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
10193     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
10194                          ISD::InputArg::NoArgIndex, 0);
10195     Ins.push_back(RetArg);
10196   }
10197 
10198   // Look for stores of arguments to static allocas. Mark such arguments with a
10199   // flag to ask the target to give us the memory location of that argument if
10200   // available.
10201   ArgCopyElisionMapTy ArgCopyElisionCandidates;
10202   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
10203                                     ArgCopyElisionCandidates);
10204 
10205   // Set up the incoming argument description vector.
10206   for (const Argument &Arg : F.args()) {
10207     unsigned ArgNo = Arg.getArgNo();
10208     SmallVector<EVT, 4> ValueVTs;
10209     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10210     bool isArgValueUsed = !Arg.use_empty();
10211     unsigned PartBase = 0;
10212     Type *FinalType = Arg.getType();
10213     if (Arg.hasAttribute(Attribute::ByVal))
10214       FinalType = Arg.getParamByValType();
10215     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
10216         FinalType, F.getCallingConv(), F.isVarArg(), DL);
10217     for (unsigned Value = 0, NumValues = ValueVTs.size();
10218          Value != NumValues; ++Value) {
10219       EVT VT = ValueVTs[Value];
10220       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
10221       ISD::ArgFlagsTy Flags;
10222 
10223 
10224       if (Arg.getType()->isPointerTy()) {
10225         Flags.setPointer();
10226         Flags.setPointerAddrSpace(
10227             cast<PointerType>(Arg.getType())->getAddressSpace());
10228       }
10229       if (Arg.hasAttribute(Attribute::ZExt))
10230         Flags.setZExt();
10231       if (Arg.hasAttribute(Attribute::SExt))
10232         Flags.setSExt();
10233       if (Arg.hasAttribute(Attribute::InReg)) {
10234         // If we are using vectorcall calling convention, a structure that is
10235         // passed InReg - is surely an HVA
10236         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
10237             isa<StructType>(Arg.getType())) {
10238           // The first value of a structure is marked
10239           if (0 == Value)
10240             Flags.setHvaStart();
10241           Flags.setHva();
10242         }
10243         // Set InReg Flag
10244         Flags.setInReg();
10245       }
10246       if (Arg.hasAttribute(Attribute::StructRet))
10247         Flags.setSRet();
10248       if (Arg.hasAttribute(Attribute::SwiftSelf))
10249         Flags.setSwiftSelf();
10250       if (Arg.hasAttribute(Attribute::SwiftAsync))
10251         Flags.setSwiftAsync();
10252       if (Arg.hasAttribute(Attribute::SwiftError))
10253         Flags.setSwiftError();
10254       if (Arg.hasAttribute(Attribute::ByVal))
10255         Flags.setByVal();
10256       if (Arg.hasAttribute(Attribute::ByRef))
10257         Flags.setByRef();
10258       if (Arg.hasAttribute(Attribute::InAlloca)) {
10259         Flags.setInAlloca();
10260         // Set the byval flag for CCAssignFn callbacks that don't know about
10261         // inalloca.  This way we can know how many bytes we should've allocated
10262         // and how many bytes a callee cleanup function will pop.  If we port
10263         // inalloca to more targets, we'll have to add custom inalloca handling
10264         // in the various CC lowering callbacks.
10265         Flags.setByVal();
10266       }
10267       if (Arg.hasAttribute(Attribute::Preallocated)) {
10268         Flags.setPreallocated();
10269         // Set the byval flag for CCAssignFn callbacks that don't know about
10270         // preallocated.  This way we can know how many bytes we should've
10271         // allocated and how many bytes a callee cleanup function will pop.  If
10272         // we port preallocated to more targets, we'll have to add custom
10273         // preallocated handling in the various CC lowering callbacks.
10274         Flags.setByVal();
10275       }
10276 
10277       // Certain targets (such as MIPS), may have a different ABI alignment
10278       // for a type depending on the context. Give the target a chance to
10279       // specify the alignment it wants.
10280       const Align OriginalAlignment(
10281           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
10282       Flags.setOrigAlign(OriginalAlignment);
10283 
10284       Align MemAlign;
10285       Type *ArgMemTy = nullptr;
10286       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
10287           Flags.isByRef()) {
10288         if (!ArgMemTy)
10289           ArgMemTy = Arg.getPointeeInMemoryValueType();
10290 
10291         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
10292 
10293         // For in-memory arguments, size and alignment should be passed from FE.
10294         // BE will guess if this info is not there but there are cases it cannot
10295         // get right.
10296         if (auto ParamAlign = Arg.getParamStackAlign())
10297           MemAlign = *ParamAlign;
10298         else if ((ParamAlign = Arg.getParamAlign()))
10299           MemAlign = *ParamAlign;
10300         else
10301           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
10302         if (Flags.isByRef())
10303           Flags.setByRefSize(MemSize);
10304         else
10305           Flags.setByValSize(MemSize);
10306       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
10307         MemAlign = *ParamAlign;
10308       } else {
10309         MemAlign = OriginalAlignment;
10310       }
10311       Flags.setMemAlign(MemAlign);
10312 
10313       if (Arg.hasAttribute(Attribute::Nest))
10314         Flags.setNest();
10315       if (NeedsRegBlock)
10316         Flags.setInConsecutiveRegs();
10317       if (ArgCopyElisionCandidates.count(&Arg))
10318         Flags.setCopyElisionCandidate();
10319       if (Arg.hasAttribute(Attribute::Returned))
10320         Flags.setReturned();
10321 
10322       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
10323           *CurDAG->getContext(), F.getCallingConv(), VT);
10324       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
10325           *CurDAG->getContext(), F.getCallingConv(), VT);
10326       for (unsigned i = 0; i != NumRegs; ++i) {
10327         // For scalable vectors, use the minimum size; individual targets
10328         // are responsible for handling scalable vector arguments and
10329         // return values.
10330         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
10331                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
10332         if (NumRegs > 1 && i == 0)
10333           MyFlags.Flags.setSplit();
10334         // if it isn't first piece, alignment must be 1
10335         else if (i > 0) {
10336           MyFlags.Flags.setOrigAlign(Align(1));
10337           if (i == NumRegs - 1)
10338             MyFlags.Flags.setSplitEnd();
10339         }
10340         Ins.push_back(MyFlags);
10341       }
10342       if (NeedsRegBlock && Value == NumValues - 1)
10343         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
10344       PartBase += VT.getStoreSize().getKnownMinSize();
10345     }
10346   }
10347 
10348   // Call the target to set up the argument values.
10349   SmallVector<SDValue, 8> InVals;
10350   SDValue NewRoot = TLI->LowerFormalArguments(
10351       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
10352 
10353   // Verify that the target's LowerFormalArguments behaved as expected.
10354   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
10355          "LowerFormalArguments didn't return a valid chain!");
10356   assert(InVals.size() == Ins.size() &&
10357          "LowerFormalArguments didn't emit the correct number of values!");
10358   LLVM_DEBUG({
10359     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10360       assert(InVals[i].getNode() &&
10361              "LowerFormalArguments emitted a null value!");
10362       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10363              "LowerFormalArguments emitted a value with the wrong type!");
10364     }
10365   });
10366 
10367   // Update the DAG with the new chain value resulting from argument lowering.
10368   DAG.setRoot(NewRoot);
10369 
10370   // Set up the argument values.
10371   unsigned i = 0;
10372   if (!FuncInfo->CanLowerReturn) {
10373     // Create a virtual register for the sret pointer, and put in a copy
10374     // from the sret argument into it.
10375     SmallVector<EVT, 1> ValueVTs;
10376     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10377                     F.getReturnType()->getPointerTo(
10378                         DAG.getDataLayout().getAllocaAddrSpace()),
10379                     ValueVTs);
10380     MVT VT = ValueVTs[0].getSimpleVT();
10381     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10382     Optional<ISD::NodeType> AssertOp = None;
10383     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10384                                         nullptr, F.getCallingConv(), AssertOp);
10385 
10386     MachineFunction& MF = SDB->DAG.getMachineFunction();
10387     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10388     Register SRetReg =
10389         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10390     FuncInfo->DemoteRegister = SRetReg;
10391     NewRoot =
10392         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10393     DAG.setRoot(NewRoot);
10394 
10395     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10396     ++i;
10397   }
10398 
10399   SmallVector<SDValue, 4> Chains;
10400   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10401   for (const Argument &Arg : F.args()) {
10402     SmallVector<SDValue, 4> ArgValues;
10403     SmallVector<EVT, 4> ValueVTs;
10404     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10405     unsigned NumValues = ValueVTs.size();
10406     if (NumValues == 0)
10407       continue;
10408 
10409     bool ArgHasUses = !Arg.use_empty();
10410 
10411     // Elide the copying store if the target loaded this argument from a
10412     // suitable fixed stack object.
10413     if (Ins[i].Flags.isCopyElisionCandidate()) {
10414       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10415                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10416                              InVals[i], ArgHasUses);
10417     }
10418 
10419     // If this argument is unused then remember its value. It is used to generate
10420     // debugging information.
10421     bool isSwiftErrorArg =
10422         TLI->supportSwiftError() &&
10423         Arg.hasAttribute(Attribute::SwiftError);
10424     if (!ArgHasUses && !isSwiftErrorArg) {
10425       SDB->setUnusedArgValue(&Arg, InVals[i]);
10426 
10427       // Also remember any frame index for use in FastISel.
10428       if (FrameIndexSDNode *FI =
10429           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10430         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10431     }
10432 
10433     for (unsigned Val = 0; Val != NumValues; ++Val) {
10434       EVT VT = ValueVTs[Val];
10435       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10436                                                       F.getCallingConv(), VT);
10437       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10438           *CurDAG->getContext(), F.getCallingConv(), VT);
10439 
10440       // Even an apparent 'unused' swifterror argument needs to be returned. So
10441       // we do generate a copy for it that can be used on return from the
10442       // function.
10443       if (ArgHasUses || isSwiftErrorArg) {
10444         Optional<ISD::NodeType> AssertOp;
10445         if (Arg.hasAttribute(Attribute::SExt))
10446           AssertOp = ISD::AssertSext;
10447         else if (Arg.hasAttribute(Attribute::ZExt))
10448           AssertOp = ISD::AssertZext;
10449 
10450         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10451                                              PartVT, VT, nullptr,
10452                                              F.getCallingConv(), AssertOp));
10453       }
10454 
10455       i += NumParts;
10456     }
10457 
10458     // We don't need to do anything else for unused arguments.
10459     if (ArgValues.empty())
10460       continue;
10461 
10462     // Note down frame index.
10463     if (FrameIndexSDNode *FI =
10464         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10465       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10466 
10467     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10468                                      SDB->getCurSDLoc());
10469 
10470     SDB->setValue(&Arg, Res);
10471     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10472       // We want to associate the argument with the frame index, among
10473       // involved operands, that correspond to the lowest address. The
10474       // getCopyFromParts function, called earlier, is swapping the order of
10475       // the operands to BUILD_PAIR depending on endianness. The result of
10476       // that swapping is that the least significant bits of the argument will
10477       // be in the first operand of the BUILD_PAIR node, and the most
10478       // significant bits will be in the second operand.
10479       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10480       if (LoadSDNode *LNode =
10481           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10482         if (FrameIndexSDNode *FI =
10483             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10484           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10485     }
10486 
10487     // Analyses past this point are naive and don't expect an assertion.
10488     if (Res.getOpcode() == ISD::AssertZext)
10489       Res = Res.getOperand(0);
10490 
10491     // Update the SwiftErrorVRegDefMap.
10492     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10493       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10494       if (Register::isVirtualRegister(Reg))
10495         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10496                                    Reg);
10497     }
10498 
10499     // If this argument is live outside of the entry block, insert a copy from
10500     // wherever we got it to the vreg that other BB's will reference it as.
10501     if (Res.getOpcode() == ISD::CopyFromReg) {
10502       // If we can, though, try to skip creating an unnecessary vreg.
10503       // FIXME: This isn't very clean... it would be nice to make this more
10504       // general.
10505       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10506       if (Register::isVirtualRegister(Reg)) {
10507         FuncInfo->ValueMap[&Arg] = Reg;
10508         continue;
10509       }
10510     }
10511     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10512       FuncInfo->InitializeRegForValue(&Arg);
10513       SDB->CopyToExportRegsIfNeeded(&Arg);
10514     }
10515   }
10516 
10517   if (!Chains.empty()) {
10518     Chains.push_back(NewRoot);
10519     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10520   }
10521 
10522   DAG.setRoot(NewRoot);
10523 
10524   assert(i == InVals.size() && "Argument register count mismatch!");
10525 
10526   // If any argument copy elisions occurred and we have debug info, update the
10527   // stale frame indices used in the dbg.declare variable info table.
10528   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10529   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10530     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10531       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10532       if (I != ArgCopyElisionFrameIndexMap.end())
10533         VI.Slot = I->second;
10534     }
10535   }
10536 
10537   // Finally, if the target has anything special to do, allow it to do so.
10538   emitFunctionEntryCode();
10539 }
10540 
10541 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10542 /// ensure constants are generated when needed.  Remember the virtual registers
10543 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10544 /// directly add them, because expansion might result in multiple MBB's for one
10545 /// BB.  As such, the start of the BB might correspond to a different MBB than
10546 /// the end.
10547 void
10548 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10549   const Instruction *TI = LLVMBB->getTerminator();
10550 
10551   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10552 
10553   // Check PHI nodes in successors that expect a value to be available from this
10554   // block.
10555   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10556     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10557     if (!isa<PHINode>(SuccBB->begin())) continue;
10558     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10559 
10560     // If this terminator has multiple identical successors (common for
10561     // switches), only handle each succ once.
10562     if (!SuccsHandled.insert(SuccMBB).second)
10563       continue;
10564 
10565     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10566 
10567     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10568     // nodes and Machine PHI nodes, but the incoming operands have not been
10569     // emitted yet.
10570     for (const PHINode &PN : SuccBB->phis()) {
10571       // Ignore dead phi's.
10572       if (PN.use_empty())
10573         continue;
10574 
10575       // Skip empty types
10576       if (PN.getType()->isEmptyTy())
10577         continue;
10578 
10579       unsigned Reg;
10580       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10581 
10582       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10583         unsigned &RegOut = ConstantsOut[C];
10584         if (RegOut == 0) {
10585           RegOut = FuncInfo.CreateRegs(C);
10586           CopyValueToVirtualRegister(C, RegOut);
10587         }
10588         Reg = RegOut;
10589       } else {
10590         DenseMap<const Value *, Register>::iterator I =
10591           FuncInfo.ValueMap.find(PHIOp);
10592         if (I != FuncInfo.ValueMap.end())
10593           Reg = I->second;
10594         else {
10595           assert(isa<AllocaInst>(PHIOp) &&
10596                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10597                  "Didn't codegen value into a register!??");
10598           Reg = FuncInfo.CreateRegs(PHIOp);
10599           CopyValueToVirtualRegister(PHIOp, Reg);
10600         }
10601       }
10602 
10603       // Remember that this register needs to added to the machine PHI node as
10604       // the input for this MBB.
10605       SmallVector<EVT, 4> ValueVTs;
10606       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10607       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10608       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10609         EVT VT = ValueVTs[vti];
10610         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10611         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10612           FuncInfo.PHINodesToUpdate.push_back(
10613               std::make_pair(&*MBBI++, Reg + i));
10614         Reg += NumRegisters;
10615       }
10616     }
10617   }
10618 
10619   ConstantsOut.clear();
10620 }
10621 
10622 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10623   MachineFunction::iterator I(MBB);
10624   if (++I == FuncInfo.MF->end())
10625     return nullptr;
10626   return &*I;
10627 }
10628 
10629 /// During lowering new call nodes can be created (such as memset, etc.).
10630 /// Those will become new roots of the current DAG, but complications arise
10631 /// when they are tail calls. In such cases, the call lowering will update
10632 /// the root, but the builder still needs to know that a tail call has been
10633 /// lowered in order to avoid generating an additional return.
10634 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10635   // If the node is null, we do have a tail call.
10636   if (MaybeTC.getNode() != nullptr)
10637     DAG.setRoot(MaybeTC);
10638   else
10639     HasTailCall = true;
10640 }
10641 
10642 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10643                                         MachineBasicBlock *SwitchMBB,
10644                                         MachineBasicBlock *DefaultMBB) {
10645   MachineFunction *CurMF = FuncInfo.MF;
10646   MachineBasicBlock *NextMBB = nullptr;
10647   MachineFunction::iterator BBI(W.MBB);
10648   if (++BBI != FuncInfo.MF->end())
10649     NextMBB = &*BBI;
10650 
10651   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10652 
10653   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10654 
10655   if (Size == 2 && W.MBB == SwitchMBB) {
10656     // If any two of the cases has the same destination, and if one value
10657     // is the same as the other, but has one bit unset that the other has set,
10658     // use bit manipulation to do two compares at once.  For example:
10659     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10660     // TODO: This could be extended to merge any 2 cases in switches with 3
10661     // cases.
10662     // TODO: Handle cases where W.CaseBB != SwitchBB.
10663     CaseCluster &Small = *W.FirstCluster;
10664     CaseCluster &Big = *W.LastCluster;
10665 
10666     if (Small.Low == Small.High && Big.Low == Big.High &&
10667         Small.MBB == Big.MBB) {
10668       const APInt &SmallValue = Small.Low->getValue();
10669       const APInt &BigValue = Big.Low->getValue();
10670 
10671       // Check that there is only one bit different.
10672       APInt CommonBit = BigValue ^ SmallValue;
10673       if (CommonBit.isPowerOf2()) {
10674         SDValue CondLHS = getValue(Cond);
10675         EVT VT = CondLHS.getValueType();
10676         SDLoc DL = getCurSDLoc();
10677 
10678         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10679                                  DAG.getConstant(CommonBit, DL, VT));
10680         SDValue Cond = DAG.getSetCC(
10681             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10682             ISD::SETEQ);
10683 
10684         // Update successor info.
10685         // Both Small and Big will jump to Small.BB, so we sum up the
10686         // probabilities.
10687         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10688         if (BPI)
10689           addSuccessorWithProb(
10690               SwitchMBB, DefaultMBB,
10691               // The default destination is the first successor in IR.
10692               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10693         else
10694           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10695 
10696         // Insert the true branch.
10697         SDValue BrCond =
10698             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10699                         DAG.getBasicBlock(Small.MBB));
10700         // Insert the false branch.
10701         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10702                              DAG.getBasicBlock(DefaultMBB));
10703 
10704         DAG.setRoot(BrCond);
10705         return;
10706       }
10707     }
10708   }
10709 
10710   if (TM.getOptLevel() != CodeGenOpt::None) {
10711     // Here, we order cases by probability so the most likely case will be
10712     // checked first. However, two clusters can have the same probability in
10713     // which case their relative ordering is non-deterministic. So we use Low
10714     // as a tie-breaker as clusters are guaranteed to never overlap.
10715     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10716                [](const CaseCluster &a, const CaseCluster &b) {
10717       return a.Prob != b.Prob ?
10718              a.Prob > b.Prob :
10719              a.Low->getValue().slt(b.Low->getValue());
10720     });
10721 
10722     // Rearrange the case blocks so that the last one falls through if possible
10723     // without changing the order of probabilities.
10724     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10725       --I;
10726       if (I->Prob > W.LastCluster->Prob)
10727         break;
10728       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10729         std::swap(*I, *W.LastCluster);
10730         break;
10731       }
10732     }
10733   }
10734 
10735   // Compute total probability.
10736   BranchProbability DefaultProb = W.DefaultProb;
10737   BranchProbability UnhandledProbs = DefaultProb;
10738   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10739     UnhandledProbs += I->Prob;
10740 
10741   MachineBasicBlock *CurMBB = W.MBB;
10742   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10743     bool FallthroughUnreachable = false;
10744     MachineBasicBlock *Fallthrough;
10745     if (I == W.LastCluster) {
10746       // For the last cluster, fall through to the default destination.
10747       Fallthrough = DefaultMBB;
10748       FallthroughUnreachable = isa<UnreachableInst>(
10749           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10750     } else {
10751       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10752       CurMF->insert(BBI, Fallthrough);
10753       // Put Cond in a virtual register to make it available from the new blocks.
10754       ExportFromCurrentBlock(Cond);
10755     }
10756     UnhandledProbs -= I->Prob;
10757 
10758     switch (I->Kind) {
10759       case CC_JumpTable: {
10760         // FIXME: Optimize away range check based on pivot comparisons.
10761         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10762         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10763 
10764         // The jump block hasn't been inserted yet; insert it here.
10765         MachineBasicBlock *JumpMBB = JT->MBB;
10766         CurMF->insert(BBI, JumpMBB);
10767 
10768         auto JumpProb = I->Prob;
10769         auto FallthroughProb = UnhandledProbs;
10770 
10771         // If the default statement is a target of the jump table, we evenly
10772         // distribute the default probability to successors of CurMBB. Also
10773         // update the probability on the edge from JumpMBB to Fallthrough.
10774         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10775                                               SE = JumpMBB->succ_end();
10776              SI != SE; ++SI) {
10777           if (*SI == DefaultMBB) {
10778             JumpProb += DefaultProb / 2;
10779             FallthroughProb -= DefaultProb / 2;
10780             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10781             JumpMBB->normalizeSuccProbs();
10782             break;
10783           }
10784         }
10785 
10786         if (FallthroughUnreachable)
10787           JTH->FallthroughUnreachable = true;
10788 
10789         if (!JTH->FallthroughUnreachable)
10790           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10791         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10792         CurMBB->normalizeSuccProbs();
10793 
10794         // The jump table header will be inserted in our current block, do the
10795         // range check, and fall through to our fallthrough block.
10796         JTH->HeaderBB = CurMBB;
10797         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10798 
10799         // If we're in the right place, emit the jump table header right now.
10800         if (CurMBB == SwitchMBB) {
10801           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10802           JTH->Emitted = true;
10803         }
10804         break;
10805       }
10806       case CC_BitTests: {
10807         // FIXME: Optimize away range check based on pivot comparisons.
10808         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10809 
10810         // The bit test blocks haven't been inserted yet; insert them here.
10811         for (BitTestCase &BTC : BTB->Cases)
10812           CurMF->insert(BBI, BTC.ThisBB);
10813 
10814         // Fill in fields of the BitTestBlock.
10815         BTB->Parent = CurMBB;
10816         BTB->Default = Fallthrough;
10817 
10818         BTB->DefaultProb = UnhandledProbs;
10819         // If the cases in bit test don't form a contiguous range, we evenly
10820         // distribute the probability on the edge to Fallthrough to two
10821         // successors of CurMBB.
10822         if (!BTB->ContiguousRange) {
10823           BTB->Prob += DefaultProb / 2;
10824           BTB->DefaultProb -= DefaultProb / 2;
10825         }
10826 
10827         if (FallthroughUnreachable)
10828           BTB->FallthroughUnreachable = true;
10829 
10830         // If we're in the right place, emit the bit test header right now.
10831         if (CurMBB == SwitchMBB) {
10832           visitBitTestHeader(*BTB, SwitchMBB);
10833           BTB->Emitted = true;
10834         }
10835         break;
10836       }
10837       case CC_Range: {
10838         const Value *RHS, *LHS, *MHS;
10839         ISD::CondCode CC;
10840         if (I->Low == I->High) {
10841           // Check Cond == I->Low.
10842           CC = ISD::SETEQ;
10843           LHS = Cond;
10844           RHS=I->Low;
10845           MHS = nullptr;
10846         } else {
10847           // Check I->Low <= Cond <= I->High.
10848           CC = ISD::SETLE;
10849           LHS = I->Low;
10850           MHS = Cond;
10851           RHS = I->High;
10852         }
10853 
10854         // If Fallthrough is unreachable, fold away the comparison.
10855         if (FallthroughUnreachable)
10856           CC = ISD::SETTRUE;
10857 
10858         // The false probability is the sum of all unhandled cases.
10859         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10860                      getCurSDLoc(), I->Prob, UnhandledProbs);
10861 
10862         if (CurMBB == SwitchMBB)
10863           visitSwitchCase(CB, SwitchMBB);
10864         else
10865           SL->SwitchCases.push_back(CB);
10866 
10867         break;
10868       }
10869     }
10870     CurMBB = Fallthrough;
10871   }
10872 }
10873 
10874 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10875                                               CaseClusterIt First,
10876                                               CaseClusterIt Last) {
10877   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10878     if (X.Prob != CC.Prob)
10879       return X.Prob > CC.Prob;
10880 
10881     // Ties are broken by comparing the case value.
10882     return X.Low->getValue().slt(CC.Low->getValue());
10883   });
10884 }
10885 
10886 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10887                                         const SwitchWorkListItem &W,
10888                                         Value *Cond,
10889                                         MachineBasicBlock *SwitchMBB) {
10890   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10891          "Clusters not sorted?");
10892 
10893   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10894 
10895   // Balance the tree based on branch probabilities to create a near-optimal (in
10896   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10897   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10898   CaseClusterIt LastLeft = W.FirstCluster;
10899   CaseClusterIt FirstRight = W.LastCluster;
10900   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10901   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10902 
10903   // Move LastLeft and FirstRight towards each other from opposite directions to
10904   // find a partitioning of the clusters which balances the probability on both
10905   // sides. If LeftProb and RightProb are equal, alternate which side is
10906   // taken to ensure 0-probability nodes are distributed evenly.
10907   unsigned I = 0;
10908   while (LastLeft + 1 < FirstRight) {
10909     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10910       LeftProb += (++LastLeft)->Prob;
10911     else
10912       RightProb += (--FirstRight)->Prob;
10913     I++;
10914   }
10915 
10916   while (true) {
10917     // Our binary search tree differs from a typical BST in that ours can have up
10918     // to three values in each leaf. The pivot selection above doesn't take that
10919     // into account, which means the tree might require more nodes and be less
10920     // efficient. We compensate for this here.
10921 
10922     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10923     unsigned NumRight = W.LastCluster - FirstRight + 1;
10924 
10925     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10926       // If one side has less than 3 clusters, and the other has more than 3,
10927       // consider taking a cluster from the other side.
10928 
10929       if (NumLeft < NumRight) {
10930         // Consider moving the first cluster on the right to the left side.
10931         CaseCluster &CC = *FirstRight;
10932         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10933         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10934         if (LeftSideRank <= RightSideRank) {
10935           // Moving the cluster to the left does not demote it.
10936           ++LastLeft;
10937           ++FirstRight;
10938           continue;
10939         }
10940       } else {
10941         assert(NumRight < NumLeft);
10942         // Consider moving the last element on the left to the right side.
10943         CaseCluster &CC = *LastLeft;
10944         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10945         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10946         if (RightSideRank <= LeftSideRank) {
10947           // Moving the cluster to the right does not demot it.
10948           --LastLeft;
10949           --FirstRight;
10950           continue;
10951         }
10952       }
10953     }
10954     break;
10955   }
10956 
10957   assert(LastLeft + 1 == FirstRight);
10958   assert(LastLeft >= W.FirstCluster);
10959   assert(FirstRight <= W.LastCluster);
10960 
10961   // Use the first element on the right as pivot since we will make less-than
10962   // comparisons against it.
10963   CaseClusterIt PivotCluster = FirstRight;
10964   assert(PivotCluster > W.FirstCluster);
10965   assert(PivotCluster <= W.LastCluster);
10966 
10967   CaseClusterIt FirstLeft = W.FirstCluster;
10968   CaseClusterIt LastRight = W.LastCluster;
10969 
10970   const ConstantInt *Pivot = PivotCluster->Low;
10971 
10972   // New blocks will be inserted immediately after the current one.
10973   MachineFunction::iterator BBI(W.MBB);
10974   ++BBI;
10975 
10976   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10977   // we can branch to its destination directly if it's squeezed exactly in
10978   // between the known lower bound and Pivot - 1.
10979   MachineBasicBlock *LeftMBB;
10980   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10981       FirstLeft->Low == W.GE &&
10982       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10983     LeftMBB = FirstLeft->MBB;
10984   } else {
10985     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10986     FuncInfo.MF->insert(BBI, LeftMBB);
10987     WorkList.push_back(
10988         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10989     // Put Cond in a virtual register to make it available from the new blocks.
10990     ExportFromCurrentBlock(Cond);
10991   }
10992 
10993   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10994   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10995   // directly if RHS.High equals the current upper bound.
10996   MachineBasicBlock *RightMBB;
10997   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10998       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10999     RightMBB = FirstRight->MBB;
11000   } else {
11001     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11002     FuncInfo.MF->insert(BBI, RightMBB);
11003     WorkList.push_back(
11004         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11005     // Put Cond in a virtual register to make it available from the new blocks.
11006     ExportFromCurrentBlock(Cond);
11007   }
11008 
11009   // Create the CaseBlock record that will be used to lower the branch.
11010   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11011                getCurSDLoc(), LeftProb, RightProb);
11012 
11013   if (W.MBB == SwitchMBB)
11014     visitSwitchCase(CB, SwitchMBB);
11015   else
11016     SL->SwitchCases.push_back(CB);
11017 }
11018 
11019 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11020 // from the swith statement.
11021 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11022                                             BranchProbability PeeledCaseProb) {
11023   if (PeeledCaseProb == BranchProbability::getOne())
11024     return BranchProbability::getZero();
11025   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11026 
11027   uint32_t Numerator = CaseProb.getNumerator();
11028   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11029   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11030 }
11031 
11032 // Try to peel the top probability case if it exceeds the threshold.
11033 // Return current MachineBasicBlock for the switch statement if the peeling
11034 // does not occur.
11035 // If the peeling is performed, return the newly created MachineBasicBlock
11036 // for the peeled switch statement. Also update Clusters to remove the peeled
11037 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11038 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11039     const SwitchInst &SI, CaseClusterVector &Clusters,
11040     BranchProbability &PeeledCaseProb) {
11041   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11042   // Don't perform if there is only one cluster or optimizing for size.
11043   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11044       TM.getOptLevel() == CodeGenOpt::None ||
11045       SwitchMBB->getParent()->getFunction().hasMinSize())
11046     return SwitchMBB;
11047 
11048   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11049   unsigned PeeledCaseIndex = 0;
11050   bool SwitchPeeled = false;
11051   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11052     CaseCluster &CC = Clusters[Index];
11053     if (CC.Prob < TopCaseProb)
11054       continue;
11055     TopCaseProb = CC.Prob;
11056     PeeledCaseIndex = Index;
11057     SwitchPeeled = true;
11058   }
11059   if (!SwitchPeeled)
11060     return SwitchMBB;
11061 
11062   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11063                     << TopCaseProb << "\n");
11064 
11065   // Record the MBB for the peeled switch statement.
11066   MachineFunction::iterator BBI(SwitchMBB);
11067   ++BBI;
11068   MachineBasicBlock *PeeledSwitchMBB =
11069       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
11070   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
11071 
11072   ExportFromCurrentBlock(SI.getCondition());
11073   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
11074   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
11075                           nullptr,   nullptr,      TopCaseProb.getCompl()};
11076   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
11077 
11078   Clusters.erase(PeeledCaseIt);
11079   for (CaseCluster &CC : Clusters) {
11080     LLVM_DEBUG(
11081         dbgs() << "Scale the probablity for one cluster, before scaling: "
11082                << CC.Prob << "\n");
11083     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
11084     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
11085   }
11086   PeeledCaseProb = TopCaseProb;
11087   return PeeledSwitchMBB;
11088 }
11089 
11090 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
11091   // Extract cases from the switch.
11092   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11093   CaseClusterVector Clusters;
11094   Clusters.reserve(SI.getNumCases());
11095   for (auto I : SI.cases()) {
11096     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
11097     const ConstantInt *CaseVal = I.getCaseValue();
11098     BranchProbability Prob =
11099         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
11100             : BranchProbability(1, SI.getNumCases() + 1);
11101     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
11102   }
11103 
11104   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
11105 
11106   // Cluster adjacent cases with the same destination. We do this at all
11107   // optimization levels because it's cheap to do and will make codegen faster
11108   // if there are many clusters.
11109   sortAndRangeify(Clusters);
11110 
11111   // The branch probablity of the peeled case.
11112   BranchProbability PeeledCaseProb = BranchProbability::getZero();
11113   MachineBasicBlock *PeeledSwitchMBB =
11114       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
11115 
11116   // If there is only the default destination, jump there directly.
11117   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11118   if (Clusters.empty()) {
11119     assert(PeeledSwitchMBB == SwitchMBB);
11120     SwitchMBB->addSuccessor(DefaultMBB);
11121     if (DefaultMBB != NextBlock(SwitchMBB)) {
11122       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
11123                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
11124     }
11125     return;
11126   }
11127 
11128   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
11129   SL->findBitTestClusters(Clusters, &SI);
11130 
11131   LLVM_DEBUG({
11132     dbgs() << "Case clusters: ";
11133     for (const CaseCluster &C : Clusters) {
11134       if (C.Kind == CC_JumpTable)
11135         dbgs() << "JT:";
11136       if (C.Kind == CC_BitTests)
11137         dbgs() << "BT:";
11138 
11139       C.Low->getValue().print(dbgs(), true);
11140       if (C.Low != C.High) {
11141         dbgs() << '-';
11142         C.High->getValue().print(dbgs(), true);
11143       }
11144       dbgs() << ' ';
11145     }
11146     dbgs() << '\n';
11147   });
11148 
11149   assert(!Clusters.empty());
11150   SwitchWorkList WorkList;
11151   CaseClusterIt First = Clusters.begin();
11152   CaseClusterIt Last = Clusters.end() - 1;
11153   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
11154   // Scale the branchprobability for DefaultMBB if the peel occurs and
11155   // DefaultMBB is not replaced.
11156   if (PeeledCaseProb != BranchProbability::getZero() &&
11157       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
11158     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
11159   WorkList.push_back(
11160       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
11161 
11162   while (!WorkList.empty()) {
11163     SwitchWorkListItem W = WorkList.pop_back_val();
11164     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
11165 
11166     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
11167         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
11168       // For optimized builds, lower large range as a balanced binary tree.
11169       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
11170       continue;
11171     }
11172 
11173     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
11174   }
11175 }
11176 
11177 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
11178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11179   auto DL = getCurSDLoc();
11180   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11181   setValue(&I, DAG.getStepVector(DL, ResultVT));
11182 }
11183 
11184 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
11185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11186   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11187 
11188   SDLoc DL = getCurSDLoc();
11189   SDValue V = getValue(I.getOperand(0));
11190   assert(VT == V.getValueType() && "Malformed vector.reverse!");
11191 
11192   if (VT.isScalableVector()) {
11193     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
11194     return;
11195   }
11196 
11197   // Use VECTOR_SHUFFLE for the fixed-length vector
11198   // to maintain existing behavior.
11199   SmallVector<int, 8> Mask;
11200   unsigned NumElts = VT.getVectorMinNumElements();
11201   for (unsigned i = 0; i != NumElts; ++i)
11202     Mask.push_back(NumElts - 1 - i);
11203 
11204   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
11205 }
11206 
11207 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
11208   SmallVector<EVT, 4> ValueVTs;
11209   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
11210                   ValueVTs);
11211   unsigned NumValues = ValueVTs.size();
11212   if (NumValues == 0) return;
11213 
11214   SmallVector<SDValue, 4> Values(NumValues);
11215   SDValue Op = getValue(I.getOperand(0));
11216 
11217   for (unsigned i = 0; i != NumValues; ++i)
11218     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
11219                             SDValue(Op.getNode(), Op.getResNo() + i));
11220 
11221   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
11222                            DAG.getVTList(ValueVTs), Values));
11223 }
11224 
11225 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
11226   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11227   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
11228 
11229   SDLoc DL = getCurSDLoc();
11230   SDValue V1 = getValue(I.getOperand(0));
11231   SDValue V2 = getValue(I.getOperand(1));
11232   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
11233 
11234   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
11235   if (VT.isScalableVector()) {
11236     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
11237     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
11238                              DAG.getConstant(Imm, DL, IdxVT)));
11239     return;
11240   }
11241 
11242   unsigned NumElts = VT.getVectorNumElements();
11243 
11244   if ((-Imm > NumElts) || (Imm >= NumElts)) {
11245     // Result is undefined if immediate is out-of-bounds.
11246     setValue(&I, DAG.getUNDEF(VT));
11247     return;
11248   }
11249 
11250   uint64_t Idx = (NumElts + Imm) % NumElts;
11251 
11252   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
11253   SmallVector<int, 8> Mask;
11254   for (unsigned i = 0; i < NumElts; ++i)
11255     Mask.push_back(Idx + i);
11256   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
11257 }
11258