xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 2d728bbff5c688284b8b8306ecfd3000b0ab8bb1)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/BranchProbabilityInfo.h"
29 #include "llvm/Analysis/ConstantFolding.h"
30 #include "llvm/Analysis/EHPersonalities.h"
31 #include "llvm/Analysis/Loads.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/ProfileSummaryInfo.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/ValueTracking.h"
36 #include "llvm/Analysis/VectorUtils.h"
37 #include "llvm/CodeGen/Analysis.h"
38 #include "llvm/CodeGen/FunctionLoweringInfo.h"
39 #include "llvm/CodeGen/GCMetadata.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
53 #include "llvm/CodeGen/StackMaps.h"
54 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
55 #include "llvm/CodeGen/TargetFrameLowering.h"
56 #include "llvm/CodeGen/TargetInstrInfo.h"
57 #include "llvm/CodeGen/TargetOpcodes.h"
58 #include "llvm/CodeGen/TargetRegisterInfo.h"
59 #include "llvm/CodeGen/TargetSubtargetInfo.h"
60 #include "llvm/CodeGen/WinEHFuncInfo.h"
61 #include "llvm/IR/Argument.h"
62 #include "llvm/IR/Attributes.h"
63 #include "llvm/IR/BasicBlock.h"
64 #include "llvm/IR/CFG.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/ConstantRange.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DebugInfoMetadata.h"
71 #include "llvm/IR/DerivedTypes.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsWebAssembly.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/Metadata.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Operator.h"
85 #include "llvm/IR/PatternMatch.h"
86 #include "llvm/IR/Statepoint.h"
87 #include "llvm/IR/Type.h"
88 #include "llvm/IR/User.h"
89 #include "llvm/IR/Value.h"
90 #include "llvm/MC/MCContext.h"
91 #include "llvm/MC/MCSymbol.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/MathExtras.h"
98 #include "llvm/Support/raw_ostream.h"
99 #include "llvm/Target/TargetIntrinsicInfo.h"
100 #include "llvm/Target/TargetMachine.h"
101 #include "llvm/Target/TargetOptions.h"
102 #include "llvm/Transforms/Utils/Local.h"
103 #include <cstddef>
104 #include <cstring>
105 #include <iterator>
106 #include <limits>
107 #include <numeric>
108 #include <tuple>
109 
110 using namespace llvm;
111 using namespace PatternMatch;
112 using namespace SwitchCG;
113 
114 #define DEBUG_TYPE "isel"
115 
116 /// LimitFloatPrecision - Generate low-precision inline sequences for
117 /// some float libcalls (6, 8 or 12 bits).
118 static unsigned LimitFloatPrecision;
119 
120 static cl::opt<bool>
121     InsertAssertAlign("insert-assert-align", cl::init(true),
122                       cl::desc("Insert the experimental `assertalign` node."),
123                       cl::ReallyHidden);
124 
125 static cl::opt<unsigned, true>
126     LimitFPPrecision("limit-float-precision",
127                      cl::desc("Generate low-precision inline sequences "
128                               "for some float libcalls"),
129                      cl::location(LimitFloatPrecision), cl::Hidden,
130                      cl::init(0));
131 
132 static cl::opt<unsigned> SwitchPeelThreshold(
133     "switch-peel-threshold", cl::Hidden, cl::init(66),
134     cl::desc("Set the case probability threshold for peeling the case from a "
135              "switch statement. A value greater than 100 will void this "
136              "optimization"));
137 
138 // Limit the width of DAG chains. This is important in general to prevent
139 // DAG-based analysis from blowing up. For example, alias analysis and
140 // load clustering may not complete in reasonable time. It is difficult to
141 // recognize and avoid this situation within each individual analysis, and
142 // future analyses are likely to have the same behavior. Limiting DAG width is
143 // the safe approach and will be especially important with global DAGs.
144 //
145 // MaxParallelChains default is arbitrarily high to avoid affecting
146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147 // sequence over this should have been converted to llvm.memcpy by the
148 // frontend. It is easy to induce this behavior with .ll code such as:
149 // %buffer = alloca [4096 x i8]
150 // %data = load [4096 x i8]* %argPtr
151 // store [4096 x i8] %data, [4096 x i8]* %buffer
152 static const unsigned MaxParallelChains = 64;
153 
154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155                                       const SDValue *Parts, unsigned NumParts,
156                                       MVT PartVT, EVT ValueVT, const Value *V,
157                                       Optional<CallingConv::ID> CC);
158 
159 /// getCopyFromParts - Create a value that contains the specified legal parts
160 /// combined into the value they represent.  If the parts combine to a type
161 /// larger than ValueVT then AssertOp can be used to specify whether the extra
162 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
163 /// (ISD::AssertSext).
164 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
165                                 const SDValue *Parts, unsigned NumParts,
166                                 MVT PartVT, EVT ValueVT, const Value *V,
167                                 Optional<CallingConv::ID> CC = None,
168                                 Optional<ISD::NodeType> AssertOp = None) {
169   // Let the target assemble the parts if it wants to
170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
171   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
172                                                    PartVT, ValueVT, CC))
173     return Val;
174 
175   if (ValueVT.isVector())
176     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
177                                   CC);
178 
179   assert(NumParts > 0 && "No parts to assemble!");
180   SDValue Val = Parts[0];
181 
182   if (NumParts > 1) {
183     // Assemble the value from multiple parts.
184     if (ValueVT.isInteger()) {
185       unsigned PartBits = PartVT.getSizeInBits();
186       unsigned ValueBits = ValueVT.getSizeInBits();
187 
188       // Assemble the power of 2 part.
189       unsigned RoundParts =
190           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
191       unsigned RoundBits = PartBits * RoundParts;
192       EVT RoundVT = RoundBits == ValueBits ?
193         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
194       SDValue Lo, Hi;
195 
196       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
197 
198       if (RoundParts > 2) {
199         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
200                               PartVT, HalfVT, V);
201         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
202                               RoundParts / 2, PartVT, HalfVT, V);
203       } else {
204         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
205         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
206       }
207 
208       if (DAG.getDataLayout().isBigEndian())
209         std::swap(Lo, Hi);
210 
211       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
212 
213       if (RoundParts < NumParts) {
214         // Assemble the trailing non-power-of-2 part.
215         unsigned OddParts = NumParts - RoundParts;
216         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
217         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
218                               OddVT, V, CC);
219 
220         // Combine the round and odd parts.
221         Lo = Val;
222         if (DAG.getDataLayout().isBigEndian())
223           std::swap(Lo, Hi);
224         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
225         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
226         Hi =
227             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
228                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
229                                         TLI.getPointerTy(DAG.getDataLayout())));
230         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
231         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
232       }
233     } else if (PartVT.isFloatingPoint()) {
234       // FP split into multiple FP parts (for ppcf128)
235       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
236              "Unexpected split");
237       SDValue Lo, Hi;
238       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
239       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
240       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
241         std::swap(Lo, Hi);
242       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
243     } else {
244       // FP split into integer parts (soft fp)
245       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
246              !PartVT.isVector() && "Unexpected split");
247       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
248       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
249     }
250   }
251 
252   // There is now one part, held in Val.  Correct it to match ValueVT.
253   // PartEVT is the type of the register class that holds the value.
254   // ValueVT is the type of the inline asm operation.
255   EVT PartEVT = Val.getValueType();
256 
257   if (PartEVT == ValueVT)
258     return Val;
259 
260   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
261       ValueVT.bitsLT(PartEVT)) {
262     // For an FP value in an integer part, we need to truncate to the right
263     // width first.
264     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
265     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
266   }
267 
268   // Handle types that have the same size.
269   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
270     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
271 
272   // Handle types with different sizes.
273   if (PartEVT.isInteger() && ValueVT.isInteger()) {
274     if (ValueVT.bitsLT(PartEVT)) {
275       // For a truncate, see if we have any information to
276       // indicate whether the truncated bits will always be
277       // zero or sign-extension.
278       if (AssertOp.hasValue())
279         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
280                           DAG.getValueType(ValueVT));
281       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
282     }
283     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
284   }
285 
286   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
287     // FP_ROUND's are always exact here.
288     if (ValueVT.bitsLT(Val.getValueType()))
289       return DAG.getNode(
290           ISD::FP_ROUND, DL, ValueVT, Val,
291           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
292 
293     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
294   }
295 
296   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
297   // then truncating.
298   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
299       ValueVT.bitsLT(PartEVT)) {
300     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
301     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
302   }
303 
304   report_fatal_error("Unknown mismatch in getCopyFromParts!");
305 }
306 
307 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
308                                               const Twine &ErrMsg) {
309   const Instruction *I = dyn_cast_or_null<Instruction>(V);
310   if (!V)
311     return Ctx.emitError(ErrMsg);
312 
313   const char *AsmError = ", possible invalid constraint for vector type";
314   if (const CallInst *CI = dyn_cast<CallInst>(I))
315     if (CI->isInlineAsm())
316       return Ctx.emitError(I, ErrMsg + AsmError);
317 
318   return Ctx.emitError(I, ErrMsg);
319 }
320 
321 /// getCopyFromPartsVector - Create a value that contains the specified legal
322 /// parts combined into the value they represent.  If the parts combine to a
323 /// type larger than ValueVT then AssertOp can be used to specify whether the
324 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
325 /// ValueVT (ISD::AssertSext).
326 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
327                                       const SDValue *Parts, unsigned NumParts,
328                                       MVT PartVT, EVT ValueVT, const Value *V,
329                                       Optional<CallingConv::ID> CallConv) {
330   assert(ValueVT.isVector() && "Not a vector value");
331   assert(NumParts > 0 && "No parts to assemble!");
332   const bool IsABIRegCopy = CallConv.hasValue();
333 
334   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
335   SDValue Val = Parts[0];
336 
337   // Handle a multi-element vector.
338   if (NumParts > 1) {
339     EVT IntermediateVT;
340     MVT RegisterVT;
341     unsigned NumIntermediates;
342     unsigned NumRegs;
343 
344     if (IsABIRegCopy) {
345       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
346           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
347           NumIntermediates, RegisterVT);
348     } else {
349       NumRegs =
350           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
351                                      NumIntermediates, RegisterVT);
352     }
353 
354     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
355     NumParts = NumRegs; // Silence a compiler warning.
356     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
357     assert(RegisterVT.getSizeInBits() ==
358            Parts[0].getSimpleValueType().getSizeInBits() &&
359            "Part type sizes don't match!");
360 
361     // Assemble the parts into intermediate operands.
362     SmallVector<SDValue, 8> Ops(NumIntermediates);
363     if (NumIntermediates == NumParts) {
364       // If the register was not expanded, truncate or copy the value,
365       // as appropriate.
366       for (unsigned i = 0; i != NumParts; ++i)
367         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
368                                   PartVT, IntermediateVT, V, CallConv);
369     } else if (NumParts > 0) {
370       // If the intermediate type was expanded, build the intermediate
371       // operands from the parts.
372       assert(NumParts % NumIntermediates == 0 &&
373              "Must expand into a divisible number of parts!");
374       unsigned Factor = NumParts / NumIntermediates;
375       for (unsigned i = 0; i != NumIntermediates; ++i)
376         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
377                                   PartVT, IntermediateVT, V, CallConv);
378     }
379 
380     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
381     // intermediate operands.
382     EVT BuiltVectorTy =
383         IntermediateVT.isVector()
384             ? EVT::getVectorVT(
385                   *DAG.getContext(), IntermediateVT.getScalarType(),
386                   IntermediateVT.getVectorElementCount() * NumParts)
387             : EVT::getVectorVT(*DAG.getContext(),
388                                IntermediateVT.getScalarType(),
389                                NumIntermediates);
390     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
391                                                 : ISD::BUILD_VECTOR,
392                       DL, BuiltVectorTy, Ops);
393   }
394 
395   // There is now one part, held in Val.  Correct it to match ValueVT.
396   EVT PartEVT = Val.getValueType();
397 
398   if (PartEVT == ValueVT)
399     return Val;
400 
401   if (PartEVT.isVector()) {
402     // If the element type of the source/dest vectors are the same, but the
403     // parts vector has more elements than the value vector, then we have a
404     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
405     // elements we want.
406     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
407       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
408               ValueVT.getVectorElementCount().getKnownMinValue()) &&
409              (PartEVT.getVectorElementCount().isScalable() ==
410               ValueVT.getVectorElementCount().isScalable()) &&
411              "Cannot narrow, it would be a lossy transformation");
412       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
413                          DAG.getVectorIdxConstant(0, DL));
414     }
415 
416     // Vector/Vector bitcast.
417     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
418       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 
420     assert(PartEVT.getVectorElementCount() == ValueVT.getVectorElementCount() &&
421       "Cannot handle this kind of promotion");
422     // Promoted vector extract
423     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
424 
425   }
426 
427   // Trivial bitcast if the types are the same size and the destination
428   // vector type is legal.
429   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
430       TLI.isTypeLegal(ValueVT))
431     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
432 
433   if (ValueVT.getVectorNumElements() != 1) {
434      // Certain ABIs require that vectors are passed as integers. For vectors
435      // are the same size, this is an obvious bitcast.
436      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
437        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438      } else if (ValueVT.bitsLT(PartEVT)) {
439        // Bitcast Val back the original type and extract the corresponding
440        // vector we want.
441        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
442        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
443                                            ValueVT.getVectorElementType(), Elts);
444        Val = DAG.getBitcast(WiderVecType, Val);
445        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
446                           DAG.getVectorIdxConstant(0, DL));
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,
614                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
615   if (!PartVT.isFixedLengthVector())
616     return SDValue();
617 
618   EVT ValueVT = Val.getValueType();
619   unsigned PartNumElts = PartVT.getVectorNumElements();
620   unsigned ValueNumElts = ValueVT.getVectorNumElements();
621   if (PartNumElts > ValueNumElts &&
622       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
623     EVT ElementVT = PartVT.getVectorElementType();
624     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
625     // undef elements.
626     SmallVector<SDValue, 16> Ops;
627     DAG.ExtractVectorElements(Val, Ops);
628     SDValue EltUndef = DAG.getUNDEF(ElementVT);
629     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
630       Ops.push_back(EltUndef);
631 
632     // FIXME: Use CONCAT for 2x -> 4x.
633     return DAG.getBuildVector(PartVT, DL, Ops);
634   }
635 
636   return SDValue();
637 }
638 
639 /// getCopyToPartsVector - Create a series of nodes that contain the specified
640 /// value split into legal parts.
641 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
642                                  SDValue Val, SDValue *Parts, unsigned NumParts,
643                                  MVT PartVT, const Value *V,
644                                  Optional<CallingConv::ID> CallConv) {
645   EVT ValueVT = Val.getValueType();
646   assert(ValueVT.isVector() && "Not a vector");
647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
648   const bool IsABIRegCopy = CallConv.hasValue();
649 
650   if (NumParts == 1) {
651     EVT PartEVT = PartVT;
652     if (PartEVT == ValueVT) {
653       // Nothing to do.
654     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
655       // Bitconvert vector->vector case.
656       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
657     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
658       Val = Widened;
659     } else if (PartVT.isVector() &&
660                PartEVT.getVectorElementType().bitsGE(
661                    ValueVT.getVectorElementType()) &&
662                PartEVT.getVectorElementCount() ==
663                    ValueVT.getVectorElementCount()) {
664 
665       // Promoted vector extract
666       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
667     } else {
668       if (ValueVT.getVectorElementCount().isScalar()) {
669         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
670                           DAG.getVectorIdxConstant(0, DL));
671       } else {
672         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
673         assert(PartVT.getFixedSizeInBits() > ValueSize &&
674                "lossy conversion of vector to scalar type");
675         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
676         Val = DAG.getBitcast(IntermediateType, Val);
677         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
678       }
679     }
680 
681     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
682     Parts[0] = Val;
683     return;
684   }
685 
686   // Handle a multi-element vector.
687   EVT IntermediateVT;
688   MVT RegisterVT;
689   unsigned NumIntermediates;
690   unsigned NumRegs;
691   if (IsABIRegCopy) {
692     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
693         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
694         NumIntermediates, RegisterVT);
695   } else {
696     NumRegs =
697         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
698                                    NumIntermediates, RegisterVT);
699   }
700 
701   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
702   NumParts = NumRegs; // Silence a compiler warning.
703   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
704 
705   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
706          "Mixing scalable and fixed vectors when copying in parts");
707 
708   Optional<ElementCount> DestEltCnt;
709 
710   if (IntermediateVT.isVector())
711     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
712   else
713     DestEltCnt = ElementCount::getFixed(NumIntermediates);
714 
715   EVT BuiltVectorTy = EVT::getVectorVT(
716       *DAG.getContext(), IntermediateVT.getScalarType(), DestEltCnt.getValue());
717   if (ValueVT != BuiltVectorTy) {
718     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
719       Val = Widened;
720 
721     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
722   }
723 
724   // Split the vector into intermediate operands.
725   SmallVector<SDValue, 8> Ops(NumIntermediates);
726   for (unsigned i = 0; i != NumIntermediates; ++i) {
727     if (IntermediateVT.isVector()) {
728       // This does something sensible for scalable vectors - see the
729       // definition of EXTRACT_SUBVECTOR for further details.
730       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
731       Ops[i] =
732           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
733                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
734     } else {
735       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
736                            DAG.getVectorIdxConstant(i, DL));
737     }
738   }
739 
740   // Split the intermediate operands into legal parts.
741   if (NumParts == NumIntermediates) {
742     // If the register was not expanded, promote or copy the value,
743     // as appropriate.
744     for (unsigned i = 0; i != NumParts; ++i)
745       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
746   } else if (NumParts > 0) {
747     // If the intermediate type was expanded, split each the value into
748     // legal parts.
749     assert(NumIntermediates != 0 && "division by zero");
750     assert(NumParts % NumIntermediates == 0 &&
751            "Must expand into a divisible number of parts!");
752     unsigned Factor = NumParts / NumIntermediates;
753     for (unsigned i = 0; i != NumIntermediates; ++i)
754       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
755                      CallConv);
756   }
757 }
758 
759 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
760                            EVT valuevt, Optional<CallingConv::ID> CC)
761     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
762       RegCount(1, regs.size()), CallConv(CC) {}
763 
764 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
765                            const DataLayout &DL, unsigned Reg, Type *Ty,
766                            Optional<CallingConv::ID> CC) {
767   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
768 
769   CallConv = CC;
770 
771   for (EVT ValueVT : ValueVTs) {
772     unsigned NumRegs =
773         isABIMangled()
774             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
775             : TLI.getNumRegisters(Context, ValueVT);
776     MVT RegisterVT =
777         isABIMangled()
778             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
779             : TLI.getRegisterType(Context, ValueVT);
780     for (unsigned i = 0; i != NumRegs; ++i)
781       Regs.push_back(Reg + i);
782     RegVTs.push_back(RegisterVT);
783     RegCount.push_back(NumRegs);
784     Reg += NumRegs;
785   }
786 }
787 
788 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
789                                       FunctionLoweringInfo &FuncInfo,
790                                       const SDLoc &dl, SDValue &Chain,
791                                       SDValue *Flag, const Value *V) const {
792   // A Value with type {} or [0 x %t] needs no registers.
793   if (ValueVTs.empty())
794     return SDValue();
795 
796   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
797 
798   // Assemble the legal parts into the final values.
799   SmallVector<SDValue, 4> Values(ValueVTs.size());
800   SmallVector<SDValue, 8> Parts;
801   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
802     // Copy the legal parts from the registers.
803     EVT ValueVT = ValueVTs[Value];
804     unsigned NumRegs = RegCount[Value];
805     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
806                                           *DAG.getContext(),
807                                           CallConv.getValue(), RegVTs[Value])
808                                     : RegVTs[Value];
809 
810     Parts.resize(NumRegs);
811     for (unsigned i = 0; i != NumRegs; ++i) {
812       SDValue P;
813       if (!Flag) {
814         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
815       } else {
816         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
817         *Flag = P.getValue(2);
818       }
819 
820       Chain = P.getValue(1);
821       Parts[i] = P;
822 
823       // If the source register was virtual and if we know something about it,
824       // add an assert node.
825       if (!Register::isVirtualRegister(Regs[Part + i]) ||
826           !RegisterVT.isInteger())
827         continue;
828 
829       const FunctionLoweringInfo::LiveOutInfo *LOI =
830         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
831       if (!LOI)
832         continue;
833 
834       unsigned RegSize = RegisterVT.getScalarSizeInBits();
835       unsigned NumSignBits = LOI->NumSignBits;
836       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
837 
838       if (NumZeroBits == RegSize) {
839         // The current value is a zero.
840         // Explicitly express that as it would be easier for
841         // optimizations to kick in.
842         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
843         continue;
844       }
845 
846       // FIXME: We capture more information than the dag can represent.  For
847       // now, just use the tightest assertzext/assertsext possible.
848       bool isSExt;
849       EVT FromVT(MVT::Other);
850       if (NumZeroBits) {
851         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
852         isSExt = false;
853       } else if (NumSignBits > 1) {
854         FromVT =
855             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
856         isSExt = true;
857       } else {
858         continue;
859       }
860       // Add an assertion node.
861       assert(FromVT != MVT::Other);
862       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
863                              RegisterVT, P, DAG.getValueType(FromVT));
864     }
865 
866     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
867                                      RegisterVT, ValueVT, V, CallConv);
868     Part += NumRegs;
869     Parts.clear();
870   }
871 
872   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
873 }
874 
875 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
876                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
877                                  const Value *V,
878                                  ISD::NodeType PreferredExtendType) const {
879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
880   ISD::NodeType ExtendKind = PreferredExtendType;
881 
882   // Get the list of the values's legal parts.
883   unsigned NumRegs = Regs.size();
884   SmallVector<SDValue, 8> Parts(NumRegs);
885   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
886     unsigned NumParts = RegCount[Value];
887 
888     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
889                                           *DAG.getContext(),
890                                           CallConv.getValue(), RegVTs[Value])
891                                     : RegVTs[Value];
892 
893     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
894       ExtendKind = ISD::ZERO_EXTEND;
895 
896     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
897                    NumParts, RegisterVT, V, CallConv, ExtendKind);
898     Part += NumParts;
899   }
900 
901   // Copy the parts into the registers.
902   SmallVector<SDValue, 8> Chains(NumRegs);
903   for (unsigned i = 0; i != NumRegs; ++i) {
904     SDValue Part;
905     if (!Flag) {
906       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
907     } else {
908       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
909       *Flag = Part.getValue(1);
910     }
911 
912     Chains[i] = Part.getValue(0);
913   }
914 
915   if (NumRegs == 1 || Flag)
916     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
917     // flagged to it. That is the CopyToReg nodes and the user are considered
918     // a single scheduling unit. If we create a TokenFactor and return it as
919     // chain, then the TokenFactor is both a predecessor (operand) of the
920     // user as well as a successor (the TF operands are flagged to the user).
921     // c1, f1 = CopyToReg
922     // c2, f2 = CopyToReg
923     // c3     = TokenFactor c1, c2
924     // ...
925     //        = op c3, ..., f2
926     Chain = Chains[NumRegs-1];
927   else
928     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
929 }
930 
931 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
932                                         unsigned MatchingIdx, const SDLoc &dl,
933                                         SelectionDAG &DAG,
934                                         std::vector<SDValue> &Ops) const {
935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
936 
937   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
938   if (HasMatching)
939     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
940   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
941     // Put the register class of the virtual registers in the flag word.  That
942     // way, later passes can recompute register class constraints for inline
943     // assembly as well as normal instructions.
944     // Don't do this for tied operands that can use the regclass information
945     // from the def.
946     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
947     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
948     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
949   }
950 
951   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
952   Ops.push_back(Res);
953 
954   if (Code == InlineAsm::Kind_Clobber) {
955     // Clobbers should always have a 1:1 mapping with registers, and may
956     // reference registers that have illegal (e.g. vector) types. Hence, we
957     // shouldn't try to apply any sort of splitting logic to them.
958     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
959            "No 1:1 mapping from clobbers to regs?");
960     Register SP = TLI.getStackPointerRegisterToSaveRestore();
961     (void)SP;
962     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
963       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
964       assert(
965           (Regs[I] != SP ||
966            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
967           "If we clobbered the stack pointer, MFI should know about it.");
968     }
969     return;
970   }
971 
972   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
973     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
974     MVT RegisterVT = RegVTs[Value];
975     for (unsigned i = 0; i != NumRegs; ++i) {
976       assert(Reg < Regs.size() && "Mismatch in # registers expected");
977       unsigned TheReg = Regs[Reg++];
978       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
979     }
980   }
981 }
982 
983 SmallVector<std::pair<unsigned, TypeSize>, 4>
984 RegsForValue::getRegsAndSizes() const {
985   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
986   unsigned I = 0;
987   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
988     unsigned RegCount = std::get<0>(CountAndVT);
989     MVT RegisterVT = std::get<1>(CountAndVT);
990     TypeSize RegisterSize = RegisterVT.getSizeInBits();
991     for (unsigned E = I + RegCount; I != E; ++I)
992       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
993   }
994   return OutVec;
995 }
996 
997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
998                                const TargetLibraryInfo *li) {
999   AA = aa;
1000   GFI = gfi;
1001   LibInfo = li;
1002   DL = &DAG.getDataLayout();
1003   Context = DAG.getContext();
1004   LPadToCallSiteMap.clear();
1005   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1006 }
1007 
1008 void SelectionDAGBuilder::clear() {
1009   NodeMap.clear();
1010   UnusedArgNodeMap.clear();
1011   PendingLoads.clear();
1012   PendingExports.clear();
1013   PendingConstrainedFP.clear();
1014   PendingConstrainedFPStrict.clear();
1015   CurInst = nullptr;
1016   HasTailCall = false;
1017   SDNodeOrder = LowestSDNodeOrder;
1018   StatepointLowering.clear();
1019 }
1020 
1021 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1022   DanglingDebugInfoMap.clear();
1023 }
1024 
1025 // Update DAG root to include dependencies on Pending chains.
1026 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1027   SDValue Root = DAG.getRoot();
1028 
1029   if (Pending.empty())
1030     return Root;
1031 
1032   // Add current root to PendingChains, unless we already indirectly
1033   // depend on it.
1034   if (Root.getOpcode() != ISD::EntryToken) {
1035     unsigned i = 0, e = Pending.size();
1036     for (; i != e; ++i) {
1037       assert(Pending[i].getNode()->getNumOperands() > 1);
1038       if (Pending[i].getNode()->getOperand(0) == Root)
1039         break;  // Don't add the root if we already indirectly depend on it.
1040     }
1041 
1042     if (i == e)
1043       Pending.push_back(Root);
1044   }
1045 
1046   if (Pending.size() == 1)
1047     Root = Pending[0];
1048   else
1049     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1050 
1051   DAG.setRoot(Root);
1052   Pending.clear();
1053   return Root;
1054 }
1055 
1056 SDValue SelectionDAGBuilder::getMemoryRoot() {
1057   return updateRoot(PendingLoads);
1058 }
1059 
1060 SDValue SelectionDAGBuilder::getRoot() {
1061   // Chain up all pending constrained intrinsics together with all
1062   // pending loads, by simply appending them to PendingLoads and
1063   // then calling getMemoryRoot().
1064   PendingLoads.reserve(PendingLoads.size() +
1065                        PendingConstrainedFP.size() +
1066                        PendingConstrainedFPStrict.size());
1067   PendingLoads.append(PendingConstrainedFP.begin(),
1068                       PendingConstrainedFP.end());
1069   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1070                       PendingConstrainedFPStrict.end());
1071   PendingConstrainedFP.clear();
1072   PendingConstrainedFPStrict.clear();
1073   return getMemoryRoot();
1074 }
1075 
1076 SDValue SelectionDAGBuilder::getControlRoot() {
1077   // We need to emit pending fpexcept.strict constrained intrinsics,
1078   // so append them to the PendingExports list.
1079   PendingExports.append(PendingConstrainedFPStrict.begin(),
1080                         PendingConstrainedFPStrict.end());
1081   PendingConstrainedFPStrict.clear();
1082   return updateRoot(PendingExports);
1083 }
1084 
1085 void SelectionDAGBuilder::visit(const Instruction &I) {
1086   // Set up outgoing PHI node register values before emitting the terminator.
1087   if (I.isTerminator()) {
1088     HandlePHINodesInSuccessorBlocks(I.getParent());
1089   }
1090 
1091   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1092   if (!isa<DbgInfoIntrinsic>(I))
1093     ++SDNodeOrder;
1094 
1095   CurInst = &I;
1096 
1097   visit(I.getOpcode(), I);
1098 
1099   if (!I.isTerminator() && !HasTailCall &&
1100       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1101     CopyToExportRegsIfNeeded(&I);
1102 
1103   CurInst = nullptr;
1104 }
1105 
1106 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1107   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1108 }
1109 
1110 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1111   // Note: this doesn't use InstVisitor, because it has to work with
1112   // ConstantExpr's in addition to instructions.
1113   switch (Opcode) {
1114   default: llvm_unreachable("Unknown instruction type encountered!");
1115     // Build the switch statement using the Instruction.def file.
1116 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1117     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1118 #include "llvm/IR/Instruction.def"
1119   }
1120 }
1121 
1122 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1123                                                 const DIExpression *Expr) {
1124   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1125     const DbgValueInst *DI = DDI.getDI();
1126     DIVariable *DanglingVariable = DI->getVariable();
1127     DIExpression *DanglingExpr = DI->getExpression();
1128     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1129       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1130       return true;
1131     }
1132     return false;
1133   };
1134 
1135   for (auto &DDIMI : DanglingDebugInfoMap) {
1136     DanglingDebugInfoVector &DDIV = DDIMI.second;
1137 
1138     // If debug info is to be dropped, run it through final checks to see
1139     // whether it can be salvaged.
1140     for (auto &DDI : DDIV)
1141       if (isMatchingDbgValue(DDI))
1142         salvageUnresolvedDbgValue(DDI);
1143 
1144     erase_if(DDIV, isMatchingDbgValue);
1145   }
1146 }
1147 
1148 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1149 // generate the debug data structures now that we've seen its definition.
1150 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1151                                                    SDValue Val) {
1152   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1153   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1154     return;
1155 
1156   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1157   for (auto &DDI : DDIV) {
1158     const DbgValueInst *DI = DDI.getDI();
1159     assert(DI && "Ill-formed DanglingDebugInfo");
1160     DebugLoc dl = DDI.getdl();
1161     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1162     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1163     DILocalVariable *Variable = DI->getVariable();
1164     DIExpression *Expr = DI->getExpression();
1165     assert(Variable->isValidLocationForIntrinsic(dl) &&
1166            "Expected inlined-at fields to agree");
1167     SDDbgValue *SDV;
1168     if (Val.getNode()) {
1169       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1170       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1171       // we couldn't resolve it directly when examining the DbgValue intrinsic
1172       // in the first place we should not be more successful here). Unless we
1173       // have some test case that prove this to be correct we should avoid
1174       // calling EmitFuncArgumentDbgValue here.
1175       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1176         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1177                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1178         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1179         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1180         // inserted after the definition of Val when emitting the instructions
1181         // after ISel. An alternative could be to teach
1182         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1183         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1184                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1185                    << ValSDNodeOrder << "\n");
1186         SDV = getDbgValue(Val, Variable, Expr, dl,
1187                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1188         DAG.AddDbgValue(SDV, Val.getNode(), false);
1189       } else
1190         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1191                           << "in EmitFuncArgumentDbgValue\n");
1192     } else {
1193       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1194       auto Undef =
1195           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1196       auto SDV =
1197           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1198       DAG.AddDbgValue(SDV, nullptr, false);
1199     }
1200   }
1201   DDIV.clear();
1202 }
1203 
1204 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1205   Value *V = DDI.getDI()->getValue();
1206   DILocalVariable *Var = DDI.getDI()->getVariable();
1207   DIExpression *Expr = DDI.getDI()->getExpression();
1208   DebugLoc DL = DDI.getdl();
1209   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1210   unsigned SDOrder = DDI.getSDNodeOrder();
1211 
1212   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1213   // that DW_OP_stack_value is desired.
1214   assert(isa<DbgValueInst>(DDI.getDI()));
1215   bool StackValue = true;
1216 
1217   // Can this Value can be encoded without any further work?
1218   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1219     return;
1220 
1221   // Attempt to salvage back through as many instructions as possible. Bail if
1222   // a non-instruction is seen, such as a constant expression or global
1223   // variable. FIXME: Further work could recover those too.
1224   while (isa<Instruction>(V)) {
1225     Instruction &VAsInst = *cast<Instruction>(V);
1226     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1227 
1228     // If we cannot salvage any further, and haven't yet found a suitable debug
1229     // expression, bail out.
1230     if (!NewExpr)
1231       break;
1232 
1233     // New value and expr now represent this debuginfo.
1234     V = VAsInst.getOperand(0);
1235     Expr = NewExpr;
1236 
1237     // Some kind of simplification occurred: check whether the operand of the
1238     // salvaged debug expression can be encoded in this DAG.
1239     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1240       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1241                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1242       return;
1243     }
1244   }
1245 
1246   // This was the final opportunity to salvage this debug information, and it
1247   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1248   // any earlier variable location.
1249   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1250   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1251   DAG.AddDbgValue(SDV, nullptr, false);
1252 
1253   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1254                     << "\n");
1255   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1256                     << "\n");
1257 }
1258 
1259 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1260                                            DIExpression *Expr, DebugLoc dl,
1261                                            DebugLoc InstDL, unsigned Order) {
1262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1263   SDDbgValue *SDV;
1264   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1265       isa<ConstantPointerNull>(V)) {
1266     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1267     DAG.AddDbgValue(SDV, nullptr, false);
1268     return true;
1269   }
1270 
1271   // If the Value is a frame index, we can create a FrameIndex debug value
1272   // without relying on the DAG at all.
1273   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1274     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1275     if (SI != FuncInfo.StaticAllocaMap.end()) {
1276       auto SDV =
1277           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1278                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1279       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1280       // is still available even if the SDNode gets optimized out.
1281       DAG.AddDbgValue(SDV, nullptr, false);
1282       return true;
1283     }
1284   }
1285 
1286   // Do not use getValue() in here; we don't want to generate code at
1287   // this point if it hasn't been done yet.
1288   SDValue N = NodeMap[V];
1289   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1290     N = UnusedArgNodeMap[V];
1291   if (N.getNode()) {
1292     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1293       return true;
1294     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1295     DAG.AddDbgValue(SDV, N.getNode(), false);
1296     return true;
1297   }
1298 
1299   // Special rules apply for the first dbg.values of parameter variables in a
1300   // function. Identify them by the fact they reference Argument Values, that
1301   // they're parameters, and they are parameters of the current function. We
1302   // need to let them dangle until they get an SDNode.
1303   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1304                        !InstDL.getInlinedAt();
1305   if (!IsParamOfFunc) {
1306     // The value is not used in this block yet (or it would have an SDNode).
1307     // We still want the value to appear for the user if possible -- if it has
1308     // an associated VReg, we can refer to that instead.
1309     auto VMI = FuncInfo.ValueMap.find(V);
1310     if (VMI != FuncInfo.ValueMap.end()) {
1311       unsigned Reg = VMI->second;
1312       // If this is a PHI node, it may be split up into several MI PHI nodes
1313       // (in FunctionLoweringInfo::set).
1314       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1315                        V->getType(), None);
1316       if (RFV.occupiesMultipleRegs()) {
1317         unsigned Offset = 0;
1318         unsigned BitsToDescribe = 0;
1319         if (auto VarSize = Var->getSizeInBits())
1320           BitsToDescribe = *VarSize;
1321         if (auto Fragment = Expr->getFragmentInfo())
1322           BitsToDescribe = Fragment->SizeInBits;
1323         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1324           // Bail out if all bits are described already.
1325           if (Offset >= BitsToDescribe)
1326             break;
1327           // TODO: handle scalable vectors.
1328           unsigned RegisterSize = RegAndSize.second;
1329           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1330               ? BitsToDescribe - Offset
1331               : RegisterSize;
1332           auto FragmentExpr = DIExpression::createFragmentExpression(
1333               Expr, Offset, FragmentSize);
1334           if (!FragmentExpr)
1335               continue;
1336           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1337                                     false, dl, SDNodeOrder);
1338           DAG.AddDbgValue(SDV, nullptr, false);
1339           Offset += RegisterSize;
1340         }
1341       } else {
1342         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1343         DAG.AddDbgValue(SDV, nullptr, false);
1344       }
1345       return true;
1346     }
1347   }
1348 
1349   return false;
1350 }
1351 
1352 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1353   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1354   for (auto &Pair : DanglingDebugInfoMap)
1355     for (auto &DDI : Pair.second)
1356       salvageUnresolvedDbgValue(DDI);
1357   clearDanglingDebugInfo();
1358 }
1359 
1360 /// getCopyFromRegs - If there was virtual register allocated for the value V
1361 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1362 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1363   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1364   SDValue Result;
1365 
1366   if (It != FuncInfo.ValueMap.end()) {
1367     Register InReg = It->second;
1368 
1369     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1370                      DAG.getDataLayout(), InReg, Ty,
1371                      None); // This is not an ABI copy.
1372     SDValue Chain = DAG.getEntryNode();
1373     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1374                                  V);
1375     resolveDanglingDebugInfo(V, Result);
1376   }
1377 
1378   return Result;
1379 }
1380 
1381 /// getValue - Return an SDValue for the given Value.
1382 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1383   // If we already have an SDValue for this value, use it. It's important
1384   // to do this first, so that we don't create a CopyFromReg if we already
1385   // have a regular SDValue.
1386   SDValue &N = NodeMap[V];
1387   if (N.getNode()) return N;
1388 
1389   // If there's a virtual register allocated and initialized for this
1390   // value, use it.
1391   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1392     return copyFromReg;
1393 
1394   // Otherwise create a new SDValue and remember it.
1395   SDValue Val = getValueImpl(V);
1396   NodeMap[V] = Val;
1397   resolveDanglingDebugInfo(V, Val);
1398   return Val;
1399 }
1400 
1401 /// getNonRegisterValue - Return an SDValue for the given Value, but
1402 /// don't look in FuncInfo.ValueMap for a virtual register.
1403 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1404   // If we already have an SDValue for this value, use it.
1405   SDValue &N = NodeMap[V];
1406   if (N.getNode()) {
1407     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1408       // Remove the debug location from the node as the node is about to be used
1409       // in a location which may differ from the original debug location.  This
1410       // is relevant to Constant and ConstantFP nodes because they can appear
1411       // as constant expressions inside PHI nodes.
1412       N->setDebugLoc(DebugLoc());
1413     }
1414     return N;
1415   }
1416 
1417   // Otherwise create a new SDValue and remember it.
1418   SDValue Val = getValueImpl(V);
1419   NodeMap[V] = Val;
1420   resolveDanglingDebugInfo(V, Val);
1421   return Val;
1422 }
1423 
1424 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1425 /// Create an SDValue for the given value.
1426 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1427   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1428 
1429   if (const Constant *C = dyn_cast<Constant>(V)) {
1430     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1431 
1432     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1433       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1434 
1435     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1436       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1437 
1438     if (isa<ConstantPointerNull>(C)) {
1439       unsigned AS = V->getType()->getPointerAddressSpace();
1440       return DAG.getConstant(0, getCurSDLoc(),
1441                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1442     }
1443 
1444     if (match(C, m_VScale(DAG.getDataLayout())))
1445       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1446 
1447     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1448       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1449 
1450     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1451       return DAG.getUNDEF(VT);
1452 
1453     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1454       visit(CE->getOpcode(), *CE);
1455       SDValue N1 = NodeMap[V];
1456       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1457       return N1;
1458     }
1459 
1460     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1461       SmallVector<SDValue, 4> Constants;
1462       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1463            OI != OE; ++OI) {
1464         SDNode *Val = getValue(*OI).getNode();
1465         // If the operand is an empty aggregate, there are no values.
1466         if (!Val) continue;
1467         // Add each leaf value from the operand to the Constants list
1468         // to form a flattened list of all the values.
1469         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1470           Constants.push_back(SDValue(Val, i));
1471       }
1472 
1473       return DAG.getMergeValues(Constants, getCurSDLoc());
1474     }
1475 
1476     if (const ConstantDataSequential *CDS =
1477           dyn_cast<ConstantDataSequential>(C)) {
1478       SmallVector<SDValue, 4> Ops;
1479       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1480         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1481         // Add each leaf value from the operand to the Constants list
1482         // to form a flattened list of all the values.
1483         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1484           Ops.push_back(SDValue(Val, i));
1485       }
1486 
1487       if (isa<ArrayType>(CDS->getType()))
1488         return DAG.getMergeValues(Ops, getCurSDLoc());
1489       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1490     }
1491 
1492     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1493       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1494              "Unknown struct or array constant!");
1495 
1496       SmallVector<EVT, 4> ValueVTs;
1497       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1498       unsigned NumElts = ValueVTs.size();
1499       if (NumElts == 0)
1500         return SDValue(); // empty struct
1501       SmallVector<SDValue, 4> Constants(NumElts);
1502       for (unsigned i = 0; i != NumElts; ++i) {
1503         EVT EltVT = ValueVTs[i];
1504         if (isa<UndefValue>(C))
1505           Constants[i] = DAG.getUNDEF(EltVT);
1506         else if (EltVT.isFloatingPoint())
1507           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1508         else
1509           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1510       }
1511 
1512       return DAG.getMergeValues(Constants, getCurSDLoc());
1513     }
1514 
1515     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1516       return DAG.getBlockAddress(BA, VT);
1517 
1518     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1519       return getValue(Equiv->getGlobalValue());
1520 
1521     VectorType *VecTy = cast<VectorType>(V->getType());
1522 
1523     // Now that we know the number and type of the elements, get that number of
1524     // elements into the Ops array based on what kind of constant it is.
1525     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1526       SmallVector<SDValue, 16> Ops;
1527       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1528       for (unsigned i = 0; i != NumElements; ++i)
1529         Ops.push_back(getValue(CV->getOperand(i)));
1530 
1531       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1532     } else if (isa<ConstantAggregateZero>(C)) {
1533       EVT EltVT =
1534           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1535 
1536       SDValue Op;
1537       if (EltVT.isFloatingPoint())
1538         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1539       else
1540         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1541 
1542       if (isa<ScalableVectorType>(VecTy))
1543         return NodeMap[V] = DAG.getSplatVector(VT, getCurSDLoc(), Op);
1544       else {
1545         SmallVector<SDValue, 16> Ops;
1546         Ops.assign(cast<FixedVectorType>(VecTy)->getNumElements(), Op);
1547         return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1548       }
1549     }
1550     llvm_unreachable("Unknown vector constant");
1551   }
1552 
1553   // If this is a static alloca, generate it as the frameindex instead of
1554   // computation.
1555   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1556     DenseMap<const AllocaInst*, int>::iterator SI =
1557       FuncInfo.StaticAllocaMap.find(AI);
1558     if (SI != FuncInfo.StaticAllocaMap.end())
1559       return DAG.getFrameIndex(SI->second,
1560                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1561   }
1562 
1563   // If this is an instruction which fast-isel has deferred, select it now.
1564   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1565     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1566 
1567     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1568                      Inst->getType(), None);
1569     SDValue Chain = DAG.getEntryNode();
1570     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1571   }
1572 
1573   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V)) {
1574     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1575   }
1576   llvm_unreachable("Can't get register for value!");
1577 }
1578 
1579 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1580   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1581   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1582   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1583   bool IsSEH = isAsynchronousEHPersonality(Pers);
1584   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1585   if (!IsSEH)
1586     CatchPadMBB->setIsEHScopeEntry();
1587   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1588   if (IsMSVCCXX || IsCoreCLR)
1589     CatchPadMBB->setIsEHFuncletEntry();
1590 }
1591 
1592 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1593   // Update machine-CFG edge.
1594   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1595   FuncInfo.MBB->addSuccessor(TargetMBB);
1596   TargetMBB->setIsEHCatchretTarget(true);
1597   DAG.getMachineFunction().setHasEHCatchret(true);
1598 
1599   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1600   bool IsSEH = isAsynchronousEHPersonality(Pers);
1601   if (IsSEH) {
1602     // If this is not a fall-through branch or optimizations are switched off,
1603     // emit the branch.
1604     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1605         TM.getOptLevel() == CodeGenOpt::None)
1606       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1607                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1608     return;
1609   }
1610 
1611   // Figure out the funclet membership for the catchret's successor.
1612   // This will be used by the FuncletLayout pass to determine how to order the
1613   // BB's.
1614   // A 'catchret' returns to the outer scope's color.
1615   Value *ParentPad = I.getCatchSwitchParentPad();
1616   const BasicBlock *SuccessorColor;
1617   if (isa<ConstantTokenNone>(ParentPad))
1618     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1619   else
1620     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1621   assert(SuccessorColor && "No parent funclet for catchret!");
1622   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1623   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1624 
1625   // Create the terminator node.
1626   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1627                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1628                             DAG.getBasicBlock(SuccessorColorMBB));
1629   DAG.setRoot(Ret);
1630 }
1631 
1632 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1633   // Don't emit any special code for the cleanuppad instruction. It just marks
1634   // the start of an EH scope/funclet.
1635   FuncInfo.MBB->setIsEHScopeEntry();
1636   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1637   if (Pers != EHPersonality::Wasm_CXX) {
1638     FuncInfo.MBB->setIsEHFuncletEntry();
1639     FuncInfo.MBB->setIsCleanupFuncletEntry();
1640   }
1641 }
1642 
1643 // In wasm EH, even though a catchpad may not catch an exception if a tag does
1644 // not match, it is OK to add only the first unwind destination catchpad to the
1645 // successors, because there will be at least one invoke instruction within the
1646 // catch scope that points to the next unwind destination, if one exists, so
1647 // CFGSort cannot mess up with BB sorting order.
1648 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
1649 // call within them, and catchpads only consisting of 'catch (...)' have a
1650 // '__cxa_end_catch' call within them, both of which generate invokes in case
1651 // the next unwind destination exists, i.e., the next unwind destination is not
1652 // the caller.)
1653 //
1654 // Having at most one EH pad successor is also simpler and helps later
1655 // transformations.
1656 //
1657 // For example,
1658 // current:
1659 //   invoke void @foo to ... unwind label %catch.dispatch
1660 // catch.dispatch:
1661 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
1662 // catch.start:
1663 //   ...
1664 //   ... in this BB or some other child BB dominated by this BB there will be an
1665 //   invoke that points to 'next' BB as an unwind destination
1666 //
1667 // next: ; We don't need to add this to 'current' BB's successor
1668 //   ...
1669 static void findWasmUnwindDestinations(
1670     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1671     BranchProbability Prob,
1672     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1673         &UnwindDests) {
1674   while (EHPadBB) {
1675     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1676     if (isa<CleanupPadInst>(Pad)) {
1677       // Stop on cleanup pads.
1678       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1679       UnwindDests.back().first->setIsEHScopeEntry();
1680       break;
1681     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1682       // Add the catchpad handlers to the possible destinations. We don't
1683       // continue to the unwind destination of the catchswitch for wasm.
1684       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1685         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1686         UnwindDests.back().first->setIsEHScopeEntry();
1687       }
1688       break;
1689     } else {
1690       continue;
1691     }
1692   }
1693 }
1694 
1695 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1696 /// many places it could ultimately go. In the IR, we have a single unwind
1697 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1698 /// This function skips over imaginary basic blocks that hold catchswitch
1699 /// instructions, and finds all the "real" machine
1700 /// basic block destinations. As those destinations may not be successors of
1701 /// EHPadBB, here we also calculate the edge probability to those destinations.
1702 /// The passed-in Prob is the edge probability to EHPadBB.
1703 static void findUnwindDestinations(
1704     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1705     BranchProbability Prob,
1706     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1707         &UnwindDests) {
1708   EHPersonality Personality =
1709     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1710   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1711   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1712   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1713   bool IsSEH = isAsynchronousEHPersonality(Personality);
1714 
1715   if (IsWasmCXX) {
1716     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1717     assert(UnwindDests.size() <= 1 &&
1718            "There should be at most one unwind destination for wasm");
1719     return;
1720   }
1721 
1722   while (EHPadBB) {
1723     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1724     BasicBlock *NewEHPadBB = nullptr;
1725     if (isa<LandingPadInst>(Pad)) {
1726       // Stop on landingpads. They are not funclets.
1727       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1728       break;
1729     } else if (isa<CleanupPadInst>(Pad)) {
1730       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1731       // personalities.
1732       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1733       UnwindDests.back().first->setIsEHScopeEntry();
1734       UnwindDests.back().first->setIsEHFuncletEntry();
1735       break;
1736     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1737       // Add the catchpad handlers to the possible destinations.
1738       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1739         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1740         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1741         if (IsMSVCCXX || IsCoreCLR)
1742           UnwindDests.back().first->setIsEHFuncletEntry();
1743         if (!IsSEH)
1744           UnwindDests.back().first->setIsEHScopeEntry();
1745       }
1746       NewEHPadBB = CatchSwitch->getUnwindDest();
1747     } else {
1748       continue;
1749     }
1750 
1751     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1752     if (BPI && NewEHPadBB)
1753       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1754     EHPadBB = NewEHPadBB;
1755   }
1756 }
1757 
1758 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1759   // Update successor info.
1760   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1761   auto UnwindDest = I.getUnwindDest();
1762   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1763   BranchProbability UnwindDestProb =
1764       (BPI && UnwindDest)
1765           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1766           : BranchProbability::getZero();
1767   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1768   for (auto &UnwindDest : UnwindDests) {
1769     UnwindDest.first->setIsEHPad();
1770     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1771   }
1772   FuncInfo.MBB->normalizeSuccProbs();
1773 
1774   // Create the terminator node.
1775   SDValue Ret =
1776       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1777   DAG.setRoot(Ret);
1778 }
1779 
1780 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1781   report_fatal_error("visitCatchSwitch not yet implemented!");
1782 }
1783 
1784 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1786   auto &DL = DAG.getDataLayout();
1787   SDValue Chain = getControlRoot();
1788   SmallVector<ISD::OutputArg, 8> Outs;
1789   SmallVector<SDValue, 8> OutVals;
1790 
1791   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1792   // lower
1793   //
1794   //   %val = call <ty> @llvm.experimental.deoptimize()
1795   //   ret <ty> %val
1796   //
1797   // differently.
1798   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1799     LowerDeoptimizingReturn();
1800     return;
1801   }
1802 
1803   if (!FuncInfo.CanLowerReturn) {
1804     unsigned DemoteReg = FuncInfo.DemoteRegister;
1805     const Function *F = I.getParent()->getParent();
1806 
1807     // Emit a store of the return value through the virtual register.
1808     // Leave Outs empty so that LowerReturn won't try to load return
1809     // registers the usual way.
1810     SmallVector<EVT, 1> PtrValueVTs;
1811     ComputeValueVTs(TLI, DL,
1812                     F->getReturnType()->getPointerTo(
1813                         DAG.getDataLayout().getAllocaAddrSpace()),
1814                     PtrValueVTs);
1815 
1816     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1817                                         DemoteReg, PtrValueVTs[0]);
1818     SDValue RetOp = getValue(I.getOperand(0));
1819 
1820     SmallVector<EVT, 4> ValueVTs, MemVTs;
1821     SmallVector<uint64_t, 4> Offsets;
1822     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1823                     &Offsets);
1824     unsigned NumValues = ValueVTs.size();
1825 
1826     SmallVector<SDValue, 4> Chains(NumValues);
1827     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
1828     for (unsigned i = 0; i != NumValues; ++i) {
1829       // An aggregate return value cannot wrap around the address space, so
1830       // offsets to its parts don't wrap either.
1831       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
1832                                            TypeSize::Fixed(Offsets[i]));
1833 
1834       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1835       if (MemVTs[i] != ValueVTs[i])
1836         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1837       Chains[i] = DAG.getStore(
1838           Chain, getCurSDLoc(), Val,
1839           // FIXME: better loc info would be nice.
1840           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
1841           commonAlignment(BaseAlign, Offsets[i]));
1842     }
1843 
1844     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1845                         MVT::Other, Chains);
1846   } else if (I.getNumOperands() != 0) {
1847     SmallVector<EVT, 4> ValueVTs;
1848     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1849     unsigned NumValues = ValueVTs.size();
1850     if (NumValues) {
1851       SDValue RetOp = getValue(I.getOperand(0));
1852 
1853       const Function *F = I.getParent()->getParent();
1854 
1855       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1856           I.getOperand(0)->getType(), F->getCallingConv(),
1857           /*IsVarArg*/ false);
1858 
1859       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1860       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1861                                           Attribute::SExt))
1862         ExtendKind = ISD::SIGN_EXTEND;
1863       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1864                                                Attribute::ZExt))
1865         ExtendKind = ISD::ZERO_EXTEND;
1866 
1867       LLVMContext &Context = F->getContext();
1868       bool RetInReg = F->getAttributes().hasAttribute(
1869           AttributeList::ReturnIndex, Attribute::InReg);
1870 
1871       for (unsigned j = 0; j != NumValues; ++j) {
1872         EVT VT = ValueVTs[j];
1873 
1874         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1875           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1876 
1877         CallingConv::ID CC = F->getCallingConv();
1878 
1879         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1880         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1881         SmallVector<SDValue, 4> Parts(NumParts);
1882         getCopyToParts(DAG, getCurSDLoc(),
1883                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1884                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1885 
1886         // 'inreg' on function refers to return value
1887         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1888         if (RetInReg)
1889           Flags.setInReg();
1890 
1891         if (I.getOperand(0)->getType()->isPointerTy()) {
1892           Flags.setPointer();
1893           Flags.setPointerAddrSpace(
1894               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1895         }
1896 
1897         if (NeedsRegBlock) {
1898           Flags.setInConsecutiveRegs();
1899           if (j == NumValues - 1)
1900             Flags.setInConsecutiveRegsLast();
1901         }
1902 
1903         // Propagate extension type if any
1904         if (ExtendKind == ISD::SIGN_EXTEND)
1905           Flags.setSExt();
1906         else if (ExtendKind == ISD::ZERO_EXTEND)
1907           Flags.setZExt();
1908 
1909         for (unsigned i = 0; i < NumParts; ++i) {
1910           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1911                                         VT, /*isfixed=*/true, 0, 0));
1912           OutVals.push_back(Parts[i]);
1913         }
1914       }
1915     }
1916   }
1917 
1918   // Push in swifterror virtual register as the last element of Outs. This makes
1919   // sure swifterror virtual register will be returned in the swifterror
1920   // physical register.
1921   const Function *F = I.getParent()->getParent();
1922   if (TLI.supportSwiftError() &&
1923       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1924     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1925     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1926     Flags.setSwiftError();
1927     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1928                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1929                                   true /*isfixed*/, 1 /*origidx*/,
1930                                   0 /*partOffs*/));
1931     // Create SDNode for the swifterror virtual register.
1932     OutVals.push_back(
1933         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1934                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1935                         EVT(TLI.getPointerTy(DL))));
1936   }
1937 
1938   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1939   CallingConv::ID CallConv =
1940     DAG.getMachineFunction().getFunction().getCallingConv();
1941   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1942       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1943 
1944   // Verify that the target's LowerReturn behaved as expected.
1945   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1946          "LowerReturn didn't return a valid chain!");
1947 
1948   // Update the DAG with the new chain value resulting from return lowering.
1949   DAG.setRoot(Chain);
1950 }
1951 
1952 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1953 /// created for it, emit nodes to copy the value into the virtual
1954 /// registers.
1955 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1956   // Skip empty types
1957   if (V->getType()->isEmptyTy())
1958     return;
1959 
1960   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
1961   if (VMI != FuncInfo.ValueMap.end()) {
1962     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1963     CopyValueToVirtualRegister(V, VMI->second);
1964   }
1965 }
1966 
1967 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1968 /// the current basic block, add it to ValueMap now so that we'll get a
1969 /// CopyTo/FromReg.
1970 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1971   // No need to export constants.
1972   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1973 
1974   // Already exported?
1975   if (FuncInfo.isExportedInst(V)) return;
1976 
1977   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1978   CopyValueToVirtualRegister(V, Reg);
1979 }
1980 
1981 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1982                                                      const BasicBlock *FromBB) {
1983   // The operands of the setcc have to be in this block.  We don't know
1984   // how to export them from some other block.
1985   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1986     // Can export from current BB.
1987     if (VI->getParent() == FromBB)
1988       return true;
1989 
1990     // Is already exported, noop.
1991     return FuncInfo.isExportedInst(V);
1992   }
1993 
1994   // If this is an argument, we can export it if the BB is the entry block or
1995   // if it is already exported.
1996   if (isa<Argument>(V)) {
1997     if (FromBB == &FromBB->getParent()->getEntryBlock())
1998       return true;
1999 
2000     // Otherwise, can only export this if it is already exported.
2001     return FuncInfo.isExportedInst(V);
2002   }
2003 
2004   // Otherwise, constants can always be exported.
2005   return true;
2006 }
2007 
2008 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2009 BranchProbability
2010 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2011                                         const MachineBasicBlock *Dst) const {
2012   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2013   const BasicBlock *SrcBB = Src->getBasicBlock();
2014   const BasicBlock *DstBB = Dst->getBasicBlock();
2015   if (!BPI) {
2016     // If BPI is not available, set the default probability as 1 / N, where N is
2017     // the number of successors.
2018     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2019     return BranchProbability(1, SuccSize);
2020   }
2021   return BPI->getEdgeProbability(SrcBB, DstBB);
2022 }
2023 
2024 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2025                                                MachineBasicBlock *Dst,
2026                                                BranchProbability Prob) {
2027   if (!FuncInfo.BPI)
2028     Src->addSuccessorWithoutProb(Dst);
2029   else {
2030     if (Prob.isUnknown())
2031       Prob = getEdgeProbability(Src, Dst);
2032     Src->addSuccessor(Dst, Prob);
2033   }
2034 }
2035 
2036 static bool InBlock(const Value *V, const BasicBlock *BB) {
2037   if (const Instruction *I = dyn_cast<Instruction>(V))
2038     return I->getParent() == BB;
2039   return true;
2040 }
2041 
2042 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2043 /// This function emits a branch and is used at the leaves of an OR or an
2044 /// AND operator tree.
2045 void
2046 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2047                                                   MachineBasicBlock *TBB,
2048                                                   MachineBasicBlock *FBB,
2049                                                   MachineBasicBlock *CurBB,
2050                                                   MachineBasicBlock *SwitchBB,
2051                                                   BranchProbability TProb,
2052                                                   BranchProbability FProb,
2053                                                   bool InvertCond) {
2054   const BasicBlock *BB = CurBB->getBasicBlock();
2055 
2056   // If the leaf of the tree is a comparison, merge the condition into
2057   // the caseblock.
2058   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2059     // The operands of the cmp have to be in this block.  We don't know
2060     // how to export them from some other block.  If this is the first block
2061     // of the sequence, no exporting is needed.
2062     if (CurBB == SwitchBB ||
2063         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2064          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2065       ISD::CondCode Condition;
2066       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2067         ICmpInst::Predicate Pred =
2068             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2069         Condition = getICmpCondCode(Pred);
2070       } else {
2071         const FCmpInst *FC = cast<FCmpInst>(Cond);
2072         FCmpInst::Predicate Pred =
2073             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2074         Condition = getFCmpCondCode(Pred);
2075         if (TM.Options.NoNaNsFPMath)
2076           Condition = getFCmpCodeWithoutNaN(Condition);
2077       }
2078 
2079       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2080                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2081       SL->SwitchCases.push_back(CB);
2082       return;
2083     }
2084   }
2085 
2086   // Create a CaseBlock record representing this branch.
2087   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2088   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2089                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2090   SL->SwitchCases.push_back(CB);
2091 }
2092 
2093 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2094                                                MachineBasicBlock *TBB,
2095                                                MachineBasicBlock *FBB,
2096                                                MachineBasicBlock *CurBB,
2097                                                MachineBasicBlock *SwitchBB,
2098                                                Instruction::BinaryOps Opc,
2099                                                BranchProbability TProb,
2100                                                BranchProbability FProb,
2101                                                bool InvertCond) {
2102   // Skip over not part of the tree and remember to invert op and operands at
2103   // next level.
2104   Value *NotCond;
2105   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2106       InBlock(NotCond, CurBB->getBasicBlock())) {
2107     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2108                          !InvertCond);
2109     return;
2110   }
2111 
2112   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2113   const Value *BOpOp0, *BOpOp1;
2114   // Compute the effective opcode for Cond, taking into account whether it needs
2115   // to be inverted, e.g.
2116   //   and (not (or A, B)), C
2117   // gets lowered as
2118   //   and (and (not A, not B), C)
2119   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2120   if (BOp) {
2121     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2122                ? Instruction::And
2123                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2124                       ? Instruction::Or
2125                       : (Instruction::BinaryOps)0);
2126     if (InvertCond) {
2127       if (BOpc == Instruction::And)
2128         BOpc = Instruction::Or;
2129       else if (BOpc == Instruction::Or)
2130         BOpc = Instruction::And;
2131     }
2132   }
2133 
2134   // If this node is not part of the or/and tree, emit it as a branch.
2135   // Note that all nodes in the tree should have same opcode.
2136   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2137   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2138       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2139       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2140     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2141                                  TProb, FProb, InvertCond);
2142     return;
2143   }
2144 
2145   //  Create TmpBB after CurBB.
2146   MachineFunction::iterator BBI(CurBB);
2147   MachineFunction &MF = DAG.getMachineFunction();
2148   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2149   CurBB->getParent()->insert(++BBI, TmpBB);
2150 
2151   if (Opc == Instruction::Or) {
2152     // Codegen X | Y as:
2153     // BB1:
2154     //   jmp_if_X TBB
2155     //   jmp TmpBB
2156     // TmpBB:
2157     //   jmp_if_Y TBB
2158     //   jmp FBB
2159     //
2160 
2161     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2162     // The requirement is that
2163     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2164     //     = TrueProb for original BB.
2165     // Assuming the original probabilities are A and B, one choice is to set
2166     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2167     // A/(1+B) and 2B/(1+B). This choice assumes that
2168     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2169     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2170     // TmpBB, but the math is more complicated.
2171 
2172     auto NewTrueProb = TProb / 2;
2173     auto NewFalseProb = TProb / 2 + FProb;
2174     // Emit the LHS condition.
2175     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2176                          NewFalseProb, InvertCond);
2177 
2178     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2179     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2180     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2181     // Emit the RHS condition into TmpBB.
2182     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2183                          Probs[1], InvertCond);
2184   } else {
2185     assert(Opc == Instruction::And && "Unknown merge op!");
2186     // Codegen X & Y as:
2187     // BB1:
2188     //   jmp_if_X TmpBB
2189     //   jmp FBB
2190     // TmpBB:
2191     //   jmp_if_Y TBB
2192     //   jmp FBB
2193     //
2194     //  This requires creation of TmpBB after CurBB.
2195 
2196     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2197     // The requirement is that
2198     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2199     //     = FalseProb for original BB.
2200     // Assuming the original probabilities are A and B, one choice is to set
2201     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2202     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2203     // TrueProb for BB1 * FalseProb for TmpBB.
2204 
2205     auto NewTrueProb = TProb + FProb / 2;
2206     auto NewFalseProb = FProb / 2;
2207     // Emit the LHS condition.
2208     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2209                          NewFalseProb, InvertCond);
2210 
2211     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2212     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2213     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2214     // Emit the RHS condition into TmpBB.
2215     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2216                          Probs[1], InvertCond);
2217   }
2218 }
2219 
2220 /// If the set of cases should be emitted as a series of branches, return true.
2221 /// If we should emit this as a bunch of and/or'd together conditions, return
2222 /// false.
2223 bool
2224 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2225   if (Cases.size() != 2) return true;
2226 
2227   // If this is two comparisons of the same values or'd or and'd together, they
2228   // will get folded into a single comparison, so don't emit two blocks.
2229   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2230        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2231       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2232        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2233     return false;
2234   }
2235 
2236   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2237   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2238   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2239       Cases[0].CC == Cases[1].CC &&
2240       isa<Constant>(Cases[0].CmpRHS) &&
2241       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2242     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2243       return false;
2244     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2245       return false;
2246   }
2247 
2248   return true;
2249 }
2250 
2251 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2252   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2253 
2254   // Update machine-CFG edges.
2255   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2256 
2257   if (I.isUnconditional()) {
2258     // Update machine-CFG edges.
2259     BrMBB->addSuccessor(Succ0MBB);
2260 
2261     // If this is not a fall-through branch or optimizations are switched off,
2262     // emit the branch.
2263     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2264       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2265                               MVT::Other, getControlRoot(),
2266                               DAG.getBasicBlock(Succ0MBB)));
2267 
2268     return;
2269   }
2270 
2271   // If this condition is one of the special cases we handle, do special stuff
2272   // now.
2273   const Value *CondVal = I.getCondition();
2274   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2275 
2276   // If this is a series of conditions that are or'd or and'd together, emit
2277   // this as a sequence of branches instead of setcc's with and/or operations.
2278   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2279   // unpredictable branches, and vector extracts because those jumps are likely
2280   // expensive for any target), this should improve performance.
2281   // For example, instead of something like:
2282   //     cmp A, B
2283   //     C = seteq
2284   //     cmp D, E
2285   //     F = setle
2286   //     or C, F
2287   //     jnz foo
2288   // Emit:
2289   //     cmp A, B
2290   //     je foo
2291   //     cmp D, E
2292   //     jle foo
2293   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2294   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2295       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2296     Value *Vec;
2297     const Value *BOp0, *BOp1;
2298     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2299     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2300       Opcode = Instruction::And;
2301     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2302       Opcode = Instruction::Or;
2303 
2304     if (Opcode && !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2305                     match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) {
2306       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2307                            getEdgeProbability(BrMBB, Succ0MBB),
2308                            getEdgeProbability(BrMBB, Succ1MBB),
2309                            /*InvertCond=*/false);
2310       // If the compares in later blocks need to use values not currently
2311       // exported from this block, export them now.  This block should always
2312       // be the first entry.
2313       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2314 
2315       // Allow some cases to be rejected.
2316       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2317         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2318           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2319           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2320         }
2321 
2322         // Emit the branch for this block.
2323         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2324         SL->SwitchCases.erase(SL->SwitchCases.begin());
2325         return;
2326       }
2327 
2328       // Okay, we decided not to do this, remove any inserted MBB's and clear
2329       // SwitchCases.
2330       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2331         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2332 
2333       SL->SwitchCases.clear();
2334     }
2335   }
2336 
2337   // Create a CaseBlock record representing this branch.
2338   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2339                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2340 
2341   // Use visitSwitchCase to actually insert the fast branch sequence for this
2342   // cond branch.
2343   visitSwitchCase(CB, BrMBB);
2344 }
2345 
2346 /// visitSwitchCase - Emits the necessary code to represent a single node in
2347 /// the binary search tree resulting from lowering a switch instruction.
2348 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2349                                           MachineBasicBlock *SwitchBB) {
2350   SDValue Cond;
2351   SDValue CondLHS = getValue(CB.CmpLHS);
2352   SDLoc dl = CB.DL;
2353 
2354   if (CB.CC == ISD::SETTRUE) {
2355     // Branch or fall through to TrueBB.
2356     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2357     SwitchBB->normalizeSuccProbs();
2358     if (CB.TrueBB != NextBlock(SwitchBB)) {
2359       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2360                               DAG.getBasicBlock(CB.TrueBB)));
2361     }
2362     return;
2363   }
2364 
2365   auto &TLI = DAG.getTargetLoweringInfo();
2366   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2367 
2368   // Build the setcc now.
2369   if (!CB.CmpMHS) {
2370     // Fold "(X == true)" to X and "(X == false)" to !X to
2371     // handle common cases produced by branch lowering.
2372     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2373         CB.CC == ISD::SETEQ)
2374       Cond = CondLHS;
2375     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2376              CB.CC == ISD::SETEQ) {
2377       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2378       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2379     } else {
2380       SDValue CondRHS = getValue(CB.CmpRHS);
2381 
2382       // If a pointer's DAG type is larger than its memory type then the DAG
2383       // values are zero-extended. This breaks signed comparisons so truncate
2384       // back to the underlying type before doing the compare.
2385       if (CondLHS.getValueType() != MemVT) {
2386         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2387         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2388       }
2389       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2390     }
2391   } else {
2392     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2393 
2394     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2395     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2396 
2397     SDValue CmpOp = getValue(CB.CmpMHS);
2398     EVT VT = CmpOp.getValueType();
2399 
2400     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2401       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2402                           ISD::SETLE);
2403     } else {
2404       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2405                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2406       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2407                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2408     }
2409   }
2410 
2411   // Update successor info
2412   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2413   // TrueBB and FalseBB are always different unless the incoming IR is
2414   // degenerate. This only happens when running llc on weird IR.
2415   if (CB.TrueBB != CB.FalseBB)
2416     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2417   SwitchBB->normalizeSuccProbs();
2418 
2419   // If the lhs block is the next block, invert the condition so that we can
2420   // fall through to the lhs instead of the rhs block.
2421   if (CB.TrueBB == NextBlock(SwitchBB)) {
2422     std::swap(CB.TrueBB, CB.FalseBB);
2423     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2424     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2425   }
2426 
2427   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2428                                MVT::Other, getControlRoot(), Cond,
2429                                DAG.getBasicBlock(CB.TrueBB));
2430 
2431   // Insert the false branch. Do this even if it's a fall through branch,
2432   // this makes it easier to do DAG optimizations which require inverting
2433   // the branch condition.
2434   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2435                        DAG.getBasicBlock(CB.FalseBB));
2436 
2437   DAG.setRoot(BrCond);
2438 }
2439 
2440 /// visitJumpTable - Emit JumpTable node in the current MBB
2441 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2442   // Emit the code for the jump table
2443   assert(JT.Reg != -1U && "Should lower JT Header first!");
2444   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2445   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2446                                      JT.Reg, PTy);
2447   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2448   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2449                                     MVT::Other, Index.getValue(1),
2450                                     Table, Index);
2451   DAG.setRoot(BrJumpTable);
2452 }
2453 
2454 /// visitJumpTableHeader - This function emits necessary code to produce index
2455 /// in the JumpTable from switch case.
2456 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2457                                                JumpTableHeader &JTH,
2458                                                MachineBasicBlock *SwitchBB) {
2459   SDLoc dl = getCurSDLoc();
2460 
2461   // Subtract the lowest switch case value from the value being switched on.
2462   SDValue SwitchOp = getValue(JTH.SValue);
2463   EVT VT = SwitchOp.getValueType();
2464   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2465                             DAG.getConstant(JTH.First, dl, VT));
2466 
2467   // The SDNode we just created, which holds the value being switched on minus
2468   // the smallest case value, needs to be copied to a virtual register so it
2469   // can be used as an index into the jump table in a subsequent basic block.
2470   // This value may be smaller or larger than the target's pointer type, and
2471   // therefore require extension or truncating.
2472   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2473   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2474 
2475   unsigned JumpTableReg =
2476       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2477   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2478                                     JumpTableReg, SwitchOp);
2479   JT.Reg = JumpTableReg;
2480 
2481   if (!JTH.OmitRangeCheck) {
2482     // Emit the range check for the jump table, and branch to the default block
2483     // for the switch statement if the value being switched on exceeds the
2484     // largest case in the switch.
2485     SDValue CMP = DAG.getSetCC(
2486         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2487                                    Sub.getValueType()),
2488         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2489 
2490     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2491                                  MVT::Other, CopyTo, CMP,
2492                                  DAG.getBasicBlock(JT.Default));
2493 
2494     // Avoid emitting unnecessary branches to the next block.
2495     if (JT.MBB != NextBlock(SwitchBB))
2496       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2497                            DAG.getBasicBlock(JT.MBB));
2498 
2499     DAG.setRoot(BrCond);
2500   } else {
2501     // Avoid emitting unnecessary branches to the next block.
2502     if (JT.MBB != NextBlock(SwitchBB))
2503       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2504                               DAG.getBasicBlock(JT.MBB)));
2505     else
2506       DAG.setRoot(CopyTo);
2507   }
2508 }
2509 
2510 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2511 /// variable if there exists one.
2512 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2513                                  SDValue &Chain) {
2514   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2515   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2516   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2517   MachineFunction &MF = DAG.getMachineFunction();
2518   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2519   MachineSDNode *Node =
2520       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2521   if (Global) {
2522     MachinePointerInfo MPInfo(Global);
2523     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2524                  MachineMemOperand::MODereferenceable;
2525     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2526         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlign(PtrTy));
2527     DAG.setNodeMemRefs(Node, {MemRef});
2528   }
2529   if (PtrTy != PtrMemTy)
2530     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2531   return SDValue(Node, 0);
2532 }
2533 
2534 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2535 /// tail spliced into a stack protector check success bb.
2536 ///
2537 /// For a high level explanation of how this fits into the stack protector
2538 /// generation see the comment on the declaration of class
2539 /// StackProtectorDescriptor.
2540 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2541                                                   MachineBasicBlock *ParentBB) {
2542 
2543   // First create the loads to the guard/stack slot for the comparison.
2544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2545   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2546   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2547 
2548   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2549   int FI = MFI.getStackProtectorIndex();
2550 
2551   SDValue Guard;
2552   SDLoc dl = getCurSDLoc();
2553   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2554   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2555   Align Align = DL->getPrefTypeAlign(Type::getInt8PtrTy(M.getContext()));
2556 
2557   // Generate code to load the content of the guard slot.
2558   SDValue GuardVal = DAG.getLoad(
2559       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2560       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2561       MachineMemOperand::MOVolatile);
2562 
2563   if (TLI.useStackGuardXorFP())
2564     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2565 
2566   // Retrieve guard check function, nullptr if instrumentation is inlined.
2567   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2568     // The target provides a guard check function to validate the guard value.
2569     // Generate a call to that function with the content of the guard slot as
2570     // argument.
2571     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2572     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2573 
2574     TargetLowering::ArgListTy Args;
2575     TargetLowering::ArgListEntry Entry;
2576     Entry.Node = GuardVal;
2577     Entry.Ty = FnTy->getParamType(0);
2578     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2579       Entry.IsInReg = true;
2580     Args.push_back(Entry);
2581 
2582     TargetLowering::CallLoweringInfo CLI(DAG);
2583     CLI.setDebugLoc(getCurSDLoc())
2584         .setChain(DAG.getEntryNode())
2585         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2586                    getValue(GuardCheckFn), std::move(Args));
2587 
2588     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2589     DAG.setRoot(Result.second);
2590     return;
2591   }
2592 
2593   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2594   // Otherwise, emit a volatile load to retrieve the stack guard value.
2595   SDValue Chain = DAG.getEntryNode();
2596   if (TLI.useLoadStackGuardNode()) {
2597     Guard = getLoadStackGuard(DAG, dl, Chain);
2598   } else {
2599     const Value *IRGuard = TLI.getSDagStackGuard(M);
2600     SDValue GuardPtr = getValue(IRGuard);
2601 
2602     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2603                         MachinePointerInfo(IRGuard, 0), Align,
2604                         MachineMemOperand::MOVolatile);
2605   }
2606 
2607   // Perform the comparison via a getsetcc.
2608   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2609                                                         *DAG.getContext(),
2610                                                         Guard.getValueType()),
2611                              Guard, GuardVal, ISD::SETNE);
2612 
2613   // If the guard/stackslot do not equal, branch to failure MBB.
2614   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2615                                MVT::Other, GuardVal.getOperand(0),
2616                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2617   // Otherwise branch to success MBB.
2618   SDValue Br = DAG.getNode(ISD::BR, dl,
2619                            MVT::Other, BrCond,
2620                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2621 
2622   DAG.setRoot(Br);
2623 }
2624 
2625 /// Codegen the failure basic block for a stack protector check.
2626 ///
2627 /// A failure stack protector machine basic block consists simply of a call to
2628 /// __stack_chk_fail().
2629 ///
2630 /// For a high level explanation of how this fits into the stack protector
2631 /// generation see the comment on the declaration of class
2632 /// StackProtectorDescriptor.
2633 void
2634 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2636   TargetLowering::MakeLibCallOptions CallOptions;
2637   CallOptions.setDiscardResult(true);
2638   SDValue Chain =
2639       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2640                       None, CallOptions, getCurSDLoc()).second;
2641   // On PS4, the "return address" must still be within the calling function,
2642   // even if it's at the very end, so emit an explicit TRAP here.
2643   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2644   if (TM.getTargetTriple().isPS4CPU())
2645     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2646   // WebAssembly needs an unreachable instruction after a non-returning call,
2647   // because the function return type can be different from __stack_chk_fail's
2648   // return type (void).
2649   if (TM.getTargetTriple().isWasm())
2650     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2651 
2652   DAG.setRoot(Chain);
2653 }
2654 
2655 /// visitBitTestHeader - This function emits necessary code to produce value
2656 /// suitable for "bit tests"
2657 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2658                                              MachineBasicBlock *SwitchBB) {
2659   SDLoc dl = getCurSDLoc();
2660 
2661   // Subtract the minimum value.
2662   SDValue SwitchOp = getValue(B.SValue);
2663   EVT VT = SwitchOp.getValueType();
2664   SDValue RangeSub =
2665       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2666 
2667   // Determine the type of the test operands.
2668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2669   bool UsePtrType = false;
2670   if (!TLI.isTypeLegal(VT)) {
2671     UsePtrType = true;
2672   } else {
2673     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2674       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2675         // Switch table case range are encoded into series of masks.
2676         // Just use pointer type, it's guaranteed to fit.
2677         UsePtrType = true;
2678         break;
2679       }
2680   }
2681   SDValue Sub = RangeSub;
2682   if (UsePtrType) {
2683     VT = TLI.getPointerTy(DAG.getDataLayout());
2684     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2685   }
2686 
2687   B.RegVT = VT.getSimpleVT();
2688   B.Reg = FuncInfo.CreateReg(B.RegVT);
2689   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2690 
2691   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2692 
2693   if (!B.OmitRangeCheck)
2694     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2695   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2696   SwitchBB->normalizeSuccProbs();
2697 
2698   SDValue Root = CopyTo;
2699   if (!B.OmitRangeCheck) {
2700     // Conditional branch to the default block.
2701     SDValue RangeCmp = DAG.getSetCC(dl,
2702         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2703                                RangeSub.getValueType()),
2704         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2705         ISD::SETUGT);
2706 
2707     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2708                        DAG.getBasicBlock(B.Default));
2709   }
2710 
2711   // Avoid emitting unnecessary branches to the next block.
2712   if (MBB != NextBlock(SwitchBB))
2713     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2714 
2715   DAG.setRoot(Root);
2716 }
2717 
2718 /// visitBitTestCase - this function produces one "bit test"
2719 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2720                                            MachineBasicBlock* NextMBB,
2721                                            BranchProbability BranchProbToNext,
2722                                            unsigned Reg,
2723                                            BitTestCase &B,
2724                                            MachineBasicBlock *SwitchBB) {
2725   SDLoc dl = getCurSDLoc();
2726   MVT VT = BB.RegVT;
2727   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2728   SDValue Cmp;
2729   unsigned PopCount = countPopulation(B.Mask);
2730   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2731   if (PopCount == 1) {
2732     // Testing for a single bit; just compare the shift count with what it
2733     // would need to be to shift a 1 bit in that position.
2734     Cmp = DAG.getSetCC(
2735         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2736         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2737         ISD::SETEQ);
2738   } else if (PopCount == BB.Range) {
2739     // There is only one zero bit in the range, test for it directly.
2740     Cmp = DAG.getSetCC(
2741         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2742         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2743         ISD::SETNE);
2744   } else {
2745     // Make desired shift
2746     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2747                                     DAG.getConstant(1, dl, VT), ShiftOp);
2748 
2749     // Emit bit tests and jumps
2750     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2751                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2752     Cmp = DAG.getSetCC(
2753         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2754         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2755   }
2756 
2757   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2758   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2759   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2760   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2761   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2762   // one as they are relative probabilities (and thus work more like weights),
2763   // and hence we need to normalize them to let the sum of them become one.
2764   SwitchBB->normalizeSuccProbs();
2765 
2766   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2767                               MVT::Other, getControlRoot(),
2768                               Cmp, DAG.getBasicBlock(B.TargetBB));
2769 
2770   // Avoid emitting unnecessary branches to the next block.
2771   if (NextMBB != NextBlock(SwitchBB))
2772     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2773                         DAG.getBasicBlock(NextMBB));
2774 
2775   DAG.setRoot(BrAnd);
2776 }
2777 
2778 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2779   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2780 
2781   // Retrieve successors. Look through artificial IR level blocks like
2782   // catchswitch for successors.
2783   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2784   const BasicBlock *EHPadBB = I.getSuccessor(1);
2785 
2786   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2787   // have to do anything here to lower funclet bundles.
2788   assert(!I.hasOperandBundlesOtherThan(
2789              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
2790               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
2791               LLVMContext::OB_cfguardtarget,
2792               LLVMContext::OB_clang_arc_attachedcall}) &&
2793          "Cannot lower invokes with arbitrary operand bundles yet!");
2794 
2795   const Value *Callee(I.getCalledOperand());
2796   const Function *Fn = dyn_cast<Function>(Callee);
2797   if (isa<InlineAsm>(Callee))
2798     visitInlineAsm(I);
2799   else if (Fn && Fn->isIntrinsic()) {
2800     switch (Fn->getIntrinsicID()) {
2801     default:
2802       llvm_unreachable("Cannot invoke this intrinsic");
2803     case Intrinsic::donothing:
2804       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2805       break;
2806     case Intrinsic::experimental_patchpoint_void:
2807     case Intrinsic::experimental_patchpoint_i64:
2808       visitPatchpoint(I, EHPadBB);
2809       break;
2810     case Intrinsic::experimental_gc_statepoint:
2811       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
2812       break;
2813     case Intrinsic::wasm_rethrow: {
2814       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2815       // special because it can be invoked, so we manually lower it to a DAG
2816       // node here.
2817       SmallVector<SDValue, 8> Ops;
2818       Ops.push_back(getRoot()); // inchain
2819       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2820       Ops.push_back(
2821           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
2822                                 TLI.getPointerTy(DAG.getDataLayout())));
2823       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2824       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2825       break;
2826     }
2827     }
2828   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2829     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2830     // Eventually we will support lowering the @llvm.experimental.deoptimize
2831     // intrinsic, and right now there are no plans to support other intrinsics
2832     // with deopt state.
2833     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2834   } else {
2835     LowerCallTo(I, getValue(Callee), false, EHPadBB);
2836   }
2837 
2838   // If the value of the invoke is used outside of its defining block, make it
2839   // available as a virtual register.
2840   // We already took care of the exported value for the statepoint instruction
2841   // during call to the LowerStatepoint.
2842   if (!isa<GCStatepointInst>(I)) {
2843     CopyToExportRegsIfNeeded(&I);
2844   }
2845 
2846   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2847   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2848   BranchProbability EHPadBBProb =
2849       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2850           : BranchProbability::getZero();
2851   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2852 
2853   // Update successor info.
2854   addSuccessorWithProb(InvokeMBB, Return);
2855   for (auto &UnwindDest : UnwindDests) {
2856     UnwindDest.first->setIsEHPad();
2857     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2858   }
2859   InvokeMBB->normalizeSuccProbs();
2860 
2861   // Drop into normal successor.
2862   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2863                           DAG.getBasicBlock(Return)));
2864 }
2865 
2866 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2867   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2868 
2869   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2870   // have to do anything here to lower funclet bundles.
2871   assert(!I.hasOperandBundlesOtherThan(
2872              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2873          "Cannot lower callbrs with arbitrary operand bundles yet!");
2874 
2875   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
2876   visitInlineAsm(I);
2877   CopyToExportRegsIfNeeded(&I);
2878 
2879   // Retrieve successors.
2880   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2881 
2882   // Update successor info.
2883   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
2884   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2885     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2886     addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
2887     Target->setIsInlineAsmBrIndirectTarget();
2888   }
2889   CallBrMBB->normalizeSuccProbs();
2890 
2891   // Drop into default successor.
2892   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2893                           MVT::Other, getControlRoot(),
2894                           DAG.getBasicBlock(Return)));
2895 }
2896 
2897 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2898   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2899 }
2900 
2901 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2902   assert(FuncInfo.MBB->isEHPad() &&
2903          "Call to landingpad not in landing pad!");
2904 
2905   // If there aren't registers to copy the values into (e.g., during SjLj
2906   // exceptions), then don't bother to create these DAG nodes.
2907   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2908   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2909   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2910       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2911     return;
2912 
2913   // If landingpad's return type is token type, we don't create DAG nodes
2914   // for its exception pointer and selector value. The extraction of exception
2915   // pointer or selector value from token type landingpads is not currently
2916   // supported.
2917   if (LP.getType()->isTokenTy())
2918     return;
2919 
2920   SmallVector<EVT, 2> ValueVTs;
2921   SDLoc dl = getCurSDLoc();
2922   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2923   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2924 
2925   // Get the two live-in registers as SDValues. The physregs have already been
2926   // copied into virtual registers.
2927   SDValue Ops[2];
2928   if (FuncInfo.ExceptionPointerVirtReg) {
2929     Ops[0] = DAG.getZExtOrTrunc(
2930         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2931                            FuncInfo.ExceptionPointerVirtReg,
2932                            TLI.getPointerTy(DAG.getDataLayout())),
2933         dl, ValueVTs[0]);
2934   } else {
2935     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2936   }
2937   Ops[1] = DAG.getZExtOrTrunc(
2938       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2939                          FuncInfo.ExceptionSelectorVirtReg,
2940                          TLI.getPointerTy(DAG.getDataLayout())),
2941       dl, ValueVTs[1]);
2942 
2943   // Merge into one.
2944   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2945                             DAG.getVTList(ValueVTs), Ops);
2946   setValue(&LP, Res);
2947 }
2948 
2949 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2950                                            MachineBasicBlock *Last) {
2951   // Update JTCases.
2952   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2953     if (SL->JTCases[i].first.HeaderBB == First)
2954       SL->JTCases[i].first.HeaderBB = Last;
2955 
2956   // Update BitTestCases.
2957   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2958     if (SL->BitTestCases[i].Parent == First)
2959       SL->BitTestCases[i].Parent = Last;
2960 }
2961 
2962 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2963   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2964 
2965   // Update machine-CFG edges with unique successors.
2966   SmallSet<BasicBlock*, 32> Done;
2967   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2968     BasicBlock *BB = I.getSuccessor(i);
2969     bool Inserted = Done.insert(BB).second;
2970     if (!Inserted)
2971         continue;
2972 
2973     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2974     addSuccessorWithProb(IndirectBrMBB, Succ);
2975   }
2976   IndirectBrMBB->normalizeSuccProbs();
2977 
2978   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2979                           MVT::Other, getControlRoot(),
2980                           getValue(I.getAddress())));
2981 }
2982 
2983 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2984   if (!DAG.getTarget().Options.TrapUnreachable)
2985     return;
2986 
2987   // We may be able to ignore unreachable behind a noreturn call.
2988   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2989     const BasicBlock &BB = *I.getParent();
2990     if (&I != &BB.front()) {
2991       BasicBlock::const_iterator PredI =
2992         std::prev(BasicBlock::const_iterator(&I));
2993       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2994         if (Call->doesNotReturn())
2995           return;
2996       }
2997     }
2998   }
2999 
3000   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3001 }
3002 
3003 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3004   SDNodeFlags Flags;
3005 
3006   SDValue Op = getValue(I.getOperand(0));
3007   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3008                                     Op, Flags);
3009   setValue(&I, UnNodeValue);
3010 }
3011 
3012 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3013   SDNodeFlags Flags;
3014   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3015     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3016     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3017   }
3018   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3019     Flags.setExact(ExactOp->isExact());
3020   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3021     Flags.copyFMF(*FPOp);
3022 
3023   SDValue Op1 = getValue(I.getOperand(0));
3024   SDValue Op2 = getValue(I.getOperand(1));
3025   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3026                                      Op1, Op2, Flags);
3027   setValue(&I, BinNodeValue);
3028 }
3029 
3030 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3031   SDValue Op1 = getValue(I.getOperand(0));
3032   SDValue Op2 = getValue(I.getOperand(1));
3033 
3034   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3035       Op1.getValueType(), DAG.getDataLayout());
3036 
3037   // Coerce the shift amount to the right type if we can.
3038   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3039     unsigned ShiftSize = ShiftTy.getSizeInBits();
3040     unsigned Op2Size = Op2.getValueSizeInBits();
3041     SDLoc DL = getCurSDLoc();
3042 
3043     // If the operand is smaller than the shift count type, promote it.
3044     if (ShiftSize > Op2Size)
3045       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3046 
3047     // If the operand is larger than the shift count type but the shift
3048     // count type has enough bits to represent any shift value, truncate
3049     // it now. This is a common case and it exposes the truncate to
3050     // optimization early.
3051     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3052       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3053     // Otherwise we'll need to temporarily settle for some other convenient
3054     // type.  Type legalization will make adjustments once the shiftee is split.
3055     else
3056       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3057   }
3058 
3059   bool nuw = false;
3060   bool nsw = false;
3061   bool exact = false;
3062 
3063   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3064 
3065     if (const OverflowingBinaryOperator *OFBinOp =
3066             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3067       nuw = OFBinOp->hasNoUnsignedWrap();
3068       nsw = OFBinOp->hasNoSignedWrap();
3069     }
3070     if (const PossiblyExactOperator *ExactOp =
3071             dyn_cast<const PossiblyExactOperator>(&I))
3072       exact = ExactOp->isExact();
3073   }
3074   SDNodeFlags Flags;
3075   Flags.setExact(exact);
3076   Flags.setNoSignedWrap(nsw);
3077   Flags.setNoUnsignedWrap(nuw);
3078   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3079                             Flags);
3080   setValue(&I, Res);
3081 }
3082 
3083 void SelectionDAGBuilder::visitSDiv(const User &I) {
3084   SDValue Op1 = getValue(I.getOperand(0));
3085   SDValue Op2 = getValue(I.getOperand(1));
3086 
3087   SDNodeFlags Flags;
3088   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3089                  cast<PossiblyExactOperator>(&I)->isExact());
3090   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3091                            Op2, Flags));
3092 }
3093 
3094 void SelectionDAGBuilder::visitICmp(const User &I) {
3095   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3096   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3097     predicate = IC->getPredicate();
3098   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3099     predicate = ICmpInst::Predicate(IC->getPredicate());
3100   SDValue Op1 = getValue(I.getOperand(0));
3101   SDValue Op2 = getValue(I.getOperand(1));
3102   ISD::CondCode Opcode = getICmpCondCode(predicate);
3103 
3104   auto &TLI = DAG.getTargetLoweringInfo();
3105   EVT MemVT =
3106       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3107 
3108   // If a pointer's DAG type is larger than its memory type then the DAG values
3109   // are zero-extended. This breaks signed comparisons so truncate back to the
3110   // underlying type before doing the compare.
3111   if (Op1.getValueType() != MemVT) {
3112     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3113     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3114   }
3115 
3116   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3117                                                         I.getType());
3118   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3119 }
3120 
3121 void SelectionDAGBuilder::visitFCmp(const User &I) {
3122   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3123   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3124     predicate = FC->getPredicate();
3125   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3126     predicate = FCmpInst::Predicate(FC->getPredicate());
3127   SDValue Op1 = getValue(I.getOperand(0));
3128   SDValue Op2 = getValue(I.getOperand(1));
3129 
3130   ISD::CondCode Condition = getFCmpCondCode(predicate);
3131   auto *FPMO = cast<FPMathOperator>(&I);
3132   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3133     Condition = getFCmpCodeWithoutNaN(Condition);
3134 
3135   SDNodeFlags Flags;
3136   Flags.copyFMF(*FPMO);
3137   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3138 
3139   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3140                                                         I.getType());
3141   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3142 }
3143 
3144 // Check if the condition of the select has one use or two users that are both
3145 // selects with the same condition.
3146 static bool hasOnlySelectUsers(const Value *Cond) {
3147   return llvm::all_of(Cond->users(), [](const Value *V) {
3148     return isa<SelectInst>(V);
3149   });
3150 }
3151 
3152 void SelectionDAGBuilder::visitSelect(const User &I) {
3153   SmallVector<EVT, 4> ValueVTs;
3154   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3155                   ValueVTs);
3156   unsigned NumValues = ValueVTs.size();
3157   if (NumValues == 0) return;
3158 
3159   SmallVector<SDValue, 4> Values(NumValues);
3160   SDValue Cond     = getValue(I.getOperand(0));
3161   SDValue LHSVal   = getValue(I.getOperand(1));
3162   SDValue RHSVal   = getValue(I.getOperand(2));
3163   SmallVector<SDValue, 1> BaseOps(1, Cond);
3164   ISD::NodeType OpCode =
3165       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3166 
3167   bool IsUnaryAbs = false;
3168   bool Negate = false;
3169 
3170   SDNodeFlags Flags;
3171   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3172     Flags.copyFMF(*FPOp);
3173 
3174   // Min/max matching is only viable if all output VTs are the same.
3175   if (is_splat(ValueVTs)) {
3176     EVT VT = ValueVTs[0];
3177     LLVMContext &Ctx = *DAG.getContext();
3178     auto &TLI = DAG.getTargetLoweringInfo();
3179 
3180     // We care about the legality of the operation after it has been type
3181     // legalized.
3182     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3183       VT = TLI.getTypeToTransformTo(Ctx, VT);
3184 
3185     // If the vselect is legal, assume we want to leave this as a vector setcc +
3186     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3187     // min/max is legal on the scalar type.
3188     bool UseScalarMinMax = VT.isVector() &&
3189       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3190 
3191     Value *LHS, *RHS;
3192     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3193     ISD::NodeType Opc = ISD::DELETED_NODE;
3194     switch (SPR.Flavor) {
3195     case SPF_UMAX:    Opc = ISD::UMAX; break;
3196     case SPF_UMIN:    Opc = ISD::UMIN; break;
3197     case SPF_SMAX:    Opc = ISD::SMAX; break;
3198     case SPF_SMIN:    Opc = ISD::SMIN; break;
3199     case SPF_FMINNUM:
3200       switch (SPR.NaNBehavior) {
3201       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3202       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3203       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3204       case SPNB_RETURNS_ANY: {
3205         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3206           Opc = ISD::FMINNUM;
3207         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3208           Opc = ISD::FMINIMUM;
3209         else if (UseScalarMinMax)
3210           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3211             ISD::FMINNUM : ISD::FMINIMUM;
3212         break;
3213       }
3214       }
3215       break;
3216     case SPF_FMAXNUM:
3217       switch (SPR.NaNBehavior) {
3218       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3219       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3220       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3221       case SPNB_RETURNS_ANY:
3222 
3223         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3224           Opc = ISD::FMAXNUM;
3225         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3226           Opc = ISD::FMAXIMUM;
3227         else if (UseScalarMinMax)
3228           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3229             ISD::FMAXNUM : ISD::FMAXIMUM;
3230         break;
3231       }
3232       break;
3233     case SPF_NABS:
3234       Negate = true;
3235       LLVM_FALLTHROUGH;
3236     case SPF_ABS:
3237       IsUnaryAbs = true;
3238       Opc = ISD::ABS;
3239       break;
3240     default: break;
3241     }
3242 
3243     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3244         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3245          (UseScalarMinMax &&
3246           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3247         // If the underlying comparison instruction is used by any other
3248         // instruction, the consumed instructions won't be destroyed, so it is
3249         // not profitable to convert to a min/max.
3250         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3251       OpCode = Opc;
3252       LHSVal = getValue(LHS);
3253       RHSVal = getValue(RHS);
3254       BaseOps.clear();
3255     }
3256 
3257     if (IsUnaryAbs) {
3258       OpCode = Opc;
3259       LHSVal = getValue(LHS);
3260       BaseOps.clear();
3261     }
3262   }
3263 
3264   if (IsUnaryAbs) {
3265     for (unsigned i = 0; i != NumValues; ++i) {
3266       SDLoc dl = getCurSDLoc();
3267       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3268       Values[i] =
3269           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3270       if (Negate)
3271         Values[i] = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT),
3272                                 Values[i]);
3273     }
3274   } else {
3275     for (unsigned i = 0; i != NumValues; ++i) {
3276       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3277       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3278       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3279       Values[i] = DAG.getNode(
3280           OpCode, getCurSDLoc(),
3281           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3282     }
3283   }
3284 
3285   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3286                            DAG.getVTList(ValueVTs), Values));
3287 }
3288 
3289 void SelectionDAGBuilder::visitTrunc(const User &I) {
3290   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3291   SDValue N = getValue(I.getOperand(0));
3292   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3293                                                         I.getType());
3294   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3295 }
3296 
3297 void SelectionDAGBuilder::visitZExt(const User &I) {
3298   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3299   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3300   SDValue N = getValue(I.getOperand(0));
3301   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3302                                                         I.getType());
3303   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3304 }
3305 
3306 void SelectionDAGBuilder::visitSExt(const User &I) {
3307   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3308   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3309   SDValue N = getValue(I.getOperand(0));
3310   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3311                                                         I.getType());
3312   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3313 }
3314 
3315 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3316   // FPTrunc is never a no-op cast, no need to check
3317   SDValue N = getValue(I.getOperand(0));
3318   SDLoc dl = getCurSDLoc();
3319   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3320   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3321   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3322                            DAG.getTargetConstant(
3323                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3324 }
3325 
3326 void SelectionDAGBuilder::visitFPExt(const User &I) {
3327   // FPExt is never a no-op cast, no need to check
3328   SDValue N = getValue(I.getOperand(0));
3329   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3330                                                         I.getType());
3331   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3332 }
3333 
3334 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3335   // FPToUI is never a no-op cast, no need to check
3336   SDValue N = getValue(I.getOperand(0));
3337   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3338                                                         I.getType());
3339   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3340 }
3341 
3342 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3343   // FPToSI is never a no-op cast, no need to check
3344   SDValue N = getValue(I.getOperand(0));
3345   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3346                                                         I.getType());
3347   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3348 }
3349 
3350 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3351   // UIToFP is never a no-op cast, no need to check
3352   SDValue N = getValue(I.getOperand(0));
3353   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3354                                                         I.getType());
3355   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3356 }
3357 
3358 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3359   // SIToFP is never a no-op cast, no need to check
3360   SDValue N = getValue(I.getOperand(0));
3361   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3362                                                         I.getType());
3363   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3364 }
3365 
3366 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3367   // What to do depends on the size of the integer and the size of the pointer.
3368   // We can either truncate, zero extend, or no-op, accordingly.
3369   SDValue N = getValue(I.getOperand(0));
3370   auto &TLI = DAG.getTargetLoweringInfo();
3371   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3372                                                         I.getType());
3373   EVT PtrMemVT =
3374       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3375   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3376   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3377   setValue(&I, N);
3378 }
3379 
3380 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3381   // What to do depends on the size of the integer and the size of the pointer.
3382   // We can either truncate, zero extend, or no-op, accordingly.
3383   SDValue N = getValue(I.getOperand(0));
3384   auto &TLI = DAG.getTargetLoweringInfo();
3385   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3386   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3387   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3388   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3389   setValue(&I, N);
3390 }
3391 
3392 void SelectionDAGBuilder::visitBitCast(const User &I) {
3393   SDValue N = getValue(I.getOperand(0));
3394   SDLoc dl = getCurSDLoc();
3395   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3396                                                         I.getType());
3397 
3398   // BitCast assures us that source and destination are the same size so this is
3399   // either a BITCAST or a no-op.
3400   if (DestVT != N.getValueType())
3401     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3402                              DestVT, N)); // convert types.
3403   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3404   // might fold any kind of constant expression to an integer constant and that
3405   // is not what we are looking for. Only recognize a bitcast of a genuine
3406   // constant integer as an opaque constant.
3407   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3408     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3409                                  /*isOpaque*/true));
3410   else
3411     setValue(&I, N);            // noop cast.
3412 }
3413 
3414 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3415   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3416   const Value *SV = I.getOperand(0);
3417   SDValue N = getValue(SV);
3418   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3419 
3420   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3421   unsigned DestAS = I.getType()->getPointerAddressSpace();
3422 
3423   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3424     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3425 
3426   setValue(&I, N);
3427 }
3428 
3429 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3431   SDValue InVec = getValue(I.getOperand(0));
3432   SDValue InVal = getValue(I.getOperand(1));
3433   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3434                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3435   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3436                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3437                            InVec, InVal, InIdx));
3438 }
3439 
3440 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3442   SDValue InVec = getValue(I.getOperand(0));
3443   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3444                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3445   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3446                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3447                            InVec, InIdx));
3448 }
3449 
3450 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3451   SDValue Src1 = getValue(I.getOperand(0));
3452   SDValue Src2 = getValue(I.getOperand(1));
3453   ArrayRef<int> Mask;
3454   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3455     Mask = SVI->getShuffleMask();
3456   else
3457     Mask = cast<ConstantExpr>(I).getShuffleMask();
3458   SDLoc DL = getCurSDLoc();
3459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3460   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3461   EVT SrcVT = Src1.getValueType();
3462 
3463   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3464       VT.isScalableVector()) {
3465     // Canonical splat form of first element of first input vector.
3466     SDValue FirstElt =
3467         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3468                     DAG.getVectorIdxConstant(0, DL));
3469     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3470     return;
3471   }
3472 
3473   // For now, we only handle splats for scalable vectors.
3474   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3475   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3476   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3477 
3478   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3479   unsigned MaskNumElts = Mask.size();
3480 
3481   if (SrcNumElts == MaskNumElts) {
3482     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3483     return;
3484   }
3485 
3486   // Normalize the shuffle vector since mask and vector length don't match.
3487   if (SrcNumElts < MaskNumElts) {
3488     // Mask is longer than the source vectors. We can use concatenate vector to
3489     // make the mask and vectors lengths match.
3490 
3491     if (MaskNumElts % SrcNumElts == 0) {
3492       // Mask length is a multiple of the source vector length.
3493       // Check if the shuffle is some kind of concatenation of the input
3494       // vectors.
3495       unsigned NumConcat = MaskNumElts / SrcNumElts;
3496       bool IsConcat = true;
3497       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3498       for (unsigned i = 0; i != MaskNumElts; ++i) {
3499         int Idx = Mask[i];
3500         if (Idx < 0)
3501           continue;
3502         // Ensure the indices in each SrcVT sized piece are sequential and that
3503         // the same source is used for the whole piece.
3504         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3505             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3506              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3507           IsConcat = false;
3508           break;
3509         }
3510         // Remember which source this index came from.
3511         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3512       }
3513 
3514       // The shuffle is concatenating multiple vectors together. Just emit
3515       // a CONCAT_VECTORS operation.
3516       if (IsConcat) {
3517         SmallVector<SDValue, 8> ConcatOps;
3518         for (auto Src : ConcatSrcs) {
3519           if (Src < 0)
3520             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3521           else if (Src == 0)
3522             ConcatOps.push_back(Src1);
3523           else
3524             ConcatOps.push_back(Src2);
3525         }
3526         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3527         return;
3528       }
3529     }
3530 
3531     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3532     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3533     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3534                                     PaddedMaskNumElts);
3535 
3536     // Pad both vectors with undefs to make them the same length as the mask.
3537     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3538 
3539     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3540     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3541     MOps1[0] = Src1;
3542     MOps2[0] = Src2;
3543 
3544     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3545     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3546 
3547     // Readjust mask for new input vector length.
3548     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3549     for (unsigned i = 0; i != MaskNumElts; ++i) {
3550       int Idx = Mask[i];
3551       if (Idx >= (int)SrcNumElts)
3552         Idx -= SrcNumElts - PaddedMaskNumElts;
3553       MappedOps[i] = Idx;
3554     }
3555 
3556     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3557 
3558     // If the concatenated vector was padded, extract a subvector with the
3559     // correct number of elements.
3560     if (MaskNumElts != PaddedMaskNumElts)
3561       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3562                            DAG.getVectorIdxConstant(0, DL));
3563 
3564     setValue(&I, Result);
3565     return;
3566   }
3567 
3568   if (SrcNumElts > MaskNumElts) {
3569     // Analyze the access pattern of the vector to see if we can extract
3570     // two subvectors and do the shuffle.
3571     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3572     bool CanExtract = true;
3573     for (int Idx : Mask) {
3574       unsigned Input = 0;
3575       if (Idx < 0)
3576         continue;
3577 
3578       if (Idx >= (int)SrcNumElts) {
3579         Input = 1;
3580         Idx -= SrcNumElts;
3581       }
3582 
3583       // If all the indices come from the same MaskNumElts sized portion of
3584       // the sources we can use extract. Also make sure the extract wouldn't
3585       // extract past the end of the source.
3586       int NewStartIdx = alignDown(Idx, MaskNumElts);
3587       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3588           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3589         CanExtract = false;
3590       // Make sure we always update StartIdx as we use it to track if all
3591       // elements are undef.
3592       StartIdx[Input] = NewStartIdx;
3593     }
3594 
3595     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3596       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3597       return;
3598     }
3599     if (CanExtract) {
3600       // Extract appropriate subvector and generate a vector shuffle
3601       for (unsigned Input = 0; Input < 2; ++Input) {
3602         SDValue &Src = Input == 0 ? Src1 : Src2;
3603         if (StartIdx[Input] < 0)
3604           Src = DAG.getUNDEF(VT);
3605         else {
3606           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3607                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3608         }
3609       }
3610 
3611       // Calculate new mask.
3612       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3613       for (int &Idx : MappedOps) {
3614         if (Idx >= (int)SrcNumElts)
3615           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3616         else if (Idx >= 0)
3617           Idx -= StartIdx[0];
3618       }
3619 
3620       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3621       return;
3622     }
3623   }
3624 
3625   // We can't use either concat vectors or extract subvectors so fall back to
3626   // replacing the shuffle with extract and build vector.
3627   // to insert and build vector.
3628   EVT EltVT = VT.getVectorElementType();
3629   SmallVector<SDValue,8> Ops;
3630   for (int Idx : Mask) {
3631     SDValue Res;
3632 
3633     if (Idx < 0) {
3634       Res = DAG.getUNDEF(EltVT);
3635     } else {
3636       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3637       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3638 
3639       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3640                         DAG.getVectorIdxConstant(Idx, DL));
3641     }
3642 
3643     Ops.push_back(Res);
3644   }
3645 
3646   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3647 }
3648 
3649 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3650   ArrayRef<unsigned> Indices;
3651   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3652     Indices = IV->getIndices();
3653   else
3654     Indices = cast<ConstantExpr>(&I)->getIndices();
3655 
3656   const Value *Op0 = I.getOperand(0);
3657   const Value *Op1 = I.getOperand(1);
3658   Type *AggTy = I.getType();
3659   Type *ValTy = Op1->getType();
3660   bool IntoUndef = isa<UndefValue>(Op0);
3661   bool FromUndef = isa<UndefValue>(Op1);
3662 
3663   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3664 
3665   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3666   SmallVector<EVT, 4> AggValueVTs;
3667   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3668   SmallVector<EVT, 4> ValValueVTs;
3669   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3670 
3671   unsigned NumAggValues = AggValueVTs.size();
3672   unsigned NumValValues = ValValueVTs.size();
3673   SmallVector<SDValue, 4> Values(NumAggValues);
3674 
3675   // Ignore an insertvalue that produces an empty object
3676   if (!NumAggValues) {
3677     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3678     return;
3679   }
3680 
3681   SDValue Agg = getValue(Op0);
3682   unsigned i = 0;
3683   // Copy the beginning value(s) from the original aggregate.
3684   for (; i != LinearIndex; ++i)
3685     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3686                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3687   // Copy values from the inserted value(s).
3688   if (NumValValues) {
3689     SDValue Val = getValue(Op1);
3690     for (; i != LinearIndex + NumValValues; ++i)
3691       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3692                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3693   }
3694   // Copy remaining value(s) from the original aggregate.
3695   for (; i != NumAggValues; ++i)
3696     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3697                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3698 
3699   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3700                            DAG.getVTList(AggValueVTs), Values));
3701 }
3702 
3703 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3704   ArrayRef<unsigned> Indices;
3705   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3706     Indices = EV->getIndices();
3707   else
3708     Indices = cast<ConstantExpr>(&I)->getIndices();
3709 
3710   const Value *Op0 = I.getOperand(0);
3711   Type *AggTy = Op0->getType();
3712   Type *ValTy = I.getType();
3713   bool OutOfUndef = isa<UndefValue>(Op0);
3714 
3715   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3716 
3717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3718   SmallVector<EVT, 4> ValValueVTs;
3719   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3720 
3721   unsigned NumValValues = ValValueVTs.size();
3722 
3723   // Ignore a extractvalue that produces an empty object
3724   if (!NumValValues) {
3725     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3726     return;
3727   }
3728 
3729   SmallVector<SDValue, 4> Values(NumValValues);
3730 
3731   SDValue Agg = getValue(Op0);
3732   // Copy out the selected value(s).
3733   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3734     Values[i - LinearIndex] =
3735       OutOfUndef ?
3736         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3737         SDValue(Agg.getNode(), Agg.getResNo() + i);
3738 
3739   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3740                            DAG.getVTList(ValValueVTs), Values));
3741 }
3742 
3743 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3744   Value *Op0 = I.getOperand(0);
3745   // Note that the pointer operand may be a vector of pointers. Take the scalar
3746   // element which holds a pointer.
3747   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3748   SDValue N = getValue(Op0);
3749   SDLoc dl = getCurSDLoc();
3750   auto &TLI = DAG.getTargetLoweringInfo();
3751 
3752   // Normalize Vector GEP - all scalar operands should be converted to the
3753   // splat vector.
3754   bool IsVectorGEP = I.getType()->isVectorTy();
3755   ElementCount VectorElementCount =
3756       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
3757                   : ElementCount::getFixed(0);
3758 
3759   if (IsVectorGEP && !N.getValueType().isVector()) {
3760     LLVMContext &Context = *DAG.getContext();
3761     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3762     if (VectorElementCount.isScalable())
3763       N = DAG.getSplatVector(VT, dl, N);
3764     else
3765       N = DAG.getSplatBuildVector(VT, dl, N);
3766   }
3767 
3768   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3769        GTI != E; ++GTI) {
3770     const Value *Idx = GTI.getOperand();
3771     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3772       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3773       if (Field) {
3774         // N = N + Offset
3775         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3776 
3777         // In an inbounds GEP with an offset that is nonnegative even when
3778         // interpreted as signed, assume there is no unsigned overflow.
3779         SDNodeFlags Flags;
3780         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3781           Flags.setNoUnsignedWrap(true);
3782 
3783         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3784                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3785       }
3786     } else {
3787       // IdxSize is the width of the arithmetic according to IR semantics.
3788       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3789       // (and fix up the result later).
3790       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3791       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3792       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3793       // We intentionally mask away the high bits here; ElementSize may not
3794       // fit in IdxTy.
3795       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3796       bool ElementScalable = ElementSize.isScalable();
3797 
3798       // If this is a scalar constant or a splat vector of constants,
3799       // handle it quickly.
3800       const auto *C = dyn_cast<Constant>(Idx);
3801       if (C && isa<VectorType>(C->getType()))
3802         C = C->getSplatValue();
3803 
3804       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3805       if (CI && CI->isZero())
3806         continue;
3807       if (CI && !ElementScalable) {
3808         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3809         LLVMContext &Context = *DAG.getContext();
3810         SDValue OffsVal;
3811         if (IsVectorGEP)
3812           OffsVal = DAG.getConstant(
3813               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3814         else
3815           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3816 
3817         // In an inbounds GEP with an offset that is nonnegative even when
3818         // interpreted as signed, assume there is no unsigned overflow.
3819         SDNodeFlags Flags;
3820         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3821           Flags.setNoUnsignedWrap(true);
3822 
3823         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3824 
3825         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3826         continue;
3827       }
3828 
3829       // N = N + Idx * ElementMul;
3830       SDValue IdxN = getValue(Idx);
3831 
3832       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3833         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3834                                   VectorElementCount);
3835         if (VectorElementCount.isScalable())
3836           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3837         else
3838           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3839       }
3840 
3841       // If the index is smaller or larger than intptr_t, truncate or extend
3842       // it.
3843       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3844 
3845       if (ElementScalable) {
3846         EVT VScaleTy = N.getValueType().getScalarType();
3847         SDValue VScale = DAG.getNode(
3848             ISD::VSCALE, dl, VScaleTy,
3849             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3850         if (IsVectorGEP)
3851           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3852         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3853       } else {
3854         // If this is a multiply by a power of two, turn it into a shl
3855         // immediately.  This is a very common case.
3856         if (ElementMul != 1) {
3857           if (ElementMul.isPowerOf2()) {
3858             unsigned Amt = ElementMul.logBase2();
3859             IdxN = DAG.getNode(ISD::SHL, dl,
3860                                N.getValueType(), IdxN,
3861                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3862           } else {
3863             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3864                                             IdxN.getValueType());
3865             IdxN = DAG.getNode(ISD::MUL, dl,
3866                                N.getValueType(), IdxN, Scale);
3867           }
3868         }
3869       }
3870 
3871       N = DAG.getNode(ISD::ADD, dl,
3872                       N.getValueType(), N, IdxN);
3873     }
3874   }
3875 
3876   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3877   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3878   if (IsVectorGEP) {
3879     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
3880     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
3881   }
3882 
3883   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3884     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3885 
3886   setValue(&I, N);
3887 }
3888 
3889 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3890   // If this is a fixed sized alloca in the entry block of the function,
3891   // allocate it statically on the stack.
3892   if (FuncInfo.StaticAllocaMap.count(&I))
3893     return;   // getValue will auto-populate this.
3894 
3895   SDLoc dl = getCurSDLoc();
3896   Type *Ty = I.getAllocatedType();
3897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3898   auto &DL = DAG.getDataLayout();
3899   uint64_t TySize = DL.getTypeAllocSize(Ty);
3900   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
3901 
3902   SDValue AllocSize = getValue(I.getArraySize());
3903 
3904   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3905   if (AllocSize.getValueType() != IntPtr)
3906     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3907 
3908   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3909                           AllocSize,
3910                           DAG.getConstant(TySize, dl, IntPtr));
3911 
3912   // Handle alignment.  If the requested alignment is less than or equal to
3913   // the stack alignment, ignore it.  If the size is greater than or equal to
3914   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3915   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
3916   if (*Alignment <= StackAlign)
3917     Alignment = None;
3918 
3919   const uint64_t StackAlignMask = StackAlign.value() - 1U;
3920   // Round the size of the allocation up to the stack alignment size
3921   // by add SA-1 to the size. This doesn't overflow because we're computing
3922   // an address inside an alloca.
3923   SDNodeFlags Flags;
3924   Flags.setNoUnsignedWrap(true);
3925   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3926                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
3927 
3928   // Mask out the low bits for alignment purposes.
3929   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3930                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
3931 
3932   SDValue Ops[] = {
3933       getRoot(), AllocSize,
3934       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
3935   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3936   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3937   setValue(&I, DSA);
3938   DAG.setRoot(DSA.getValue(1));
3939 
3940   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3941 }
3942 
3943 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3944   if (I.isAtomic())
3945     return visitAtomicLoad(I);
3946 
3947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3948   const Value *SV = I.getOperand(0);
3949   if (TLI.supportSwiftError()) {
3950     // Swifterror values can come from either a function parameter with
3951     // swifterror attribute or an alloca with swifterror attribute.
3952     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3953       if (Arg->hasSwiftErrorAttr())
3954         return visitLoadFromSwiftError(I);
3955     }
3956 
3957     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3958       if (Alloca->isSwiftError())
3959         return visitLoadFromSwiftError(I);
3960     }
3961   }
3962 
3963   SDValue Ptr = getValue(SV);
3964 
3965   Type *Ty = I.getType();
3966   Align Alignment = I.getAlign();
3967 
3968   AAMDNodes AAInfo;
3969   I.getAAMetadata(AAInfo);
3970   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3971 
3972   SmallVector<EVT, 4> ValueVTs, MemVTs;
3973   SmallVector<uint64_t, 4> Offsets;
3974   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
3975   unsigned NumValues = ValueVTs.size();
3976   if (NumValues == 0)
3977     return;
3978 
3979   bool isVolatile = I.isVolatile();
3980 
3981   SDValue Root;
3982   bool ConstantMemory = false;
3983   if (isVolatile)
3984     // Serialize volatile loads with other side effects.
3985     Root = getRoot();
3986   else if (NumValues > MaxParallelChains)
3987     Root = getMemoryRoot();
3988   else if (AA &&
3989            AA->pointsToConstantMemory(MemoryLocation(
3990                SV,
3991                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3992                AAInfo))) {
3993     // Do not serialize (non-volatile) loads of constant memory with anything.
3994     Root = DAG.getEntryNode();
3995     ConstantMemory = true;
3996   } else {
3997     // Do not serialize non-volatile loads against each other.
3998     Root = DAG.getRoot();
3999   }
4000 
4001   SDLoc dl = getCurSDLoc();
4002 
4003   if (isVolatile)
4004     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4005 
4006   // An aggregate load cannot wrap around the address space, so offsets to its
4007   // parts don't wrap either.
4008   SDNodeFlags Flags;
4009   Flags.setNoUnsignedWrap(true);
4010 
4011   SmallVector<SDValue, 4> Values(NumValues);
4012   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4013   EVT PtrVT = Ptr.getValueType();
4014 
4015   MachineMemOperand::Flags MMOFlags
4016     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4017 
4018   unsigned ChainI = 0;
4019   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4020     // Serializing loads here may result in excessive register pressure, and
4021     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4022     // could recover a bit by hoisting nodes upward in the chain by recognizing
4023     // they are side-effect free or do not alias. The optimizer should really
4024     // avoid this case by converting large object/array copies to llvm.memcpy
4025     // (MaxParallelChains should always remain as failsafe).
4026     if (ChainI == MaxParallelChains) {
4027       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4028       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4029                                   makeArrayRef(Chains.data(), ChainI));
4030       Root = Chain;
4031       ChainI = 0;
4032     }
4033     SDValue A = DAG.getNode(ISD::ADD, dl,
4034                             PtrVT, Ptr,
4035                             DAG.getConstant(Offsets[i], dl, PtrVT),
4036                             Flags);
4037 
4038     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4039                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4040                             MMOFlags, AAInfo, Ranges);
4041     Chains[ChainI] = L.getValue(1);
4042 
4043     if (MemVTs[i] != ValueVTs[i])
4044       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4045 
4046     Values[i] = L;
4047   }
4048 
4049   if (!ConstantMemory) {
4050     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4051                                 makeArrayRef(Chains.data(), ChainI));
4052     if (isVolatile)
4053       DAG.setRoot(Chain);
4054     else
4055       PendingLoads.push_back(Chain);
4056   }
4057 
4058   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4059                            DAG.getVTList(ValueVTs), Values));
4060 }
4061 
4062 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4063   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4064          "call visitStoreToSwiftError when backend supports swifterror");
4065 
4066   SmallVector<EVT, 4> ValueVTs;
4067   SmallVector<uint64_t, 4> Offsets;
4068   const Value *SrcV = I.getOperand(0);
4069   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4070                   SrcV->getType(), ValueVTs, &Offsets);
4071   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4072          "expect a single EVT for swifterror");
4073 
4074   SDValue Src = getValue(SrcV);
4075   // Create a virtual register, then update the virtual register.
4076   Register VReg =
4077       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4078   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4079   // Chain can be getRoot or getControlRoot.
4080   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4081                                       SDValue(Src.getNode(), Src.getResNo()));
4082   DAG.setRoot(CopyNode);
4083 }
4084 
4085 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4086   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4087          "call visitLoadFromSwiftError when backend supports swifterror");
4088 
4089   assert(!I.isVolatile() &&
4090          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4091          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4092          "Support volatile, non temporal, invariant for load_from_swift_error");
4093 
4094   const Value *SV = I.getOperand(0);
4095   Type *Ty = I.getType();
4096   AAMDNodes AAInfo;
4097   I.getAAMetadata(AAInfo);
4098   assert(
4099       (!AA ||
4100        !AA->pointsToConstantMemory(MemoryLocation(
4101            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4102            AAInfo))) &&
4103       "load_from_swift_error should not be constant memory");
4104 
4105   SmallVector<EVT, 4> ValueVTs;
4106   SmallVector<uint64_t, 4> Offsets;
4107   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4108                   ValueVTs, &Offsets);
4109   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4110          "expect a single EVT for swifterror");
4111 
4112   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4113   SDValue L = DAG.getCopyFromReg(
4114       getRoot(), getCurSDLoc(),
4115       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4116 
4117   setValue(&I, L);
4118 }
4119 
4120 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4121   if (I.isAtomic())
4122     return visitAtomicStore(I);
4123 
4124   const Value *SrcV = I.getOperand(0);
4125   const Value *PtrV = I.getOperand(1);
4126 
4127   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4128   if (TLI.supportSwiftError()) {
4129     // Swifterror values can come from either a function parameter with
4130     // swifterror attribute or an alloca with swifterror attribute.
4131     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4132       if (Arg->hasSwiftErrorAttr())
4133         return visitStoreToSwiftError(I);
4134     }
4135 
4136     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4137       if (Alloca->isSwiftError())
4138         return visitStoreToSwiftError(I);
4139     }
4140   }
4141 
4142   SmallVector<EVT, 4> ValueVTs, MemVTs;
4143   SmallVector<uint64_t, 4> Offsets;
4144   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4145                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4146   unsigned NumValues = ValueVTs.size();
4147   if (NumValues == 0)
4148     return;
4149 
4150   // Get the lowered operands. Note that we do this after
4151   // checking if NumResults is zero, because with zero results
4152   // the operands won't have values in the map.
4153   SDValue Src = getValue(SrcV);
4154   SDValue Ptr = getValue(PtrV);
4155 
4156   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4157   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4158   SDLoc dl = getCurSDLoc();
4159   Align Alignment = I.getAlign();
4160   AAMDNodes AAInfo;
4161   I.getAAMetadata(AAInfo);
4162 
4163   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4164 
4165   // An aggregate load cannot wrap around the address space, so offsets to its
4166   // parts don't wrap either.
4167   SDNodeFlags Flags;
4168   Flags.setNoUnsignedWrap(true);
4169 
4170   unsigned ChainI = 0;
4171   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4172     // See visitLoad comments.
4173     if (ChainI == MaxParallelChains) {
4174       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4175                                   makeArrayRef(Chains.data(), ChainI));
4176       Root = Chain;
4177       ChainI = 0;
4178     }
4179     SDValue Add =
4180         DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(Offsets[i]), dl, Flags);
4181     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4182     if (MemVTs[i] != ValueVTs[i])
4183       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4184     SDValue St =
4185         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4186                      Alignment, MMOFlags, AAInfo);
4187     Chains[ChainI] = St;
4188   }
4189 
4190   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4191                                   makeArrayRef(Chains.data(), ChainI));
4192   DAG.setRoot(StoreNode);
4193 }
4194 
4195 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4196                                            bool IsCompressing) {
4197   SDLoc sdl = getCurSDLoc();
4198 
4199   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4200                                MaybeAlign &Alignment) {
4201     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4202     Src0 = I.getArgOperand(0);
4203     Ptr = I.getArgOperand(1);
4204     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getMaybeAlignValue();
4205     Mask = I.getArgOperand(3);
4206   };
4207   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4208                                     MaybeAlign &Alignment) {
4209     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4210     Src0 = I.getArgOperand(0);
4211     Ptr = I.getArgOperand(1);
4212     Mask = I.getArgOperand(2);
4213     Alignment = None;
4214   };
4215 
4216   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4217   MaybeAlign Alignment;
4218   if (IsCompressing)
4219     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4220   else
4221     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4222 
4223   SDValue Ptr = getValue(PtrOperand);
4224   SDValue Src0 = getValue(Src0Operand);
4225   SDValue Mask = getValue(MaskOperand);
4226   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4227 
4228   EVT VT = Src0.getValueType();
4229   if (!Alignment)
4230     Alignment = DAG.getEVTAlign(VT);
4231 
4232   AAMDNodes AAInfo;
4233   I.getAAMetadata(AAInfo);
4234 
4235   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4236       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4237       // TODO: Make MachineMemOperands aware of scalable
4238       // vectors.
4239       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo);
4240   SDValue StoreNode =
4241       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4242                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4243   DAG.setRoot(StoreNode);
4244   setValue(&I, StoreNode);
4245 }
4246 
4247 // Get a uniform base for the Gather/Scatter intrinsic.
4248 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4249 // We try to represent it as a base pointer + vector of indices.
4250 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4251 // The first operand of the GEP may be a single pointer or a vector of pointers
4252 // Example:
4253 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4254 //  or
4255 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4256 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4257 //
4258 // When the first GEP operand is a single pointer - it is the uniform base we
4259 // are looking for. If first operand of the GEP is a splat vector - we
4260 // extract the splat value and use it as a uniform base.
4261 // In all other cases the function returns 'false'.
4262 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4263                            ISD::MemIndexType &IndexType, SDValue &Scale,
4264                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB) {
4265   SelectionDAG& DAG = SDB->DAG;
4266   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4267   const DataLayout &DL = DAG.getDataLayout();
4268 
4269   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4270 
4271   // Handle splat constant pointer.
4272   if (auto *C = dyn_cast<Constant>(Ptr)) {
4273     C = C->getSplatValue();
4274     if (!C)
4275       return false;
4276 
4277     Base = SDB->getValue(C);
4278 
4279     unsigned NumElts = cast<FixedVectorType>(Ptr->getType())->getNumElements();
4280     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4281     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4282     IndexType = ISD::SIGNED_SCALED;
4283     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4284     return true;
4285   }
4286 
4287   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4288   if (!GEP || GEP->getParent() != CurBB)
4289     return false;
4290 
4291   if (GEP->getNumOperands() != 2)
4292     return false;
4293 
4294   const Value *BasePtr = GEP->getPointerOperand();
4295   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4296 
4297   // Make sure the base is scalar and the index is a vector.
4298   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4299     return false;
4300 
4301   Base = SDB->getValue(BasePtr);
4302   Index = SDB->getValue(IndexVal);
4303   IndexType = ISD::SIGNED_SCALED;
4304   Scale = DAG.getTargetConstant(
4305               DL.getTypeAllocSize(GEP->getResultElementType()),
4306               SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4307   return true;
4308 }
4309 
4310 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4311   SDLoc sdl = getCurSDLoc();
4312 
4313   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4314   const Value *Ptr = I.getArgOperand(1);
4315   SDValue Src0 = getValue(I.getArgOperand(0));
4316   SDValue Mask = getValue(I.getArgOperand(3));
4317   EVT VT = Src0.getValueType();
4318   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4319                         ->getMaybeAlignValue()
4320                         .getValueOr(DAG.getEVTAlign(VT));
4321   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4322 
4323   AAMDNodes AAInfo;
4324   I.getAAMetadata(AAInfo);
4325 
4326   SDValue Base;
4327   SDValue Index;
4328   ISD::MemIndexType IndexType;
4329   SDValue Scale;
4330   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4331                                     I.getParent());
4332 
4333   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4334   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4335       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4336       // TODO: Make MachineMemOperands aware of scalable
4337       // vectors.
4338       MemoryLocation::UnknownSize, Alignment, AAInfo);
4339   if (!UniformBase) {
4340     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4341     Index = getValue(Ptr);
4342     IndexType = ISD::SIGNED_UNSCALED;
4343     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4344   }
4345 
4346   EVT IdxVT = Index.getValueType();
4347   EVT EltTy = IdxVT.getVectorElementType();
4348   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4349     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4350     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4351   }
4352 
4353   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4354   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4355                                          Ops, MMO, IndexType, false);
4356   DAG.setRoot(Scatter);
4357   setValue(&I, Scatter);
4358 }
4359 
4360 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4361   SDLoc sdl = getCurSDLoc();
4362 
4363   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4364                               MaybeAlign &Alignment) {
4365     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4366     Ptr = I.getArgOperand(0);
4367     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getMaybeAlignValue();
4368     Mask = I.getArgOperand(2);
4369     Src0 = I.getArgOperand(3);
4370   };
4371   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4372                                  MaybeAlign &Alignment) {
4373     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4374     Ptr = I.getArgOperand(0);
4375     Alignment = None;
4376     Mask = I.getArgOperand(1);
4377     Src0 = I.getArgOperand(2);
4378   };
4379 
4380   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4381   MaybeAlign Alignment;
4382   if (IsExpanding)
4383     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4384   else
4385     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4386 
4387   SDValue Ptr = getValue(PtrOperand);
4388   SDValue Src0 = getValue(Src0Operand);
4389   SDValue Mask = getValue(MaskOperand);
4390   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4391 
4392   EVT VT = Src0.getValueType();
4393   if (!Alignment)
4394     Alignment = DAG.getEVTAlign(VT);
4395 
4396   AAMDNodes AAInfo;
4397   I.getAAMetadata(AAInfo);
4398   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4399 
4400   // Do not serialize masked loads of constant memory with anything.
4401   MemoryLocation ML;
4402   if (VT.isScalableVector())
4403     ML = MemoryLocation::getAfter(PtrOperand);
4404   else
4405     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4406                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4407                            AAInfo);
4408   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4409 
4410   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4411 
4412   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4413       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4414       // TODO: Make MachineMemOperands aware of scalable
4415       // vectors.
4416       VT.getStoreSize().getKnownMinSize(), *Alignment, AAInfo, Ranges);
4417 
4418   SDValue Load =
4419       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4420                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4421   if (AddToChain)
4422     PendingLoads.push_back(Load.getValue(1));
4423   setValue(&I, Load);
4424 }
4425 
4426 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4427   SDLoc sdl = getCurSDLoc();
4428 
4429   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4430   const Value *Ptr = I.getArgOperand(0);
4431   SDValue Src0 = getValue(I.getArgOperand(3));
4432   SDValue Mask = getValue(I.getArgOperand(2));
4433 
4434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4435   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4436   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4437                         ->getMaybeAlignValue()
4438                         .getValueOr(DAG.getEVTAlign(VT));
4439 
4440   AAMDNodes AAInfo;
4441   I.getAAMetadata(AAInfo);
4442   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4443 
4444   SDValue Root = DAG.getRoot();
4445   SDValue Base;
4446   SDValue Index;
4447   ISD::MemIndexType IndexType;
4448   SDValue Scale;
4449   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4450                                     I.getParent());
4451   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4452   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4453       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4454       // TODO: Make MachineMemOperands aware of scalable
4455       // vectors.
4456       MemoryLocation::UnknownSize, Alignment, AAInfo, Ranges);
4457 
4458   if (!UniformBase) {
4459     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4460     Index = getValue(Ptr);
4461     IndexType = ISD::SIGNED_UNSCALED;
4462     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4463   }
4464 
4465   EVT IdxVT = Index.getValueType();
4466   EVT EltTy = IdxVT.getVectorElementType();
4467   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4468     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4469     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4470   }
4471 
4472   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4473   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4474                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4475 
4476   PendingLoads.push_back(Gather.getValue(1));
4477   setValue(&I, Gather);
4478 }
4479 
4480 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4481   SDLoc dl = getCurSDLoc();
4482   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4483   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4484   SyncScope::ID SSID = I.getSyncScopeID();
4485 
4486   SDValue InChain = getRoot();
4487 
4488   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4489   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4490 
4491   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4492   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4493 
4494   MachineFunction &MF = DAG.getMachineFunction();
4495   MachineMemOperand *MMO = MF.getMachineMemOperand(
4496       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4497       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, SuccessOrdering,
4498       FailureOrdering);
4499 
4500   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4501                                    dl, MemVT, VTs, InChain,
4502                                    getValue(I.getPointerOperand()),
4503                                    getValue(I.getCompareOperand()),
4504                                    getValue(I.getNewValOperand()), MMO);
4505 
4506   SDValue OutChain = L.getValue(2);
4507 
4508   setValue(&I, L);
4509   DAG.setRoot(OutChain);
4510 }
4511 
4512 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4513   SDLoc dl = getCurSDLoc();
4514   ISD::NodeType NT;
4515   switch (I.getOperation()) {
4516   default: llvm_unreachable("Unknown atomicrmw operation");
4517   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4518   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4519   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4520   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4521   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4522   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4523   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4524   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4525   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4526   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4527   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4528   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4529   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4530   }
4531   AtomicOrdering Ordering = I.getOrdering();
4532   SyncScope::ID SSID = I.getSyncScopeID();
4533 
4534   SDValue InChain = getRoot();
4535 
4536   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4538   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4539 
4540   MachineFunction &MF = DAG.getMachineFunction();
4541   MachineMemOperand *MMO = MF.getMachineMemOperand(
4542       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4543       DAG.getEVTAlign(MemVT), AAMDNodes(), nullptr, SSID, Ordering);
4544 
4545   SDValue L =
4546     DAG.getAtomic(NT, dl, MemVT, InChain,
4547                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4548                   MMO);
4549 
4550   SDValue OutChain = L.getValue(1);
4551 
4552   setValue(&I, L);
4553   DAG.setRoot(OutChain);
4554 }
4555 
4556 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4557   SDLoc dl = getCurSDLoc();
4558   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4559   SDValue Ops[3];
4560   Ops[0] = getRoot();
4561   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4562                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4563   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4564                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4565   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4566 }
4567 
4568 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4569   SDLoc dl = getCurSDLoc();
4570   AtomicOrdering Order = I.getOrdering();
4571   SyncScope::ID SSID = I.getSyncScopeID();
4572 
4573   SDValue InChain = getRoot();
4574 
4575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4576   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4577   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4578 
4579   if (!TLI.supportsUnalignedAtomics() &&
4580       I.getAlignment() < MemVT.getSizeInBits() / 8)
4581     report_fatal_error("Cannot generate unaligned atomic load");
4582 
4583   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4584 
4585   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4586       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4587       I.getAlign(), AAMDNodes(), nullptr, SSID, Order);
4588 
4589   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4590 
4591   SDValue Ptr = getValue(I.getPointerOperand());
4592 
4593   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4594     // TODO: Once this is better exercised by tests, it should be merged with
4595     // the normal path for loads to prevent future divergence.
4596     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4597     if (MemVT != VT)
4598       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4599 
4600     setValue(&I, L);
4601     SDValue OutChain = L.getValue(1);
4602     if (!I.isUnordered())
4603       DAG.setRoot(OutChain);
4604     else
4605       PendingLoads.push_back(OutChain);
4606     return;
4607   }
4608 
4609   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4610                             Ptr, MMO);
4611 
4612   SDValue OutChain = L.getValue(1);
4613   if (MemVT != VT)
4614     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4615 
4616   setValue(&I, L);
4617   DAG.setRoot(OutChain);
4618 }
4619 
4620 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4621   SDLoc dl = getCurSDLoc();
4622 
4623   AtomicOrdering Ordering = I.getOrdering();
4624   SyncScope::ID SSID = I.getSyncScopeID();
4625 
4626   SDValue InChain = getRoot();
4627 
4628   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4629   EVT MemVT =
4630       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4631 
4632   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4633     report_fatal_error("Cannot generate unaligned atomic store");
4634 
4635   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4636 
4637   MachineFunction &MF = DAG.getMachineFunction();
4638   MachineMemOperand *MMO = MF.getMachineMemOperand(
4639       MachinePointerInfo(I.getPointerOperand()), Flags, MemVT.getStoreSize(),
4640       I.getAlign(), AAMDNodes(), nullptr, SSID, Ordering);
4641 
4642   SDValue Val = getValue(I.getValueOperand());
4643   if (Val.getValueType() != MemVT)
4644     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4645   SDValue Ptr = getValue(I.getPointerOperand());
4646 
4647   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4648     // TODO: Once this is better exercised by tests, it should be merged with
4649     // the normal path for stores to prevent future divergence.
4650     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4651     DAG.setRoot(S);
4652     return;
4653   }
4654   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4655                                    Ptr, Val, MMO);
4656 
4657 
4658   DAG.setRoot(OutChain);
4659 }
4660 
4661 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4662 /// node.
4663 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4664                                                unsigned Intrinsic) {
4665   // Ignore the callsite's attributes. A specific call site may be marked with
4666   // readnone, but the lowering code will expect the chain based on the
4667   // definition.
4668   const Function *F = I.getCalledFunction();
4669   bool HasChain = !F->doesNotAccessMemory();
4670   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4671 
4672   // Build the operand list.
4673   SmallVector<SDValue, 8> Ops;
4674   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4675     if (OnlyLoad) {
4676       // We don't need to serialize loads against other loads.
4677       Ops.push_back(DAG.getRoot());
4678     } else {
4679       Ops.push_back(getRoot());
4680     }
4681   }
4682 
4683   // Info is set by getTgtMemInstrinsic
4684   TargetLowering::IntrinsicInfo Info;
4685   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4686   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4687                                                DAG.getMachineFunction(),
4688                                                Intrinsic);
4689 
4690   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4691   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4692       Info.opc == ISD::INTRINSIC_W_CHAIN)
4693     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4694                                         TLI.getPointerTy(DAG.getDataLayout())));
4695 
4696   // Add all operands of the call to the operand list.
4697   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4698     const Value *Arg = I.getArgOperand(i);
4699     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4700       Ops.push_back(getValue(Arg));
4701       continue;
4702     }
4703 
4704     // Use TargetConstant instead of a regular constant for immarg.
4705     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4706     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4707       assert(CI->getBitWidth() <= 64 &&
4708              "large intrinsic immediates not handled");
4709       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4710     } else {
4711       Ops.push_back(
4712           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4713     }
4714   }
4715 
4716   SmallVector<EVT, 4> ValueVTs;
4717   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4718 
4719   if (HasChain)
4720     ValueVTs.push_back(MVT::Other);
4721 
4722   SDVTList VTs = DAG.getVTList(ValueVTs);
4723 
4724   // Create the node.
4725   SDValue Result;
4726   if (IsTgtIntrinsic) {
4727     // This is target intrinsic that touches memory
4728     AAMDNodes AAInfo;
4729     I.getAAMetadata(AAInfo);
4730     Result =
4731         DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4732                                 MachinePointerInfo(Info.ptrVal, Info.offset),
4733                                 Info.align, Info.flags, Info.size, AAInfo);
4734   } else if (!HasChain) {
4735     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4736   } else if (!I.getType()->isVoidTy()) {
4737     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4738   } else {
4739     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4740   }
4741 
4742   if (HasChain) {
4743     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4744     if (OnlyLoad)
4745       PendingLoads.push_back(Chain);
4746     else
4747       DAG.setRoot(Chain);
4748   }
4749 
4750   if (!I.getType()->isVoidTy()) {
4751     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4752       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4753       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4754     } else
4755       Result = lowerRangeToAssertZExt(DAG, I, Result);
4756 
4757     MaybeAlign Alignment = I.getRetAlign();
4758     if (!Alignment)
4759       Alignment = F->getAttributes().getRetAlignment();
4760     // Insert `assertalign` node if there's an alignment.
4761     if (InsertAssertAlign && Alignment) {
4762       Result =
4763           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
4764     }
4765 
4766     setValue(&I, Result);
4767   }
4768 }
4769 
4770 /// GetSignificand - Get the significand and build it into a floating-point
4771 /// number with exponent of 1:
4772 ///
4773 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4774 ///
4775 /// where Op is the hexadecimal representation of floating point value.
4776 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4777   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4778                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4779   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4780                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4781   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4782 }
4783 
4784 /// GetExponent - Get the exponent:
4785 ///
4786 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4787 ///
4788 /// where Op is the hexadecimal representation of floating point value.
4789 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4790                            const TargetLowering &TLI, const SDLoc &dl) {
4791   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4792                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4793   SDValue t1 = DAG.getNode(
4794       ISD::SRL, dl, MVT::i32, t0,
4795       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4796   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4797                            DAG.getConstant(127, dl, MVT::i32));
4798   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4799 }
4800 
4801 /// getF32Constant - Get 32-bit floating point constant.
4802 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4803                               const SDLoc &dl) {
4804   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4805                            MVT::f32);
4806 }
4807 
4808 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4809                                        SelectionDAG &DAG) {
4810   // TODO: What fast-math-flags should be set on the floating-point nodes?
4811 
4812   //   IntegerPartOfX = ((int32_t)(t0);
4813   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4814 
4815   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4816   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4817   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4818 
4819   //   IntegerPartOfX <<= 23;
4820   IntegerPartOfX = DAG.getNode(
4821       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4822       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4823                                   DAG.getDataLayout())));
4824 
4825   SDValue TwoToFractionalPartOfX;
4826   if (LimitFloatPrecision <= 6) {
4827     // For floating-point precision of 6:
4828     //
4829     //   TwoToFractionalPartOfX =
4830     //     0.997535578f +
4831     //       (0.735607626f + 0.252464424f * x) * x;
4832     //
4833     // error 0.0144103317, which is 6 bits
4834     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4835                              getF32Constant(DAG, 0x3e814304, dl));
4836     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4837                              getF32Constant(DAG, 0x3f3c50c8, dl));
4838     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4839     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4840                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4841   } else if (LimitFloatPrecision <= 12) {
4842     // For floating-point precision of 12:
4843     //
4844     //   TwoToFractionalPartOfX =
4845     //     0.999892986f +
4846     //       (0.696457318f +
4847     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4848     //
4849     // error 0.000107046256, which is 13 to 14 bits
4850     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4851                              getF32Constant(DAG, 0x3da235e3, dl));
4852     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4853                              getF32Constant(DAG, 0x3e65b8f3, dl));
4854     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4855     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4856                              getF32Constant(DAG, 0x3f324b07, dl));
4857     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4858     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4859                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4860   } else { // LimitFloatPrecision <= 18
4861     // For floating-point precision of 18:
4862     //
4863     //   TwoToFractionalPartOfX =
4864     //     0.999999982f +
4865     //       (0.693148872f +
4866     //         (0.240227044f +
4867     //           (0.554906021e-1f +
4868     //             (0.961591928e-2f +
4869     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4870     // error 2.47208000*10^(-7), which is better than 18 bits
4871     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4872                              getF32Constant(DAG, 0x3924b03e, dl));
4873     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4874                              getF32Constant(DAG, 0x3ab24b87, dl));
4875     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4876     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4877                              getF32Constant(DAG, 0x3c1d8c17, dl));
4878     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4879     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4880                              getF32Constant(DAG, 0x3d634a1d, dl));
4881     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4882     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4883                              getF32Constant(DAG, 0x3e75fe14, dl));
4884     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4885     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4886                               getF32Constant(DAG, 0x3f317234, dl));
4887     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4888     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4889                                          getF32Constant(DAG, 0x3f800000, dl));
4890   }
4891 
4892   // Add the exponent into the result in integer domain.
4893   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4894   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4895                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4896 }
4897 
4898 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4899 /// limited-precision mode.
4900 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4901                          const TargetLowering &TLI, SDNodeFlags Flags) {
4902   if (Op.getValueType() == MVT::f32 &&
4903       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4904 
4905     // Put the exponent in the right bit position for later addition to the
4906     // final result:
4907     //
4908     // t0 = Op * log2(e)
4909 
4910     // TODO: What fast-math-flags should be set here?
4911     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4912                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
4913     return getLimitedPrecisionExp2(t0, dl, DAG);
4914   }
4915 
4916   // No special expansion.
4917   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
4918 }
4919 
4920 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4921 /// limited-precision mode.
4922 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4923                          const TargetLowering &TLI, SDNodeFlags Flags) {
4924   // TODO: What fast-math-flags should be set on the floating-point nodes?
4925 
4926   if (Op.getValueType() == MVT::f32 &&
4927       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4928     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4929 
4930     // Scale the exponent by log(2).
4931     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4932     SDValue LogOfExponent =
4933         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4934                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
4935 
4936     // Get the significand and build it into a floating-point number with
4937     // exponent of 1.
4938     SDValue X = GetSignificand(DAG, Op1, dl);
4939 
4940     SDValue LogOfMantissa;
4941     if (LimitFloatPrecision <= 6) {
4942       // For floating-point precision of 6:
4943       //
4944       //   LogofMantissa =
4945       //     -1.1609546f +
4946       //       (1.4034025f - 0.23903021f * x) * x;
4947       //
4948       // error 0.0034276066, which is better than 8 bits
4949       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4950                                getF32Constant(DAG, 0xbe74c456, dl));
4951       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4952                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4953       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4954       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4955                                   getF32Constant(DAG, 0x3f949a29, dl));
4956     } else if (LimitFloatPrecision <= 12) {
4957       // For floating-point precision of 12:
4958       //
4959       //   LogOfMantissa =
4960       //     -1.7417939f +
4961       //       (2.8212026f +
4962       //         (-1.4699568f +
4963       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4964       //
4965       // error 0.000061011436, which is 14 bits
4966       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4967                                getF32Constant(DAG, 0xbd67b6d6, dl));
4968       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4969                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4970       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4971       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4972                                getF32Constant(DAG, 0x3fbc278b, dl));
4973       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4974       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4975                                getF32Constant(DAG, 0x40348e95, dl));
4976       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4977       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4978                                   getF32Constant(DAG, 0x3fdef31a, dl));
4979     } else { // LimitFloatPrecision <= 18
4980       // For floating-point precision of 18:
4981       //
4982       //   LogOfMantissa =
4983       //     -2.1072184f +
4984       //       (4.2372794f +
4985       //         (-3.7029485f +
4986       //           (2.2781945f +
4987       //             (-0.87823314f +
4988       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4989       //
4990       // error 0.0000023660568, which is better than 18 bits
4991       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4992                                getF32Constant(DAG, 0xbc91e5ac, dl));
4993       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4994                                getF32Constant(DAG, 0x3e4350aa, dl));
4995       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4996       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4997                                getF32Constant(DAG, 0x3f60d3e3, dl));
4998       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4999       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5000                                getF32Constant(DAG, 0x4011cdf0, dl));
5001       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5002       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5003                                getF32Constant(DAG, 0x406cfd1c, dl));
5004       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5005       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5006                                getF32Constant(DAG, 0x408797cb, dl));
5007       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5008       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5009                                   getF32Constant(DAG, 0x4006dcab, dl));
5010     }
5011 
5012     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5013   }
5014 
5015   // No special expansion.
5016   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5017 }
5018 
5019 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5020 /// limited-precision mode.
5021 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5022                           const TargetLowering &TLI, SDNodeFlags Flags) {
5023   // TODO: What fast-math-flags should be set on the floating-point nodes?
5024 
5025   if (Op.getValueType() == MVT::f32 &&
5026       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5027     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5028 
5029     // Get the exponent.
5030     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5031 
5032     // Get the significand and build it into a floating-point number with
5033     // exponent of 1.
5034     SDValue X = GetSignificand(DAG, Op1, dl);
5035 
5036     // Different possible minimax approximations of significand in
5037     // floating-point for various degrees of accuracy over [1,2].
5038     SDValue Log2ofMantissa;
5039     if (LimitFloatPrecision <= 6) {
5040       // For floating-point precision of 6:
5041       //
5042       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5043       //
5044       // error 0.0049451742, which is more than 7 bits
5045       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5046                                getF32Constant(DAG, 0xbeb08fe0, dl));
5047       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5048                                getF32Constant(DAG, 0x40019463, dl));
5049       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5050       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5051                                    getF32Constant(DAG, 0x3fd6633d, dl));
5052     } else if (LimitFloatPrecision <= 12) {
5053       // For floating-point precision of 12:
5054       //
5055       //   Log2ofMantissa =
5056       //     -2.51285454f +
5057       //       (4.07009056f +
5058       //         (-2.12067489f +
5059       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5060       //
5061       // error 0.0000876136000, which is better than 13 bits
5062       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5063                                getF32Constant(DAG, 0xbda7262e, dl));
5064       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5065                                getF32Constant(DAG, 0x3f25280b, dl));
5066       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5067       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5068                                getF32Constant(DAG, 0x4007b923, dl));
5069       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5070       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5071                                getF32Constant(DAG, 0x40823e2f, dl));
5072       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5073       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5074                                    getF32Constant(DAG, 0x4020d29c, dl));
5075     } else { // LimitFloatPrecision <= 18
5076       // For floating-point precision of 18:
5077       //
5078       //   Log2ofMantissa =
5079       //     -3.0400495f +
5080       //       (6.1129976f +
5081       //         (-5.3420409f +
5082       //           (3.2865683f +
5083       //             (-1.2669343f +
5084       //               (0.27515199f -
5085       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5086       //
5087       // error 0.0000018516, which is better than 18 bits
5088       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5089                                getF32Constant(DAG, 0xbcd2769e, dl));
5090       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5091                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5092       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5093       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5094                                getF32Constant(DAG, 0x3fa22ae7, dl));
5095       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5096       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5097                                getF32Constant(DAG, 0x40525723, dl));
5098       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5099       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5100                                getF32Constant(DAG, 0x40aaf200, dl));
5101       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5102       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5103                                getF32Constant(DAG, 0x40c39dad, dl));
5104       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5105       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5106                                    getF32Constant(DAG, 0x4042902c, dl));
5107     }
5108 
5109     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5110   }
5111 
5112   // No special expansion.
5113   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5114 }
5115 
5116 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5117 /// limited-precision mode.
5118 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5119                            const TargetLowering &TLI, SDNodeFlags Flags) {
5120   // TODO: What fast-math-flags should be set on the floating-point nodes?
5121 
5122   if (Op.getValueType() == MVT::f32 &&
5123       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5124     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5125 
5126     // Scale the exponent by log10(2) [0.30102999f].
5127     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5128     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5129                                         getF32Constant(DAG, 0x3e9a209a, dl));
5130 
5131     // Get the significand and build it into a floating-point number with
5132     // exponent of 1.
5133     SDValue X = GetSignificand(DAG, Op1, dl);
5134 
5135     SDValue Log10ofMantissa;
5136     if (LimitFloatPrecision <= 6) {
5137       // For floating-point precision of 6:
5138       //
5139       //   Log10ofMantissa =
5140       //     -0.50419619f +
5141       //       (0.60948995f - 0.10380950f * x) * x;
5142       //
5143       // error 0.0014886165, which is 6 bits
5144       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5145                                getF32Constant(DAG, 0xbdd49a13, dl));
5146       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5147                                getF32Constant(DAG, 0x3f1c0789, dl));
5148       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5149       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5150                                     getF32Constant(DAG, 0x3f011300, dl));
5151     } else if (LimitFloatPrecision <= 12) {
5152       // For floating-point precision of 12:
5153       //
5154       //   Log10ofMantissa =
5155       //     -0.64831180f +
5156       //       (0.91751397f +
5157       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5158       //
5159       // error 0.00019228036, which is better than 12 bits
5160       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5161                                getF32Constant(DAG, 0x3d431f31, dl));
5162       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5163                                getF32Constant(DAG, 0x3ea21fb2, dl));
5164       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5165       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5166                                getF32Constant(DAG, 0x3f6ae232, dl));
5167       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5168       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5169                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5170     } else { // LimitFloatPrecision <= 18
5171       // For floating-point precision of 18:
5172       //
5173       //   Log10ofMantissa =
5174       //     -0.84299375f +
5175       //       (1.5327582f +
5176       //         (-1.0688956f +
5177       //           (0.49102474f +
5178       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5179       //
5180       // error 0.0000037995730, which is better than 18 bits
5181       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5182                                getF32Constant(DAG, 0x3c5d51ce, dl));
5183       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5184                                getF32Constant(DAG, 0x3e00685a, dl));
5185       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5186       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5187                                getF32Constant(DAG, 0x3efb6798, dl));
5188       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5189       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5190                                getF32Constant(DAG, 0x3f88d192, dl));
5191       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5192       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5193                                getF32Constant(DAG, 0x3fc4316c, dl));
5194       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5195       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5196                                     getF32Constant(DAG, 0x3f57ce70, dl));
5197     }
5198 
5199     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5200   }
5201 
5202   // No special expansion.
5203   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5204 }
5205 
5206 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5207 /// limited-precision mode.
5208 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5209                           const TargetLowering &TLI, SDNodeFlags Flags) {
5210   if (Op.getValueType() == MVT::f32 &&
5211       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5212     return getLimitedPrecisionExp2(Op, dl, DAG);
5213 
5214   // No special expansion.
5215   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5216 }
5217 
5218 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5219 /// limited-precision mode with x == 10.0f.
5220 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5221                          SelectionDAG &DAG, const TargetLowering &TLI,
5222                          SDNodeFlags Flags) {
5223   bool IsExp10 = false;
5224   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5225       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5226     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5227       APFloat Ten(10.0f);
5228       IsExp10 = LHSC->isExactlyValue(Ten);
5229     }
5230   }
5231 
5232   // TODO: What fast-math-flags should be set on the FMUL node?
5233   if (IsExp10) {
5234     // Put the exponent in the right bit position for later addition to the
5235     // final result:
5236     //
5237     //   #define LOG2OF10 3.3219281f
5238     //   t0 = Op * LOG2OF10;
5239     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5240                              getF32Constant(DAG, 0x40549a78, dl));
5241     return getLimitedPrecisionExp2(t0, dl, DAG);
5242   }
5243 
5244   // No special expansion.
5245   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5246 }
5247 
5248 /// ExpandPowI - Expand a llvm.powi intrinsic.
5249 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5250                           SelectionDAG &DAG) {
5251   // If RHS is a constant, we can expand this out to a multiplication tree,
5252   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5253   // optimizing for size, we only want to do this if the expansion would produce
5254   // a small number of multiplies, otherwise we do the full expansion.
5255   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5256     // Get the exponent as a positive value.
5257     unsigned Val = RHSC->getSExtValue();
5258     if ((int)Val < 0) Val = -Val;
5259 
5260     // powi(x, 0) -> 1.0
5261     if (Val == 0)
5262       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5263 
5264     bool OptForSize = DAG.shouldOptForSize();
5265     if (!OptForSize ||
5266         // If optimizing for size, don't insert too many multiplies.
5267         // This inserts up to 5 multiplies.
5268         countPopulation(Val) + Log2_32(Val) < 7) {
5269       // We use the simple binary decomposition method to generate the multiply
5270       // sequence.  There are more optimal ways to do this (for example,
5271       // powi(x,15) generates one more multiply than it should), but this has
5272       // the benefit of being both really simple and much better than a libcall.
5273       SDValue Res;  // Logically starts equal to 1.0
5274       SDValue CurSquare = LHS;
5275       // TODO: Intrinsics should have fast-math-flags that propagate to these
5276       // nodes.
5277       while (Val) {
5278         if (Val & 1) {
5279           if (Res.getNode())
5280             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5281           else
5282             Res = CurSquare;  // 1.0*CurSquare.
5283         }
5284 
5285         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5286                                 CurSquare, CurSquare);
5287         Val >>= 1;
5288       }
5289 
5290       // If the original was negative, invert the result, producing 1/(x*x*x).
5291       if (RHSC->getSExtValue() < 0)
5292         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5293                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5294       return Res;
5295     }
5296   }
5297 
5298   // Otherwise, expand to a libcall.
5299   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5300 }
5301 
5302 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5303                             SDValue LHS, SDValue RHS, SDValue Scale,
5304                             SelectionDAG &DAG, const TargetLowering &TLI) {
5305   EVT VT = LHS.getValueType();
5306   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5307   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5308   LLVMContext &Ctx = *DAG.getContext();
5309 
5310   // If the type is legal but the operation isn't, this node might survive all
5311   // the way to operation legalization. If we end up there and we do not have
5312   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5313   // node.
5314 
5315   // Coax the legalizer into expanding the node during type legalization instead
5316   // by bumping the size by one bit. This will force it to Promote, enabling the
5317   // early expansion and avoiding the need to expand later.
5318 
5319   // We don't have to do this if Scale is 0; that can always be expanded, unless
5320   // it's a saturating signed operation. Those can experience true integer
5321   // division overflow, a case which we must avoid.
5322 
5323   // FIXME: We wouldn't have to do this (or any of the early
5324   // expansion/promotion) if it was possible to expand a libcall of an
5325   // illegal type during operation legalization. But it's not, so things
5326   // get a bit hacky.
5327   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5328   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5329       (TLI.isTypeLegal(VT) ||
5330        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5331     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5332         Opcode, VT, ScaleInt);
5333     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5334       EVT PromVT;
5335       if (VT.isScalarInteger())
5336         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5337       else if (VT.isVector()) {
5338         PromVT = VT.getVectorElementType();
5339         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5340         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5341       } else
5342         llvm_unreachable("Wrong VT for DIVFIX?");
5343       if (Signed) {
5344         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5345         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5346       } else {
5347         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5348         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5349       }
5350       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5351       // For saturating operations, we need to shift up the LHS to get the
5352       // proper saturation width, and then shift down again afterwards.
5353       if (Saturating)
5354         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5355                           DAG.getConstant(1, DL, ShiftTy));
5356       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5357       if (Saturating)
5358         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5359                           DAG.getConstant(1, DL, ShiftTy));
5360       return DAG.getZExtOrTrunc(Res, DL, VT);
5361     }
5362   }
5363 
5364   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5365 }
5366 
5367 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5368 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5369 static void
5370 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5371                      const SDValue &N) {
5372   switch (N.getOpcode()) {
5373   case ISD::CopyFromReg: {
5374     SDValue Op = N.getOperand(1);
5375     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5376                       Op.getValueType().getSizeInBits());
5377     return;
5378   }
5379   case ISD::BITCAST:
5380   case ISD::AssertZext:
5381   case ISD::AssertSext:
5382   case ISD::TRUNCATE:
5383     getUnderlyingArgRegs(Regs, N.getOperand(0));
5384     return;
5385   case ISD::BUILD_PAIR:
5386   case ISD::BUILD_VECTOR:
5387   case ISD::CONCAT_VECTORS:
5388     for (SDValue Op : N->op_values())
5389       getUnderlyingArgRegs(Regs, Op);
5390     return;
5391   default:
5392     return;
5393   }
5394 }
5395 
5396 /// If the DbgValueInst is a dbg_value of a function argument, create the
5397 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5398 /// instruction selection, they will be inserted to the entry BB.
5399 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5400     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5401     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5402   const Argument *Arg = dyn_cast<Argument>(V);
5403   if (!Arg)
5404     return false;
5405 
5406   if (!IsDbgDeclare) {
5407     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5408     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5409     // the entry block.
5410     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5411     if (!IsInEntryBlock)
5412       return false;
5413 
5414     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5415     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5416     // variable that also is a param.
5417     //
5418     // Although, if we are at the top of the entry block already, we can still
5419     // emit using ArgDbgValue. This might catch some situations when the
5420     // dbg.value refers to an argument that isn't used in the entry block, so
5421     // any CopyToReg node would be optimized out and the only way to express
5422     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5423     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5424     // we should only emit as ArgDbgValue if the Variable is an argument to the
5425     // current function, and the dbg.value intrinsic is found in the entry
5426     // block.
5427     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5428         !DL->getInlinedAt();
5429     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5430     if (!IsInPrologue && !VariableIsFunctionInputArg)
5431       return false;
5432 
5433     // Here we assume that a function argument on IR level only can be used to
5434     // describe one input parameter on source level. If we for example have
5435     // source code like this
5436     //
5437     //    struct A { long x, y; };
5438     //    void foo(struct A a, long b) {
5439     //      ...
5440     //      b = a.x;
5441     //      ...
5442     //    }
5443     //
5444     // and IR like this
5445     //
5446     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5447     //  entry:
5448     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5449     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5450     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5451     //    ...
5452     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5453     //    ...
5454     //
5455     // then the last dbg.value is describing a parameter "b" using a value that
5456     // is an argument. But since we already has used %a1 to describe a parameter
5457     // we should not handle that last dbg.value here (that would result in an
5458     // incorrect hoisting of the DBG_VALUE to the function entry).
5459     // Notice that we allow one dbg.value per IR level argument, to accommodate
5460     // for the situation with fragments above.
5461     if (VariableIsFunctionInputArg) {
5462       unsigned ArgNo = Arg->getArgNo();
5463       if (ArgNo >= FuncInfo.DescribedArgs.size())
5464         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5465       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5466         return false;
5467       FuncInfo.DescribedArgs.set(ArgNo);
5468     }
5469   }
5470 
5471   MachineFunction &MF = DAG.getMachineFunction();
5472   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5473 
5474   bool IsIndirect = false;
5475   Optional<MachineOperand> Op;
5476   // Some arguments' frame index is recorded during argument lowering.
5477   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5478   if (FI != std::numeric_limits<int>::max())
5479     Op = MachineOperand::CreateFI(FI);
5480 
5481   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
5482   if (!Op && N.getNode()) {
5483     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5484     Register Reg;
5485     if (ArgRegsAndSizes.size() == 1)
5486       Reg = ArgRegsAndSizes.front().first;
5487 
5488     if (Reg && Reg.isVirtual()) {
5489       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5490       Register PR = RegInfo.getLiveInPhysReg(Reg);
5491       if (PR)
5492         Reg = PR;
5493     }
5494     if (Reg) {
5495       Op = MachineOperand::CreateReg(Reg, false);
5496       IsIndirect = IsDbgDeclare;
5497     }
5498   }
5499 
5500   if (!Op && N.getNode()) {
5501     // Check if frame index is available.
5502     SDValue LCandidate = peekThroughBitcasts(N);
5503     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5504       if (FrameIndexSDNode *FINode =
5505           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5506         Op = MachineOperand::CreateFI(FINode->getIndex());
5507   }
5508 
5509   if (!Op) {
5510     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5511     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
5512                                          SplitRegs) {
5513       unsigned Offset = 0;
5514       for (auto RegAndSize : SplitRegs) {
5515         // If the expression is already a fragment, the current register
5516         // offset+size might extend beyond the fragment. In this case, only
5517         // the register bits that are inside the fragment are relevant.
5518         int RegFragmentSizeInBits = RegAndSize.second;
5519         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5520           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5521           // The register is entirely outside the expression fragment,
5522           // so is irrelevant for debug info.
5523           if (Offset >= ExprFragmentSizeInBits)
5524             break;
5525           // The register is partially outside the expression fragment, only
5526           // the low bits within the fragment are relevant for debug info.
5527           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5528             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5529           }
5530         }
5531 
5532         auto FragmentExpr = DIExpression::createFragmentExpression(
5533             Expr, Offset, RegFragmentSizeInBits);
5534         Offset += RegAndSize.second;
5535         // If a valid fragment expression cannot be created, the variable's
5536         // correct value cannot be determined and so it is set as Undef.
5537         if (!FragmentExpr) {
5538           SDDbgValue *SDV = DAG.getConstantDbgValue(
5539               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5540           DAG.AddDbgValue(SDV, nullptr, false);
5541           continue;
5542         }
5543         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5544         FuncInfo.ArgDbgValues.push_back(
5545           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5546                   RegAndSize.first, Variable, *FragmentExpr));
5547       }
5548     };
5549 
5550     // Check if ValueMap has reg number.
5551     DenseMap<const Value *, Register>::const_iterator
5552       VMI = FuncInfo.ValueMap.find(V);
5553     if (VMI != FuncInfo.ValueMap.end()) {
5554       const auto &TLI = DAG.getTargetLoweringInfo();
5555       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5556                        V->getType(), None);
5557       if (RFV.occupiesMultipleRegs()) {
5558         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5559         return true;
5560       }
5561 
5562       Op = MachineOperand::CreateReg(VMI->second, false);
5563       IsIndirect = IsDbgDeclare;
5564     } else if (ArgRegsAndSizes.size() > 1) {
5565       // This was split due to the calling convention, and no virtual register
5566       // mapping exists for the value.
5567       splitMultiRegDbgValue(ArgRegsAndSizes);
5568       return true;
5569     }
5570   }
5571 
5572   if (!Op)
5573     return false;
5574 
5575   assert(Variable->isValidLocationForIntrinsic(DL) &&
5576          "Expected inlined-at fields to agree");
5577   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5578   FuncInfo.ArgDbgValues.push_back(
5579       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5580               *Op, Variable, Expr));
5581 
5582   return true;
5583 }
5584 
5585 /// Return the appropriate SDDbgValue based on N.
5586 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5587                                              DILocalVariable *Variable,
5588                                              DIExpression *Expr,
5589                                              const DebugLoc &dl,
5590                                              unsigned DbgSDNodeOrder) {
5591   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5592     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5593     // stack slot locations.
5594     //
5595     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5596     // debug values here after optimization:
5597     //
5598     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5599     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5600     //
5601     // Both describe the direct values of their associated variables.
5602     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5603                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5604   }
5605   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5606                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5607 }
5608 
5609 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5610   switch (Intrinsic) {
5611   case Intrinsic::smul_fix:
5612     return ISD::SMULFIX;
5613   case Intrinsic::umul_fix:
5614     return ISD::UMULFIX;
5615   case Intrinsic::smul_fix_sat:
5616     return ISD::SMULFIXSAT;
5617   case Intrinsic::umul_fix_sat:
5618     return ISD::UMULFIXSAT;
5619   case Intrinsic::sdiv_fix:
5620     return ISD::SDIVFIX;
5621   case Intrinsic::udiv_fix:
5622     return ISD::UDIVFIX;
5623   case Intrinsic::sdiv_fix_sat:
5624     return ISD::SDIVFIXSAT;
5625   case Intrinsic::udiv_fix_sat:
5626     return ISD::UDIVFIXSAT;
5627   default:
5628     llvm_unreachable("Unhandled fixed point intrinsic");
5629   }
5630 }
5631 
5632 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5633                                            const char *FunctionName) {
5634   assert(FunctionName && "FunctionName must not be nullptr");
5635   SDValue Callee = DAG.getExternalSymbol(
5636       FunctionName,
5637       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5638   LowerCallTo(I, Callee, I.isTailCall());
5639 }
5640 
5641 /// Given a @llvm.call.preallocated.setup, return the corresponding
5642 /// preallocated call.
5643 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
5644   assert(cast<CallBase>(PreallocatedSetup)
5645                  ->getCalledFunction()
5646                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
5647          "expected call_preallocated_setup Value");
5648   for (auto *U : PreallocatedSetup->users()) {
5649     auto *UseCall = cast<CallBase>(U);
5650     const Function *Fn = UseCall->getCalledFunction();
5651     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
5652       return UseCall;
5653     }
5654   }
5655   llvm_unreachable("expected corresponding call to preallocated setup/arg");
5656 }
5657 
5658 /// Lower the call to the specified intrinsic function.
5659 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5660                                              unsigned Intrinsic) {
5661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5662   SDLoc sdl = getCurSDLoc();
5663   DebugLoc dl = getCurDebugLoc();
5664   SDValue Res;
5665 
5666   SDNodeFlags Flags;
5667   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
5668     Flags.copyFMF(*FPOp);
5669 
5670   switch (Intrinsic) {
5671   default:
5672     // By default, turn this into a target intrinsic node.
5673     visitTargetIntrinsic(I, Intrinsic);
5674     return;
5675   case Intrinsic::vscale: {
5676     match(&I, m_VScale(DAG.getDataLayout()));
5677     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5678     setValue(&I,
5679              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5680     return;
5681   }
5682   case Intrinsic::vastart:  visitVAStart(I); return;
5683   case Intrinsic::vaend:    visitVAEnd(I); return;
5684   case Intrinsic::vacopy:   visitVACopy(I); return;
5685   case Intrinsic::returnaddress:
5686     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5687                              TLI.getPointerTy(DAG.getDataLayout()),
5688                              getValue(I.getArgOperand(0))));
5689     return;
5690   case Intrinsic::addressofreturnaddress:
5691     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5692                              TLI.getPointerTy(DAG.getDataLayout())));
5693     return;
5694   case Intrinsic::sponentry:
5695     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5696                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5697     return;
5698   case Intrinsic::frameaddress:
5699     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5700                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5701                              getValue(I.getArgOperand(0))));
5702     return;
5703   case Intrinsic::read_volatile_register:
5704   case Intrinsic::read_register: {
5705     Value *Reg = I.getArgOperand(0);
5706     SDValue Chain = getRoot();
5707     SDValue RegName =
5708         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5709     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5710     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5711       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5712     setValue(&I, Res);
5713     DAG.setRoot(Res.getValue(1));
5714     return;
5715   }
5716   case Intrinsic::write_register: {
5717     Value *Reg = I.getArgOperand(0);
5718     Value *RegValue = I.getArgOperand(1);
5719     SDValue Chain = getRoot();
5720     SDValue RegName =
5721         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5722     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5723                             RegName, getValue(RegValue)));
5724     return;
5725   }
5726   case Intrinsic::memcpy: {
5727     const auto &MCI = cast<MemCpyInst>(I);
5728     SDValue Op1 = getValue(I.getArgOperand(0));
5729     SDValue Op2 = getValue(I.getArgOperand(1));
5730     SDValue Op3 = getValue(I.getArgOperand(2));
5731     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5732     Align DstAlign = MCI.getDestAlign().valueOrOne();
5733     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5734     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5735     bool isVol = MCI.isVolatile();
5736     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5737     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5738     // node.
5739     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5740     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5741                                /* AlwaysInline */ false, isTC,
5742                                MachinePointerInfo(I.getArgOperand(0)),
5743                                MachinePointerInfo(I.getArgOperand(1)));
5744     updateDAGForMaybeTailCall(MC);
5745     return;
5746   }
5747   case Intrinsic::memcpy_inline: {
5748     const auto &MCI = cast<MemCpyInlineInst>(I);
5749     SDValue Dst = getValue(I.getArgOperand(0));
5750     SDValue Src = getValue(I.getArgOperand(1));
5751     SDValue Size = getValue(I.getArgOperand(2));
5752     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5753     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5754     Align DstAlign = MCI.getDestAlign().valueOrOne();
5755     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5756     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5757     bool isVol = MCI.isVolatile();
5758     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5759     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5760     // node.
5761     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5762                                /* AlwaysInline */ true, isTC,
5763                                MachinePointerInfo(I.getArgOperand(0)),
5764                                MachinePointerInfo(I.getArgOperand(1)));
5765     updateDAGForMaybeTailCall(MC);
5766     return;
5767   }
5768   case Intrinsic::memset: {
5769     const auto &MSI = cast<MemSetInst>(I);
5770     SDValue Op1 = getValue(I.getArgOperand(0));
5771     SDValue Op2 = getValue(I.getArgOperand(1));
5772     SDValue Op3 = getValue(I.getArgOperand(2));
5773     // @llvm.memset defines 0 and 1 to both mean no alignment.
5774     Align Alignment = MSI.getDestAlign().valueOrOne();
5775     bool isVol = MSI.isVolatile();
5776     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5777     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5778     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5779                                MachinePointerInfo(I.getArgOperand(0)));
5780     updateDAGForMaybeTailCall(MS);
5781     return;
5782   }
5783   case Intrinsic::memmove: {
5784     const auto &MMI = cast<MemMoveInst>(I);
5785     SDValue Op1 = getValue(I.getArgOperand(0));
5786     SDValue Op2 = getValue(I.getArgOperand(1));
5787     SDValue Op3 = getValue(I.getArgOperand(2));
5788     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5789     Align DstAlign = MMI.getDestAlign().valueOrOne();
5790     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5791     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5792     bool isVol = MMI.isVolatile();
5793     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5794     // FIXME: Support passing different dest/src alignments to the memmove DAG
5795     // node.
5796     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5797     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5798                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5799                                 MachinePointerInfo(I.getArgOperand(1)));
5800     updateDAGForMaybeTailCall(MM);
5801     return;
5802   }
5803   case Intrinsic::memcpy_element_unordered_atomic: {
5804     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5805     SDValue Dst = getValue(MI.getRawDest());
5806     SDValue Src = getValue(MI.getRawSource());
5807     SDValue Length = getValue(MI.getLength());
5808 
5809     unsigned DstAlign = MI.getDestAlignment();
5810     unsigned SrcAlign = MI.getSourceAlignment();
5811     Type *LengthTy = MI.getLength()->getType();
5812     unsigned ElemSz = MI.getElementSizeInBytes();
5813     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5814     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5815                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5816                                      MachinePointerInfo(MI.getRawDest()),
5817                                      MachinePointerInfo(MI.getRawSource()));
5818     updateDAGForMaybeTailCall(MC);
5819     return;
5820   }
5821   case Intrinsic::memmove_element_unordered_atomic: {
5822     auto &MI = cast<AtomicMemMoveInst>(I);
5823     SDValue Dst = getValue(MI.getRawDest());
5824     SDValue Src = getValue(MI.getRawSource());
5825     SDValue Length = getValue(MI.getLength());
5826 
5827     unsigned DstAlign = MI.getDestAlignment();
5828     unsigned SrcAlign = MI.getSourceAlignment();
5829     Type *LengthTy = MI.getLength()->getType();
5830     unsigned ElemSz = MI.getElementSizeInBytes();
5831     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5832     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5833                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5834                                       MachinePointerInfo(MI.getRawDest()),
5835                                       MachinePointerInfo(MI.getRawSource()));
5836     updateDAGForMaybeTailCall(MC);
5837     return;
5838   }
5839   case Intrinsic::memset_element_unordered_atomic: {
5840     auto &MI = cast<AtomicMemSetInst>(I);
5841     SDValue Dst = getValue(MI.getRawDest());
5842     SDValue Val = getValue(MI.getValue());
5843     SDValue Length = getValue(MI.getLength());
5844 
5845     unsigned DstAlign = MI.getDestAlignment();
5846     Type *LengthTy = MI.getLength()->getType();
5847     unsigned ElemSz = MI.getElementSizeInBytes();
5848     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
5849     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5850                                      LengthTy, ElemSz, isTC,
5851                                      MachinePointerInfo(MI.getRawDest()));
5852     updateDAGForMaybeTailCall(MC);
5853     return;
5854   }
5855   case Intrinsic::call_preallocated_setup: {
5856     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
5857     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5858     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
5859                               getRoot(), SrcValue);
5860     setValue(&I, Res);
5861     DAG.setRoot(Res);
5862     return;
5863   }
5864   case Intrinsic::call_preallocated_arg: {
5865     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
5866     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
5867     SDValue Ops[3];
5868     Ops[0] = getRoot();
5869     Ops[1] = SrcValue;
5870     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
5871                                    MVT::i32); // arg index
5872     SDValue Res = DAG.getNode(
5873         ISD::PREALLOCATED_ARG, sdl,
5874         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
5875     setValue(&I, Res);
5876     DAG.setRoot(Res.getValue(1));
5877     return;
5878   }
5879   case Intrinsic::dbg_addr:
5880   case Intrinsic::dbg_declare: {
5881     const auto &DI = cast<DbgVariableIntrinsic>(I);
5882     DILocalVariable *Variable = DI.getVariable();
5883     DIExpression *Expression = DI.getExpression();
5884     dropDanglingDebugInfo(Variable, Expression);
5885     assert(Variable && "Missing variable");
5886     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5887                       << "\n");
5888     // Check if address has undef value.
5889     const Value *Address = DI.getVariableLocation();
5890     if (!Address || isa<UndefValue>(Address) ||
5891         (Address->use_empty() && !isa<Argument>(Address))) {
5892       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5893                         << " (bad/undef/unused-arg address)\n");
5894       return;
5895     }
5896 
5897     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5898 
5899     // Check if this variable can be described by a frame index, typically
5900     // either as a static alloca or a byval parameter.
5901     int FI = std::numeric_limits<int>::max();
5902     if (const auto *AI =
5903             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5904       if (AI->isStaticAlloca()) {
5905         auto I = FuncInfo.StaticAllocaMap.find(AI);
5906         if (I != FuncInfo.StaticAllocaMap.end())
5907           FI = I->second;
5908       }
5909     } else if (const auto *Arg = dyn_cast<Argument>(
5910                    Address->stripInBoundsConstantOffsets())) {
5911       FI = FuncInfo.getArgumentFrameIndex(Arg);
5912     }
5913 
5914     // llvm.dbg.addr is control dependent and always generates indirect
5915     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5916     // the MachineFunction variable table.
5917     if (FI != std::numeric_limits<int>::max()) {
5918       if (Intrinsic == Intrinsic::dbg_addr) {
5919         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5920             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5921         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5922       } else {
5923         LLVM_DEBUG(dbgs() << "Skipping " << DI
5924                           << " (variable info stashed in MF side table)\n");
5925       }
5926       return;
5927     }
5928 
5929     SDValue &N = NodeMap[Address];
5930     if (!N.getNode() && isa<Argument>(Address))
5931       // Check unused arguments map.
5932       N = UnusedArgNodeMap[Address];
5933     SDDbgValue *SDV;
5934     if (N.getNode()) {
5935       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5936         Address = BCI->getOperand(0);
5937       // Parameters are handled specially.
5938       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5939       if (isParameter && FINode) {
5940         // Byval parameter. We have a frame index at this point.
5941         SDV =
5942             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5943                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5944       } else if (isa<Argument>(Address)) {
5945         // Address is an argument, so try to emit its dbg value using
5946         // virtual register info from the FuncInfo.ValueMap.
5947         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5948         return;
5949       } else {
5950         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5951                               true, dl, SDNodeOrder);
5952       }
5953       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5954     } else {
5955       // If Address is an argument then try to emit its dbg value using
5956       // virtual register info from the FuncInfo.ValueMap.
5957       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5958                                     N)) {
5959         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5960                           << " (could not emit func-arg dbg_value)\n");
5961       }
5962     }
5963     return;
5964   }
5965   case Intrinsic::dbg_label: {
5966     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5967     DILabel *Label = DI.getLabel();
5968     assert(Label && "Missing label");
5969 
5970     SDDbgLabel *SDV;
5971     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5972     DAG.AddDbgLabel(SDV);
5973     return;
5974   }
5975   case Intrinsic::dbg_value: {
5976     const DbgValueInst &DI = cast<DbgValueInst>(I);
5977     assert(DI.getVariable() && "Missing variable");
5978 
5979     DILocalVariable *Variable = DI.getVariable();
5980     DIExpression *Expression = DI.getExpression();
5981     dropDanglingDebugInfo(Variable, Expression);
5982     const Value *V = DI.getValue();
5983     if (!V)
5984       return;
5985 
5986     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5987         SDNodeOrder))
5988       return;
5989 
5990     // TODO: Dangling debug info will eventually either be resolved or produce
5991     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5992     // between the original dbg.value location and its resolved DBG_VALUE, which
5993     // we should ideally fill with an extra Undef DBG_VALUE.
5994 
5995     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5996     return;
5997   }
5998 
5999   case Intrinsic::eh_typeid_for: {
6000     // Find the type id for the given typeinfo.
6001     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6002     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6003     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6004     setValue(&I, Res);
6005     return;
6006   }
6007 
6008   case Intrinsic::eh_return_i32:
6009   case Intrinsic::eh_return_i64:
6010     DAG.getMachineFunction().setCallsEHReturn(true);
6011     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6012                             MVT::Other,
6013                             getControlRoot(),
6014                             getValue(I.getArgOperand(0)),
6015                             getValue(I.getArgOperand(1))));
6016     return;
6017   case Intrinsic::eh_unwind_init:
6018     DAG.getMachineFunction().setCallsUnwindInit(true);
6019     return;
6020   case Intrinsic::eh_dwarf_cfa:
6021     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6022                              TLI.getPointerTy(DAG.getDataLayout()),
6023                              getValue(I.getArgOperand(0))));
6024     return;
6025   case Intrinsic::eh_sjlj_callsite: {
6026     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6027     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6028     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6029     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6030 
6031     MMI.setCurrentCallSite(CI->getZExtValue());
6032     return;
6033   }
6034   case Intrinsic::eh_sjlj_functioncontext: {
6035     // Get and store the index of the function context.
6036     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6037     AllocaInst *FnCtx =
6038       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6039     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6040     MFI.setFunctionContextIndex(FI);
6041     return;
6042   }
6043   case Intrinsic::eh_sjlj_setjmp: {
6044     SDValue Ops[2];
6045     Ops[0] = getRoot();
6046     Ops[1] = getValue(I.getArgOperand(0));
6047     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6048                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6049     setValue(&I, Op.getValue(0));
6050     DAG.setRoot(Op.getValue(1));
6051     return;
6052   }
6053   case Intrinsic::eh_sjlj_longjmp:
6054     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6055                             getRoot(), getValue(I.getArgOperand(0))));
6056     return;
6057   case Intrinsic::eh_sjlj_setup_dispatch:
6058     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6059                             getRoot()));
6060     return;
6061   case Intrinsic::masked_gather:
6062     visitMaskedGather(I);
6063     return;
6064   case Intrinsic::masked_load:
6065     visitMaskedLoad(I);
6066     return;
6067   case Intrinsic::masked_scatter:
6068     visitMaskedScatter(I);
6069     return;
6070   case Intrinsic::masked_store:
6071     visitMaskedStore(I);
6072     return;
6073   case Intrinsic::masked_expandload:
6074     visitMaskedLoad(I, true /* IsExpanding */);
6075     return;
6076   case Intrinsic::masked_compressstore:
6077     visitMaskedStore(I, true /* IsCompressing */);
6078     return;
6079   case Intrinsic::powi:
6080     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6081                             getValue(I.getArgOperand(1)), DAG));
6082     return;
6083   case Intrinsic::log:
6084     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6085     return;
6086   case Intrinsic::log2:
6087     setValue(&I,
6088              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6089     return;
6090   case Intrinsic::log10:
6091     setValue(&I,
6092              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6093     return;
6094   case Intrinsic::exp:
6095     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6096     return;
6097   case Intrinsic::exp2:
6098     setValue(&I,
6099              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6100     return;
6101   case Intrinsic::pow:
6102     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6103                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6104     return;
6105   case Intrinsic::sqrt:
6106   case Intrinsic::fabs:
6107   case Intrinsic::sin:
6108   case Intrinsic::cos:
6109   case Intrinsic::floor:
6110   case Intrinsic::ceil:
6111   case Intrinsic::trunc:
6112   case Intrinsic::rint:
6113   case Intrinsic::nearbyint:
6114   case Intrinsic::round:
6115   case Intrinsic::roundeven:
6116   case Intrinsic::canonicalize: {
6117     unsigned Opcode;
6118     switch (Intrinsic) {
6119     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6120     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6121     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6122     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6123     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6124     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6125     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6126     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6127     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6128     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6129     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6130     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6131     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6132     }
6133 
6134     setValue(&I, DAG.getNode(Opcode, sdl,
6135                              getValue(I.getArgOperand(0)).getValueType(),
6136                              getValue(I.getArgOperand(0)), Flags));
6137     return;
6138   }
6139   case Intrinsic::lround:
6140   case Intrinsic::llround:
6141   case Intrinsic::lrint:
6142   case Intrinsic::llrint: {
6143     unsigned Opcode;
6144     switch (Intrinsic) {
6145     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6146     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6147     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6148     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6149     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6150     }
6151 
6152     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6153     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6154                              getValue(I.getArgOperand(0))));
6155     return;
6156   }
6157   case Intrinsic::minnum:
6158     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6159                              getValue(I.getArgOperand(0)).getValueType(),
6160                              getValue(I.getArgOperand(0)),
6161                              getValue(I.getArgOperand(1)), Flags));
6162     return;
6163   case Intrinsic::maxnum:
6164     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6165                              getValue(I.getArgOperand(0)).getValueType(),
6166                              getValue(I.getArgOperand(0)),
6167                              getValue(I.getArgOperand(1)), Flags));
6168     return;
6169   case Intrinsic::minimum:
6170     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6171                              getValue(I.getArgOperand(0)).getValueType(),
6172                              getValue(I.getArgOperand(0)),
6173                              getValue(I.getArgOperand(1)), Flags));
6174     return;
6175   case Intrinsic::maximum:
6176     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6177                              getValue(I.getArgOperand(0)).getValueType(),
6178                              getValue(I.getArgOperand(0)),
6179                              getValue(I.getArgOperand(1)), Flags));
6180     return;
6181   case Intrinsic::copysign:
6182     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6183                              getValue(I.getArgOperand(0)).getValueType(),
6184                              getValue(I.getArgOperand(0)),
6185                              getValue(I.getArgOperand(1)), Flags));
6186     return;
6187   case Intrinsic::fma:
6188     setValue(&I, DAG.getNode(
6189                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6190                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6191                      getValue(I.getArgOperand(2)), Flags));
6192     return;
6193 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6194   case Intrinsic::INTRINSIC:
6195 #include "llvm/IR/ConstrainedOps.def"
6196     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6197     return;
6198 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6199 #include "llvm/IR/VPIntrinsics.def"
6200     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6201     return;
6202   case Intrinsic::fmuladd: {
6203     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6204     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6205         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6206       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6207                                getValue(I.getArgOperand(0)).getValueType(),
6208                                getValue(I.getArgOperand(0)),
6209                                getValue(I.getArgOperand(1)),
6210                                getValue(I.getArgOperand(2)), Flags));
6211     } else {
6212       // TODO: Intrinsic calls should have fast-math-flags.
6213       SDValue Mul = DAG.getNode(
6214           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6215           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6216       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6217                                 getValue(I.getArgOperand(0)).getValueType(),
6218                                 Mul, getValue(I.getArgOperand(2)), Flags);
6219       setValue(&I, Add);
6220     }
6221     return;
6222   }
6223   case Intrinsic::convert_to_fp16:
6224     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6225                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6226                                          getValue(I.getArgOperand(0)),
6227                                          DAG.getTargetConstant(0, sdl,
6228                                                                MVT::i32))));
6229     return;
6230   case Intrinsic::convert_from_fp16:
6231     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6232                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6233                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6234                                          getValue(I.getArgOperand(0)))));
6235     return;
6236   case Intrinsic::fptosi_sat: {
6237     EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
6238     SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
6239     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, Type,
6240                              getValue(I.getArgOperand(0)), SatW));
6241     return;
6242   }
6243   case Intrinsic::fptoui_sat: {
6244     EVT Type = TLI.getValueType(DAG.getDataLayout(), I.getType());
6245     SDValue SatW = DAG.getConstant(Type.getScalarSizeInBits(), sdl, MVT::i32);
6246     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, Type,
6247                              getValue(I.getArgOperand(0)), SatW));
6248     return;
6249   }
6250   case Intrinsic::set_rounding:
6251     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6252                       {getRoot(), getValue(I.getArgOperand(0))});
6253     setValue(&I, Res);
6254     DAG.setRoot(Res.getValue(0));
6255     return;
6256   case Intrinsic::pcmarker: {
6257     SDValue Tmp = getValue(I.getArgOperand(0));
6258     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6259     return;
6260   }
6261   case Intrinsic::readcyclecounter: {
6262     SDValue Op = getRoot();
6263     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6264                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6265     setValue(&I, Res);
6266     DAG.setRoot(Res.getValue(1));
6267     return;
6268   }
6269   case Intrinsic::bitreverse:
6270     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6271                              getValue(I.getArgOperand(0)).getValueType(),
6272                              getValue(I.getArgOperand(0))));
6273     return;
6274   case Intrinsic::bswap:
6275     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6276                              getValue(I.getArgOperand(0)).getValueType(),
6277                              getValue(I.getArgOperand(0))));
6278     return;
6279   case Intrinsic::cttz: {
6280     SDValue Arg = getValue(I.getArgOperand(0));
6281     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6282     EVT Ty = Arg.getValueType();
6283     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6284                              sdl, Ty, Arg));
6285     return;
6286   }
6287   case Intrinsic::ctlz: {
6288     SDValue Arg = getValue(I.getArgOperand(0));
6289     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6290     EVT Ty = Arg.getValueType();
6291     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6292                              sdl, Ty, Arg));
6293     return;
6294   }
6295   case Intrinsic::ctpop: {
6296     SDValue Arg = getValue(I.getArgOperand(0));
6297     EVT Ty = Arg.getValueType();
6298     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6299     return;
6300   }
6301   case Intrinsic::fshl:
6302   case Intrinsic::fshr: {
6303     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6304     SDValue X = getValue(I.getArgOperand(0));
6305     SDValue Y = getValue(I.getArgOperand(1));
6306     SDValue Z = getValue(I.getArgOperand(2));
6307     EVT VT = X.getValueType();
6308 
6309     if (X == Y) {
6310       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6311       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6312     } else {
6313       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6314       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6315     }
6316     return;
6317   }
6318   case Intrinsic::sadd_sat: {
6319     SDValue Op1 = getValue(I.getArgOperand(0));
6320     SDValue Op2 = getValue(I.getArgOperand(1));
6321     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6322     return;
6323   }
6324   case Intrinsic::uadd_sat: {
6325     SDValue Op1 = getValue(I.getArgOperand(0));
6326     SDValue Op2 = getValue(I.getArgOperand(1));
6327     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6328     return;
6329   }
6330   case Intrinsic::ssub_sat: {
6331     SDValue Op1 = getValue(I.getArgOperand(0));
6332     SDValue Op2 = getValue(I.getArgOperand(1));
6333     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6334     return;
6335   }
6336   case Intrinsic::usub_sat: {
6337     SDValue Op1 = getValue(I.getArgOperand(0));
6338     SDValue Op2 = getValue(I.getArgOperand(1));
6339     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6340     return;
6341   }
6342   case Intrinsic::sshl_sat: {
6343     SDValue Op1 = getValue(I.getArgOperand(0));
6344     SDValue Op2 = getValue(I.getArgOperand(1));
6345     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6346     return;
6347   }
6348   case Intrinsic::ushl_sat: {
6349     SDValue Op1 = getValue(I.getArgOperand(0));
6350     SDValue Op2 = getValue(I.getArgOperand(1));
6351     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
6352     return;
6353   }
6354   case Intrinsic::smul_fix:
6355   case Intrinsic::umul_fix:
6356   case Intrinsic::smul_fix_sat:
6357   case Intrinsic::umul_fix_sat: {
6358     SDValue Op1 = getValue(I.getArgOperand(0));
6359     SDValue Op2 = getValue(I.getArgOperand(1));
6360     SDValue Op3 = getValue(I.getArgOperand(2));
6361     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6362                              Op1.getValueType(), Op1, Op2, Op3));
6363     return;
6364   }
6365   case Intrinsic::sdiv_fix:
6366   case Intrinsic::udiv_fix:
6367   case Intrinsic::sdiv_fix_sat:
6368   case Intrinsic::udiv_fix_sat: {
6369     SDValue Op1 = getValue(I.getArgOperand(0));
6370     SDValue Op2 = getValue(I.getArgOperand(1));
6371     SDValue Op3 = getValue(I.getArgOperand(2));
6372     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6373                               Op1, Op2, Op3, DAG, TLI));
6374     return;
6375   }
6376   case Intrinsic::smax: {
6377     SDValue Op1 = getValue(I.getArgOperand(0));
6378     SDValue Op2 = getValue(I.getArgOperand(1));
6379     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
6380     return;
6381   }
6382   case Intrinsic::smin: {
6383     SDValue Op1 = getValue(I.getArgOperand(0));
6384     SDValue Op2 = getValue(I.getArgOperand(1));
6385     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
6386     return;
6387   }
6388   case Intrinsic::umax: {
6389     SDValue Op1 = getValue(I.getArgOperand(0));
6390     SDValue Op2 = getValue(I.getArgOperand(1));
6391     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
6392     return;
6393   }
6394   case Intrinsic::umin: {
6395     SDValue Op1 = getValue(I.getArgOperand(0));
6396     SDValue Op2 = getValue(I.getArgOperand(1));
6397     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
6398     return;
6399   }
6400   case Intrinsic::abs: {
6401     // TODO: Preserve "int min is poison" arg in SDAG?
6402     SDValue Op1 = getValue(I.getArgOperand(0));
6403     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
6404     return;
6405   }
6406   case Intrinsic::stacksave: {
6407     SDValue Op = getRoot();
6408     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6409     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
6410     setValue(&I, Res);
6411     DAG.setRoot(Res.getValue(1));
6412     return;
6413   }
6414   case Intrinsic::stackrestore:
6415     Res = getValue(I.getArgOperand(0));
6416     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6417     return;
6418   case Intrinsic::get_dynamic_area_offset: {
6419     SDValue Op = getRoot();
6420     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6421     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6422     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6423     // target.
6424     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
6425       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6426                          " intrinsic!");
6427     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6428                       Op);
6429     DAG.setRoot(Op);
6430     setValue(&I, Res);
6431     return;
6432   }
6433   case Intrinsic::stackguard: {
6434     MachineFunction &MF = DAG.getMachineFunction();
6435     const Module &M = *MF.getFunction().getParent();
6436     SDValue Chain = getRoot();
6437     if (TLI.useLoadStackGuardNode()) {
6438       Res = getLoadStackGuard(DAG, sdl, Chain);
6439     } else {
6440       EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6441       const Value *Global = TLI.getSDagStackGuard(M);
6442       Align Align = DL->getPrefTypeAlign(Global->getType());
6443       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6444                         MachinePointerInfo(Global, 0), Align,
6445                         MachineMemOperand::MOVolatile);
6446     }
6447     if (TLI.useStackGuardXorFP())
6448       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6449     DAG.setRoot(Chain);
6450     setValue(&I, Res);
6451     return;
6452   }
6453   case Intrinsic::stackprotector: {
6454     // Emit code into the DAG to store the stack guard onto the stack.
6455     MachineFunction &MF = DAG.getMachineFunction();
6456     MachineFrameInfo &MFI = MF.getFrameInfo();
6457     SDValue Src, Chain = getRoot();
6458 
6459     if (TLI.useLoadStackGuardNode())
6460       Src = getLoadStackGuard(DAG, sdl, Chain);
6461     else
6462       Src = getValue(I.getArgOperand(0));   // The guard's value.
6463 
6464     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6465 
6466     int FI = FuncInfo.StaticAllocaMap[Slot];
6467     MFI.setStackProtectorIndex(FI);
6468     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
6469 
6470     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6471 
6472     // Store the stack protector onto the stack.
6473     Res = DAG.getStore(
6474         Chain, sdl, Src, FIN,
6475         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
6476         MaybeAlign(), MachineMemOperand::MOVolatile);
6477     setValue(&I, Res);
6478     DAG.setRoot(Res);
6479     return;
6480   }
6481   case Intrinsic::objectsize:
6482     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6483 
6484   case Intrinsic::is_constant:
6485     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6486 
6487   case Intrinsic::annotation:
6488   case Intrinsic::ptr_annotation:
6489   case Intrinsic::launder_invariant_group:
6490   case Intrinsic::strip_invariant_group:
6491     // Drop the intrinsic, but forward the value
6492     setValue(&I, getValue(I.getOperand(0)));
6493     return;
6494 
6495   case Intrinsic::assume:
6496   case Intrinsic::experimental_noalias_scope_decl:
6497   case Intrinsic::var_annotation:
6498   case Intrinsic::sideeffect:
6499     // Discard annotate attributes, noalias scope declarations, assumptions, and
6500     // artificial side-effects.
6501     return;
6502 
6503   case Intrinsic::codeview_annotation: {
6504     // Emit a label associated with this metadata.
6505     MachineFunction &MF = DAG.getMachineFunction();
6506     MCSymbol *Label =
6507         MF.getMMI().getContext().createTempSymbol("annotation", true);
6508     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6509     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6510     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6511     DAG.setRoot(Res);
6512     return;
6513   }
6514 
6515   case Intrinsic::init_trampoline: {
6516     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6517 
6518     SDValue Ops[6];
6519     Ops[0] = getRoot();
6520     Ops[1] = getValue(I.getArgOperand(0));
6521     Ops[2] = getValue(I.getArgOperand(1));
6522     Ops[3] = getValue(I.getArgOperand(2));
6523     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6524     Ops[5] = DAG.getSrcValue(F);
6525 
6526     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6527 
6528     DAG.setRoot(Res);
6529     return;
6530   }
6531   case Intrinsic::adjust_trampoline:
6532     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6533                              TLI.getPointerTy(DAG.getDataLayout()),
6534                              getValue(I.getArgOperand(0))));
6535     return;
6536   case Intrinsic::gcroot: {
6537     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6538            "only valid in functions with gc specified, enforced by Verifier");
6539     assert(GFI && "implied by previous");
6540     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6541     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6542 
6543     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6544     GFI->addStackRoot(FI->getIndex(), TypeMap);
6545     return;
6546   }
6547   case Intrinsic::gcread:
6548   case Intrinsic::gcwrite:
6549     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6550   case Intrinsic::flt_rounds:
6551     Res = DAG.getNode(ISD::FLT_ROUNDS_, sdl, {MVT::i32, MVT::Other}, getRoot());
6552     setValue(&I, Res);
6553     DAG.setRoot(Res.getValue(1));
6554     return;
6555 
6556   case Intrinsic::expect:
6557     // Just replace __builtin_expect(exp, c) with EXP.
6558     setValue(&I, getValue(I.getArgOperand(0)));
6559     return;
6560 
6561   case Intrinsic::ubsantrap:
6562   case Intrinsic::debugtrap:
6563   case Intrinsic::trap: {
6564     StringRef TrapFuncName =
6565         I.getAttributes()
6566             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6567             .getValueAsString();
6568     if (TrapFuncName.empty()) {
6569       switch (Intrinsic) {
6570       case Intrinsic::trap:
6571         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
6572         break;
6573       case Intrinsic::debugtrap:
6574         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
6575         break;
6576       case Intrinsic::ubsantrap:
6577         DAG.setRoot(DAG.getNode(
6578             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
6579             DAG.getTargetConstant(
6580                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
6581                 MVT::i32)));
6582         break;
6583       default: llvm_unreachable("unknown trap intrinsic");
6584       }
6585       return;
6586     }
6587     TargetLowering::ArgListTy Args;
6588     if (Intrinsic == Intrinsic::ubsantrap) {
6589       Args.push_back(TargetLoweringBase::ArgListEntry());
6590       Args[0].Val = I.getArgOperand(0);
6591       Args[0].Node = getValue(Args[0].Val);
6592       Args[0].Ty = Args[0].Val->getType();
6593     }
6594 
6595     TargetLowering::CallLoweringInfo CLI(DAG);
6596     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6597         CallingConv::C, I.getType(),
6598         DAG.getExternalSymbol(TrapFuncName.data(),
6599                               TLI.getPointerTy(DAG.getDataLayout())),
6600         std::move(Args));
6601 
6602     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6603     DAG.setRoot(Result.second);
6604     return;
6605   }
6606 
6607   case Intrinsic::uadd_with_overflow:
6608   case Intrinsic::sadd_with_overflow:
6609   case Intrinsic::usub_with_overflow:
6610   case Intrinsic::ssub_with_overflow:
6611   case Intrinsic::umul_with_overflow:
6612   case Intrinsic::smul_with_overflow: {
6613     ISD::NodeType Op;
6614     switch (Intrinsic) {
6615     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6616     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6617     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6618     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6619     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6620     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6621     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6622     }
6623     SDValue Op1 = getValue(I.getArgOperand(0));
6624     SDValue Op2 = getValue(I.getArgOperand(1));
6625 
6626     EVT ResultVT = Op1.getValueType();
6627     EVT OverflowVT = MVT::i1;
6628     if (ResultVT.isVector())
6629       OverflowVT = EVT::getVectorVT(
6630           *Context, OverflowVT, ResultVT.getVectorElementCount());
6631 
6632     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6633     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6634     return;
6635   }
6636   case Intrinsic::prefetch: {
6637     SDValue Ops[5];
6638     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6639     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6640     Ops[0] = DAG.getRoot();
6641     Ops[1] = getValue(I.getArgOperand(0));
6642     Ops[2] = getValue(I.getArgOperand(1));
6643     Ops[3] = getValue(I.getArgOperand(2));
6644     Ops[4] = getValue(I.getArgOperand(3));
6645     SDValue Result = DAG.getMemIntrinsicNode(
6646         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
6647         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
6648         /* align */ None, Flags);
6649 
6650     // Chain the prefetch in parallell with any pending loads, to stay out of
6651     // the way of later optimizations.
6652     PendingLoads.push_back(Result);
6653     Result = getRoot();
6654     DAG.setRoot(Result);
6655     return;
6656   }
6657   case Intrinsic::lifetime_start:
6658   case Intrinsic::lifetime_end: {
6659     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6660     // Stack coloring is not enabled in O0, discard region information.
6661     if (TM.getOptLevel() == CodeGenOpt::None)
6662       return;
6663 
6664     const int64_t ObjectSize =
6665         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6666     Value *const ObjectPtr = I.getArgOperand(1);
6667     SmallVector<const Value *, 4> Allocas;
6668     getUnderlyingObjects(ObjectPtr, Allocas);
6669 
6670     for (const Value *Alloca : Allocas) {
6671       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
6672 
6673       // Could not find an Alloca.
6674       if (!LifetimeObject)
6675         continue;
6676 
6677       // First check that the Alloca is static, otherwise it won't have a
6678       // valid frame index.
6679       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6680       if (SI == FuncInfo.StaticAllocaMap.end())
6681         return;
6682 
6683       const int FrameIndex = SI->second;
6684       int64_t Offset;
6685       if (GetPointerBaseWithConstantOffset(
6686               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6687         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6688       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6689                                 Offset);
6690       DAG.setRoot(Res);
6691     }
6692     return;
6693   }
6694   case Intrinsic::pseudoprobe: {
6695     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
6696     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6697     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
6698     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
6699     DAG.setRoot(Res);
6700     return;
6701   }
6702   case Intrinsic::invariant_start:
6703     // Discard region information.
6704     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6705     return;
6706   case Intrinsic::invariant_end:
6707     // Discard region information.
6708     return;
6709   case Intrinsic::clear_cache:
6710     /// FunctionName may be null.
6711     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6712       lowerCallToExternalSymbol(I, FunctionName);
6713     return;
6714   case Intrinsic::donothing:
6715     // ignore
6716     return;
6717   case Intrinsic::experimental_stackmap:
6718     visitStackmap(I);
6719     return;
6720   case Intrinsic::experimental_patchpoint_void:
6721   case Intrinsic::experimental_patchpoint_i64:
6722     visitPatchpoint(I);
6723     return;
6724   case Intrinsic::experimental_gc_statepoint:
6725     LowerStatepoint(cast<GCStatepointInst>(I));
6726     return;
6727   case Intrinsic::experimental_gc_result:
6728     visitGCResult(cast<GCResultInst>(I));
6729     return;
6730   case Intrinsic::experimental_gc_relocate:
6731     visitGCRelocate(cast<GCRelocateInst>(I));
6732     return;
6733   case Intrinsic::instrprof_increment:
6734     llvm_unreachable("instrprof failed to lower an increment");
6735   case Intrinsic::instrprof_value_profile:
6736     llvm_unreachable("instrprof failed to lower a value profiling call");
6737   case Intrinsic::localescape: {
6738     MachineFunction &MF = DAG.getMachineFunction();
6739     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6740 
6741     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6742     // is the same on all targets.
6743     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6744       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6745       if (isa<ConstantPointerNull>(Arg))
6746         continue; // Skip null pointers. They represent a hole in index space.
6747       AllocaInst *Slot = cast<AllocaInst>(Arg);
6748       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6749              "can only escape static allocas");
6750       int FI = FuncInfo.StaticAllocaMap[Slot];
6751       MCSymbol *FrameAllocSym =
6752           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6753               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6754       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6755               TII->get(TargetOpcode::LOCAL_ESCAPE))
6756           .addSym(FrameAllocSym)
6757           .addFrameIndex(FI);
6758     }
6759 
6760     return;
6761   }
6762 
6763   case Intrinsic::localrecover: {
6764     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6765     MachineFunction &MF = DAG.getMachineFunction();
6766 
6767     // Get the symbol that defines the frame offset.
6768     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6769     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6770     unsigned IdxVal =
6771         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6772     MCSymbol *FrameAllocSym =
6773         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6774             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6775 
6776     Value *FP = I.getArgOperand(1);
6777     SDValue FPVal = getValue(FP);
6778     EVT PtrVT = FPVal.getValueType();
6779 
6780     // Create a MCSymbol for the label to avoid any target lowering
6781     // that would make this PC relative.
6782     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6783     SDValue OffsetVal =
6784         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6785 
6786     // Add the offset to the FP.
6787     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6788     setValue(&I, Add);
6789 
6790     return;
6791   }
6792 
6793   case Intrinsic::eh_exceptionpointer:
6794   case Intrinsic::eh_exceptioncode: {
6795     // Get the exception pointer vreg, copy from it, and resize it to fit.
6796     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6797     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6798     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6799     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6800     SDValue N =
6801         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6802     if (Intrinsic == Intrinsic::eh_exceptioncode)
6803       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6804     setValue(&I, N);
6805     return;
6806   }
6807   case Intrinsic::xray_customevent: {
6808     // Here we want to make sure that the intrinsic behaves as if it has a
6809     // specific calling convention, and only for x86_64.
6810     // FIXME: Support other platforms later.
6811     const auto &Triple = DAG.getTarget().getTargetTriple();
6812     if (Triple.getArch() != Triple::x86_64)
6813       return;
6814 
6815     SDLoc DL = getCurSDLoc();
6816     SmallVector<SDValue, 8> Ops;
6817 
6818     // We want to say that we always want the arguments in registers.
6819     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6820     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6821     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6822     SDValue Chain = getRoot();
6823     Ops.push_back(LogEntryVal);
6824     Ops.push_back(StrSizeVal);
6825     Ops.push_back(Chain);
6826 
6827     // We need to enforce the calling convention for the callsite, so that
6828     // argument ordering is enforced correctly, and that register allocation can
6829     // see that some registers may be assumed clobbered and have to preserve
6830     // them across calls to the intrinsic.
6831     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6832                                            DL, NodeTys, Ops);
6833     SDValue patchableNode = SDValue(MN, 0);
6834     DAG.setRoot(patchableNode);
6835     setValue(&I, patchableNode);
6836     return;
6837   }
6838   case Intrinsic::xray_typedevent: {
6839     // Here we want to make sure that the intrinsic behaves as if it has a
6840     // specific calling convention, and only for x86_64.
6841     // FIXME: Support other platforms later.
6842     const auto &Triple = DAG.getTarget().getTargetTriple();
6843     if (Triple.getArch() != Triple::x86_64)
6844       return;
6845 
6846     SDLoc DL = getCurSDLoc();
6847     SmallVector<SDValue, 8> Ops;
6848 
6849     // We want to say that we always want the arguments in registers.
6850     // It's unclear to me how manipulating the selection DAG here forces callers
6851     // to provide arguments in registers instead of on the stack.
6852     SDValue LogTypeId = getValue(I.getArgOperand(0));
6853     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6854     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6855     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6856     SDValue Chain = getRoot();
6857     Ops.push_back(LogTypeId);
6858     Ops.push_back(LogEntryVal);
6859     Ops.push_back(StrSizeVal);
6860     Ops.push_back(Chain);
6861 
6862     // We need to enforce the calling convention for the callsite, so that
6863     // argument ordering is enforced correctly, and that register allocation can
6864     // see that some registers may be assumed clobbered and have to preserve
6865     // them across calls to the intrinsic.
6866     MachineSDNode *MN = DAG.getMachineNode(
6867         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6868     SDValue patchableNode = SDValue(MN, 0);
6869     DAG.setRoot(patchableNode);
6870     setValue(&I, patchableNode);
6871     return;
6872   }
6873   case Intrinsic::experimental_deoptimize:
6874     LowerDeoptimizeCall(&I);
6875     return;
6876 
6877   case Intrinsic::vector_reduce_fadd:
6878   case Intrinsic::vector_reduce_fmul:
6879   case Intrinsic::vector_reduce_add:
6880   case Intrinsic::vector_reduce_mul:
6881   case Intrinsic::vector_reduce_and:
6882   case Intrinsic::vector_reduce_or:
6883   case Intrinsic::vector_reduce_xor:
6884   case Intrinsic::vector_reduce_smax:
6885   case Intrinsic::vector_reduce_smin:
6886   case Intrinsic::vector_reduce_umax:
6887   case Intrinsic::vector_reduce_umin:
6888   case Intrinsic::vector_reduce_fmax:
6889   case Intrinsic::vector_reduce_fmin:
6890     visitVectorReduce(I, Intrinsic);
6891     return;
6892 
6893   case Intrinsic::icall_branch_funnel: {
6894     SmallVector<SDValue, 16> Ops;
6895     Ops.push_back(getValue(I.getArgOperand(0)));
6896 
6897     int64_t Offset;
6898     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6899         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6900     if (!Base)
6901       report_fatal_error(
6902           "llvm.icall.branch.funnel operand must be a GlobalValue");
6903     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6904 
6905     struct BranchFunnelTarget {
6906       int64_t Offset;
6907       SDValue Target;
6908     };
6909     SmallVector<BranchFunnelTarget, 8> Targets;
6910 
6911     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6912       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6913           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6914       if (ElemBase != Base)
6915         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6916                            "to the same GlobalValue");
6917 
6918       SDValue Val = getValue(I.getArgOperand(Op + 1));
6919       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6920       if (!GA)
6921         report_fatal_error(
6922             "llvm.icall.branch.funnel operand must be a GlobalValue");
6923       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6924                                      GA->getGlobal(), getCurSDLoc(),
6925                                      Val.getValueType(), GA->getOffset())});
6926     }
6927     llvm::sort(Targets,
6928                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6929                  return T1.Offset < T2.Offset;
6930                });
6931 
6932     for (auto &T : Targets) {
6933       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6934       Ops.push_back(T.Target);
6935     }
6936 
6937     Ops.push_back(DAG.getRoot()); // Chain
6938     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6939                                  getCurSDLoc(), MVT::Other, Ops),
6940               0);
6941     DAG.setRoot(N);
6942     setValue(&I, N);
6943     HasTailCall = true;
6944     return;
6945   }
6946 
6947   case Intrinsic::wasm_landingpad_index:
6948     // Information this intrinsic contained has been transferred to
6949     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6950     // delete it now.
6951     return;
6952 
6953   case Intrinsic::aarch64_settag:
6954   case Intrinsic::aarch64_settag_zero: {
6955     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6956     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6957     SDValue Val = TSI.EmitTargetCodeForSetTag(
6958         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6959         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6960         ZeroMemory);
6961     DAG.setRoot(Val);
6962     setValue(&I, Val);
6963     return;
6964   }
6965   case Intrinsic::ptrmask: {
6966     SDValue Ptr = getValue(I.getOperand(0));
6967     SDValue Const = getValue(I.getOperand(1));
6968 
6969     EVT PtrVT = Ptr.getValueType();
6970     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), PtrVT, Ptr,
6971                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), PtrVT)));
6972     return;
6973   }
6974   case Intrinsic::get_active_lane_mask: {
6975     auto DL = getCurSDLoc();
6976     SDValue Index = getValue(I.getOperand(0));
6977     SDValue TripCount = getValue(I.getOperand(1));
6978     Type *ElementTy = I.getOperand(0)->getType();
6979     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6980     unsigned VecWidth = VT.getVectorNumElements();
6981 
6982     SmallVector<SDValue, 16> OpsTripCount;
6983     SmallVector<SDValue, 16> OpsIndex;
6984     SmallVector<SDValue, 16> OpsStepConstants;
6985     for (unsigned i = 0; i < VecWidth; i++) {
6986       OpsTripCount.push_back(TripCount);
6987       OpsIndex.push_back(Index);
6988       OpsStepConstants.push_back(
6989           DAG.getConstant(i, DL, EVT::getEVT(ElementTy)));
6990     }
6991 
6992     EVT CCVT = EVT::getVectorVT(I.getContext(), MVT::i1, VecWidth);
6993 
6994     auto VecTy = EVT::getEVT(FixedVectorType::get(ElementTy, VecWidth));
6995     SDValue VectorIndex = DAG.getBuildVector(VecTy, DL, OpsIndex);
6996     SDValue VectorStep = DAG.getBuildVector(VecTy, DL, OpsStepConstants);
6997     SDValue VectorInduction = DAG.getNode(
6998        ISD::UADDO, DL, DAG.getVTList(VecTy, CCVT), VectorIndex, VectorStep);
6999     SDValue VectorTripCount = DAG.getBuildVector(VecTy, DL, OpsTripCount);
7000     SDValue SetCC = DAG.getSetCC(DL, CCVT, VectorInduction.getValue(0),
7001                                  VectorTripCount, ISD::CondCode::SETULT);
7002     setValue(&I, DAG.getNode(ISD::AND, DL, CCVT,
7003                              DAG.getNOT(DL, VectorInduction.getValue(1), CCVT),
7004                              SetCC));
7005     return;
7006   }
7007   case Intrinsic::experimental_vector_insert: {
7008     auto DL = getCurSDLoc();
7009 
7010     SDValue Vec = getValue(I.getOperand(0));
7011     SDValue SubVec = getValue(I.getOperand(1));
7012     SDValue Index = getValue(I.getOperand(2));
7013     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7014     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ResultVT, Vec, SubVec,
7015                              Index));
7016     return;
7017   }
7018   case Intrinsic::experimental_vector_extract: {
7019     auto DL = getCurSDLoc();
7020 
7021     SDValue Vec = getValue(I.getOperand(0));
7022     SDValue Index = getValue(I.getOperand(1));
7023     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7024 
7025     setValue(&I, DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResultVT, Vec, Index));
7026     return;
7027   }
7028   case Intrinsic::experimental_vector_reverse:
7029     visitVectorReverse(I);
7030     return;
7031   }
7032 }
7033 
7034 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7035     const ConstrainedFPIntrinsic &FPI) {
7036   SDLoc sdl = getCurSDLoc();
7037 
7038   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7039   SmallVector<EVT, 4> ValueVTs;
7040   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7041   ValueVTs.push_back(MVT::Other); // Out chain
7042 
7043   // We do not need to serialize constrained FP intrinsics against
7044   // each other or against (nonvolatile) loads, so they can be
7045   // chained like loads.
7046   SDValue Chain = DAG.getRoot();
7047   SmallVector<SDValue, 4> Opers;
7048   Opers.push_back(Chain);
7049   if (FPI.isUnaryOp()) {
7050     Opers.push_back(getValue(FPI.getArgOperand(0)));
7051   } else if (FPI.isTernaryOp()) {
7052     Opers.push_back(getValue(FPI.getArgOperand(0)));
7053     Opers.push_back(getValue(FPI.getArgOperand(1)));
7054     Opers.push_back(getValue(FPI.getArgOperand(2)));
7055   } else {
7056     Opers.push_back(getValue(FPI.getArgOperand(0)));
7057     Opers.push_back(getValue(FPI.getArgOperand(1)));
7058   }
7059 
7060   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7061     assert(Result.getNode()->getNumValues() == 2);
7062 
7063     // Push node to the appropriate list so that future instructions can be
7064     // chained up correctly.
7065     SDValue OutChain = Result.getValue(1);
7066     switch (EB) {
7067     case fp::ExceptionBehavior::ebIgnore:
7068       // The only reason why ebIgnore nodes still need to be chained is that
7069       // they might depend on the current rounding mode, and therefore must
7070       // not be moved across instruction that may change that mode.
7071       LLVM_FALLTHROUGH;
7072     case fp::ExceptionBehavior::ebMayTrap:
7073       // These must not be moved across calls or instructions that may change
7074       // floating-point exception masks.
7075       PendingConstrainedFP.push_back(OutChain);
7076       break;
7077     case fp::ExceptionBehavior::ebStrict:
7078       // These must not be moved across calls or instructions that may change
7079       // floating-point exception masks or read floating-point exception flags.
7080       // In addition, they cannot be optimized out even if unused.
7081       PendingConstrainedFPStrict.push_back(OutChain);
7082       break;
7083     }
7084   };
7085 
7086   SDVTList VTs = DAG.getVTList(ValueVTs);
7087   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7088 
7089   SDNodeFlags Flags;
7090   if (EB == fp::ExceptionBehavior::ebIgnore)
7091     Flags.setNoFPExcept(true);
7092 
7093   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7094     Flags.copyFMF(*FPOp);
7095 
7096   unsigned Opcode;
7097   switch (FPI.getIntrinsicID()) {
7098   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7099 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7100   case Intrinsic::INTRINSIC:                                                   \
7101     Opcode = ISD::STRICT_##DAGN;                                               \
7102     break;
7103 #include "llvm/IR/ConstrainedOps.def"
7104   case Intrinsic::experimental_constrained_fmuladd: {
7105     Opcode = ISD::STRICT_FMA;
7106     // Break fmuladd into fmul and fadd.
7107     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7108         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7109                                         ValueVTs[0])) {
7110       Opers.pop_back();
7111       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
7112       pushOutChain(Mul, EB);
7113       Opcode = ISD::STRICT_FADD;
7114       Opers.clear();
7115       Opers.push_back(Mul.getValue(1));
7116       Opers.push_back(Mul.getValue(0));
7117       Opers.push_back(getValue(FPI.getArgOperand(2)));
7118     }
7119     break;
7120   }
7121   }
7122 
7123   // A few strict DAG nodes carry additional operands that are not
7124   // set up by the default code above.
7125   switch (Opcode) {
7126   default: break;
7127   case ISD::STRICT_FP_ROUND:
7128     Opers.push_back(
7129         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7130     break;
7131   case ISD::STRICT_FSETCC:
7132   case ISD::STRICT_FSETCCS: {
7133     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7134     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
7135     if (TM.Options.NoNaNsFPMath)
7136       Condition = getFCmpCodeWithoutNaN(Condition);
7137     Opers.push_back(DAG.getCondCode(Condition));
7138     break;
7139   }
7140   }
7141 
7142   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
7143   pushOutChain(Result, EB);
7144 
7145   SDValue FPResult = Result.getValue(0);
7146   setValue(&FPI, FPResult);
7147 }
7148 
7149 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
7150   Optional<unsigned> ResOPC;
7151   switch (VPIntrin.getIntrinsicID()) {
7152 #define BEGIN_REGISTER_VP_INTRINSIC(INTRIN, ...) case Intrinsic::INTRIN:
7153 #define BEGIN_REGISTER_VP_SDNODE(VPSDID, ...) ResOPC = ISD::VPSDID;
7154 #define END_REGISTER_VP_INTRINSIC(...) break;
7155 #include "llvm/IR/VPIntrinsics.def"
7156   }
7157 
7158   if (!ResOPC.hasValue())
7159     llvm_unreachable(
7160         "Inconsistency: no SDNode available for this VPIntrinsic!");
7161 
7162   return ResOPC.getValue();
7163 }
7164 
7165 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
7166     const VPIntrinsic &VPIntrin) {
7167   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
7168 
7169   SmallVector<EVT, 4> ValueVTs;
7170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7171   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
7172   SDVTList VTs = DAG.getVTList(ValueVTs);
7173 
7174   // Request operands.
7175   SmallVector<SDValue, 7> OpValues;
7176   for (int i = 0; i < (int)VPIntrin.getNumArgOperands(); ++i)
7177     OpValues.push_back(getValue(VPIntrin.getArgOperand(i)));
7178 
7179   SDLoc DL = getCurSDLoc();
7180   SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues);
7181   setValue(&VPIntrin, Result);
7182 }
7183 
7184 std::pair<SDValue, SDValue>
7185 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7186                                     const BasicBlock *EHPadBB) {
7187   MachineFunction &MF = DAG.getMachineFunction();
7188   MachineModuleInfo &MMI = MF.getMMI();
7189   MCSymbol *BeginLabel = nullptr;
7190 
7191   if (EHPadBB) {
7192     // Insert a label before the invoke call to mark the try range.  This can be
7193     // used to detect deletion of the invoke via the MachineModuleInfo.
7194     BeginLabel = MMI.getContext().createTempSymbol();
7195 
7196     // For SjLj, keep track of which landing pads go with which invokes
7197     // so as to maintain the ordering of pads in the LSDA.
7198     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7199     if (CallSiteIndex) {
7200       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7201       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7202 
7203       // Now that the call site is handled, stop tracking it.
7204       MMI.setCurrentCallSite(0);
7205     }
7206 
7207     // Both PendingLoads and PendingExports must be flushed here;
7208     // this call might not return.
7209     (void)getRoot();
7210     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7211 
7212     CLI.setChain(getRoot());
7213   }
7214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7215   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7216 
7217   assert((CLI.IsTailCall || Result.second.getNode()) &&
7218          "Non-null chain expected with non-tail call!");
7219   assert((Result.second.getNode() || !Result.first.getNode()) &&
7220          "Null value expected with tail call!");
7221 
7222   if (!Result.second.getNode()) {
7223     // As a special case, a null chain means that a tail call has been emitted
7224     // and the DAG root is already updated.
7225     HasTailCall = true;
7226 
7227     // Since there's no actual continuation from this block, nothing can be
7228     // relying on us setting vregs for them.
7229     PendingExports.clear();
7230   } else {
7231     DAG.setRoot(Result.second);
7232   }
7233 
7234   if (EHPadBB) {
7235     // Insert a label at the end of the invoke call to mark the try range.  This
7236     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7237     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7238     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7239 
7240     // Inform MachineModuleInfo of range.
7241     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7242     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7243     // actually use outlined funclets and their LSDA info style.
7244     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7245       assert(CLI.CB);
7246       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7247       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CB), BeginLabel, EndLabel);
7248     } else if (!isScopedEHPersonality(Pers)) {
7249       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7250     }
7251   }
7252 
7253   return Result;
7254 }
7255 
7256 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
7257                                       bool isTailCall,
7258                                       const BasicBlock *EHPadBB) {
7259   auto &DL = DAG.getDataLayout();
7260   FunctionType *FTy = CB.getFunctionType();
7261   Type *RetTy = CB.getType();
7262 
7263   TargetLowering::ArgListTy Args;
7264   Args.reserve(CB.arg_size());
7265 
7266   const Value *SwiftErrorVal = nullptr;
7267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7268 
7269   if (isTailCall) {
7270     // Avoid emitting tail calls in functions with the disable-tail-calls
7271     // attribute.
7272     auto *Caller = CB.getParent()->getParent();
7273     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7274         "true")
7275       isTailCall = false;
7276 
7277     // We can't tail call inside a function with a swifterror argument. Lowering
7278     // does not support this yet. It would have to move into the swifterror
7279     // register before the call.
7280     if (TLI.supportSwiftError() &&
7281         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7282       isTailCall = false;
7283   }
7284 
7285   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
7286     TargetLowering::ArgListEntry Entry;
7287     const Value *V = *I;
7288 
7289     // Skip empty types
7290     if (V->getType()->isEmptyTy())
7291       continue;
7292 
7293     SDValue ArgNode = getValue(V);
7294     Entry.Node = ArgNode; Entry.Ty = V->getType();
7295 
7296     Entry.setAttributes(&CB, I - CB.arg_begin());
7297 
7298     // Use swifterror virtual register as input to the call.
7299     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7300       SwiftErrorVal = V;
7301       // We find the virtual register for the actual swifterror argument.
7302       // Instead of using the Value, we use the virtual register instead.
7303       Entry.Node =
7304           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
7305                           EVT(TLI.getPointerTy(DL)));
7306     }
7307 
7308     Args.push_back(Entry);
7309 
7310     // If we have an explicit sret argument that is an Instruction, (i.e., it
7311     // might point to function-local memory), we can't meaningfully tail-call.
7312     if (Entry.IsSRet && isa<Instruction>(V))
7313       isTailCall = false;
7314   }
7315 
7316   // If call site has a cfguardtarget operand bundle, create and add an
7317   // additional ArgListEntry.
7318   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7319     TargetLowering::ArgListEntry Entry;
7320     Value *V = Bundle->Inputs[0];
7321     SDValue ArgNode = getValue(V);
7322     Entry.Node = ArgNode;
7323     Entry.Ty = V->getType();
7324     Entry.IsCFGuardTarget = true;
7325     Args.push_back(Entry);
7326   }
7327 
7328   // Check if target-independent constraints permit a tail call here.
7329   // Target-dependent constraints are checked within TLI->LowerCallTo.
7330   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
7331     isTailCall = false;
7332 
7333   // Disable tail calls if there is an swifterror argument. Targets have not
7334   // been updated to support tail calls.
7335   if (TLI.supportSwiftError() && SwiftErrorVal)
7336     isTailCall = false;
7337 
7338   TargetLowering::CallLoweringInfo CLI(DAG);
7339   CLI.setDebugLoc(getCurSDLoc())
7340       .setChain(getRoot())
7341       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
7342       .setTailCall(isTailCall)
7343       .setConvergent(CB.isConvergent())
7344       .setIsPreallocated(
7345           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
7346   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7347 
7348   if (Result.first.getNode()) {
7349     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
7350     setValue(&CB, Result.first);
7351   }
7352 
7353   // The last element of CLI.InVals has the SDValue for swifterror return.
7354   // Here we copy it to a virtual register and update SwiftErrorMap for
7355   // book-keeping.
7356   if (SwiftErrorVal && TLI.supportSwiftError()) {
7357     // Get the last element of InVals.
7358     SDValue Src = CLI.InVals.back();
7359     Register VReg =
7360         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
7361     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7362     DAG.setRoot(CopyNode);
7363   }
7364 }
7365 
7366 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7367                              SelectionDAGBuilder &Builder) {
7368   // Check to see if this load can be trivially constant folded, e.g. if the
7369   // input is from a string literal.
7370   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7371     // Cast pointer to the type we really want to load.
7372     Type *LoadTy =
7373         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7374     if (LoadVT.isVector())
7375       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
7376 
7377     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7378                                          PointerType::getUnqual(LoadTy));
7379 
7380     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7381             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7382       return Builder.getValue(LoadCst);
7383   }
7384 
7385   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7386   // still constant memory, the input chain can be the entry node.
7387   SDValue Root;
7388   bool ConstantMemory = false;
7389 
7390   // Do not serialize (non-volatile) loads of constant memory with anything.
7391   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7392     Root = Builder.DAG.getEntryNode();
7393     ConstantMemory = true;
7394   } else {
7395     // Do not serialize non-volatile loads against each other.
7396     Root = Builder.DAG.getRoot();
7397   }
7398 
7399   SDValue Ptr = Builder.getValue(PtrVal);
7400   SDValue LoadVal =
7401       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
7402                           MachinePointerInfo(PtrVal), Align(1));
7403 
7404   if (!ConstantMemory)
7405     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7406   return LoadVal;
7407 }
7408 
7409 /// Record the value for an instruction that produces an integer result,
7410 /// converting the type where necessary.
7411 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7412                                                   SDValue Value,
7413                                                   bool IsSigned) {
7414   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7415                                                     I.getType(), true);
7416   if (IsSigned)
7417     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7418   else
7419     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7420   setValue(&I, Value);
7421 }
7422 
7423 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
7424 /// true and lower it. Otherwise return false, and it will be lowered like a
7425 /// normal call.
7426 /// The caller already checked that \p I calls the appropriate LibFunc with a
7427 /// correct prototype.
7428 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
7429   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7430   const Value *Size = I.getArgOperand(2);
7431   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7432   if (CSize && CSize->getZExtValue() == 0) {
7433     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7434                                                           I.getType(), true);
7435     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7436     return true;
7437   }
7438 
7439   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7440   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7441       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7442       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7443   if (Res.first.getNode()) {
7444     processIntegerCallValue(I, Res.first, true);
7445     PendingLoads.push_back(Res.second);
7446     return true;
7447   }
7448 
7449   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7450   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7451   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7452     return false;
7453 
7454   // If the target has a fast compare for the given size, it will return a
7455   // preferred load type for that size. Require that the load VT is legal and
7456   // that the target supports unaligned loads of that type. Otherwise, return
7457   // INVALID.
7458   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7459     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7460     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7461     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7462       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7463       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7464       // TODO: Check alignment of src and dest ptrs.
7465       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7466       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7467       if (!TLI.isTypeLegal(LVT) ||
7468           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7469           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7470         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7471     }
7472 
7473     return LVT;
7474   };
7475 
7476   // This turns into unaligned loads. We only do this if the target natively
7477   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7478   // we'll only produce a small number of byte loads.
7479   MVT LoadVT;
7480   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7481   switch (NumBitsToCompare) {
7482   default:
7483     return false;
7484   case 16:
7485     LoadVT = MVT::i16;
7486     break;
7487   case 32:
7488     LoadVT = MVT::i32;
7489     break;
7490   case 64:
7491   case 128:
7492   case 256:
7493     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7494     break;
7495   }
7496 
7497   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7498     return false;
7499 
7500   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7501   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7502 
7503   // Bitcast to a wide integer type if the loads are vectors.
7504   if (LoadVT.isVector()) {
7505     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7506     LoadL = DAG.getBitcast(CmpVT, LoadL);
7507     LoadR = DAG.getBitcast(CmpVT, LoadR);
7508   }
7509 
7510   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7511   processIntegerCallValue(I, Cmp, false);
7512   return true;
7513 }
7514 
7515 /// See if we can lower a memchr call into an optimized form. If so, return
7516 /// true and lower it. Otherwise return false, and it will be lowered like a
7517 /// normal call.
7518 /// The caller already checked that \p I calls the appropriate LibFunc with a
7519 /// correct prototype.
7520 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7521   const Value *Src = I.getArgOperand(0);
7522   const Value *Char = I.getArgOperand(1);
7523   const Value *Length = I.getArgOperand(2);
7524 
7525   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7526   std::pair<SDValue, SDValue> Res =
7527     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7528                                 getValue(Src), getValue(Char), getValue(Length),
7529                                 MachinePointerInfo(Src));
7530   if (Res.first.getNode()) {
7531     setValue(&I, Res.first);
7532     PendingLoads.push_back(Res.second);
7533     return true;
7534   }
7535 
7536   return false;
7537 }
7538 
7539 /// See if we can lower a mempcpy call into an optimized form. If so, return
7540 /// true and lower it. Otherwise return false, and it will be lowered like a
7541 /// normal call.
7542 /// The caller already checked that \p I calls the appropriate LibFunc with a
7543 /// correct prototype.
7544 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7545   SDValue Dst = getValue(I.getArgOperand(0));
7546   SDValue Src = getValue(I.getArgOperand(1));
7547   SDValue Size = getValue(I.getArgOperand(2));
7548 
7549   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
7550   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
7551   // DAG::getMemcpy needs Alignment to be defined.
7552   Align Alignment = std::min(DstAlign, SrcAlign);
7553 
7554   bool isVol = false;
7555   SDLoc sdl = getCurSDLoc();
7556 
7557   // In the mempcpy context we need to pass in a false value for isTailCall
7558   // because the return pointer needs to be adjusted by the size of
7559   // the copied memory.
7560   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7561   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7562                              /*isTailCall=*/false,
7563                              MachinePointerInfo(I.getArgOperand(0)),
7564                              MachinePointerInfo(I.getArgOperand(1)));
7565   assert(MC.getNode() != nullptr &&
7566          "** memcpy should not be lowered as TailCall in mempcpy context **");
7567   DAG.setRoot(MC);
7568 
7569   // Check if Size needs to be truncated or extended.
7570   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7571 
7572   // Adjust return pointer to point just past the last dst byte.
7573   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7574                                     Dst, Size);
7575   setValue(&I, DstPlusSize);
7576   return true;
7577 }
7578 
7579 /// See if we can lower a strcpy call into an optimized form.  If so, return
7580 /// true and lower it, otherwise return false and it will be lowered like a
7581 /// normal call.
7582 /// The caller already checked that \p I calls the appropriate LibFunc with a
7583 /// correct prototype.
7584 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7585   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7586 
7587   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7588   std::pair<SDValue, SDValue> Res =
7589     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7590                                 getValue(Arg0), getValue(Arg1),
7591                                 MachinePointerInfo(Arg0),
7592                                 MachinePointerInfo(Arg1), isStpcpy);
7593   if (Res.first.getNode()) {
7594     setValue(&I, Res.first);
7595     DAG.setRoot(Res.second);
7596     return true;
7597   }
7598 
7599   return false;
7600 }
7601 
7602 /// See if we can lower a strcmp call into an optimized form.  If so, return
7603 /// true and lower it, otherwise return false and it will be lowered like a
7604 /// normal call.
7605 /// The caller already checked that \p I calls the appropriate LibFunc with a
7606 /// correct prototype.
7607 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7608   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7609 
7610   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7611   std::pair<SDValue, SDValue> Res =
7612     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7613                                 getValue(Arg0), getValue(Arg1),
7614                                 MachinePointerInfo(Arg0),
7615                                 MachinePointerInfo(Arg1));
7616   if (Res.first.getNode()) {
7617     processIntegerCallValue(I, Res.first, true);
7618     PendingLoads.push_back(Res.second);
7619     return true;
7620   }
7621 
7622   return false;
7623 }
7624 
7625 /// See if we can lower a strlen call into an optimized form.  If so, return
7626 /// true and lower it, otherwise return false and it will be lowered like a
7627 /// normal call.
7628 /// The caller already checked that \p I calls the appropriate LibFunc with a
7629 /// correct prototype.
7630 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7631   const Value *Arg0 = I.getArgOperand(0);
7632 
7633   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7634   std::pair<SDValue, SDValue> Res =
7635     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7636                                 getValue(Arg0), MachinePointerInfo(Arg0));
7637   if (Res.first.getNode()) {
7638     processIntegerCallValue(I, Res.first, false);
7639     PendingLoads.push_back(Res.second);
7640     return true;
7641   }
7642 
7643   return false;
7644 }
7645 
7646 /// See if we can lower a strnlen call into an optimized form.  If so, return
7647 /// true and lower it, otherwise return false and it will be lowered like a
7648 /// normal call.
7649 /// The caller already checked that \p I calls the appropriate LibFunc with a
7650 /// correct prototype.
7651 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7652   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7653 
7654   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7655   std::pair<SDValue, SDValue> Res =
7656     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7657                                  getValue(Arg0), getValue(Arg1),
7658                                  MachinePointerInfo(Arg0));
7659   if (Res.first.getNode()) {
7660     processIntegerCallValue(I, Res.first, false);
7661     PendingLoads.push_back(Res.second);
7662     return true;
7663   }
7664 
7665   return false;
7666 }
7667 
7668 /// See if we can lower a unary floating-point operation into an SDNode with
7669 /// the specified Opcode.  If so, return true and lower it, otherwise return
7670 /// false and it will be lowered like a normal call.
7671 /// The caller already checked that \p I calls the appropriate LibFunc with a
7672 /// correct prototype.
7673 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7674                                               unsigned Opcode) {
7675   // We already checked this call's prototype; verify it doesn't modify errno.
7676   if (!I.onlyReadsMemory())
7677     return false;
7678 
7679   SDNodeFlags Flags;
7680   Flags.copyFMF(cast<FPMathOperator>(I));
7681 
7682   SDValue Tmp = getValue(I.getArgOperand(0));
7683   setValue(&I,
7684            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
7685   return true;
7686 }
7687 
7688 /// See if we can lower a binary floating-point operation into an SDNode with
7689 /// the specified Opcode. If so, return true and lower it. Otherwise return
7690 /// false, and it will be lowered like a normal call.
7691 /// The caller already checked that \p I calls the appropriate LibFunc with a
7692 /// correct prototype.
7693 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7694                                                unsigned Opcode) {
7695   // We already checked this call's prototype; verify it doesn't modify errno.
7696   if (!I.onlyReadsMemory())
7697     return false;
7698 
7699   SDNodeFlags Flags;
7700   Flags.copyFMF(cast<FPMathOperator>(I));
7701 
7702   SDValue Tmp0 = getValue(I.getArgOperand(0));
7703   SDValue Tmp1 = getValue(I.getArgOperand(1));
7704   EVT VT = Tmp0.getValueType();
7705   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
7706   return true;
7707 }
7708 
7709 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7710   // Handle inline assembly differently.
7711   if (I.isInlineAsm()) {
7712     visitInlineAsm(I);
7713     return;
7714   }
7715 
7716   if (Function *F = I.getCalledFunction()) {
7717     if (F->isDeclaration()) {
7718       // Is this an LLVM intrinsic or a target-specific intrinsic?
7719       unsigned IID = F->getIntrinsicID();
7720       if (!IID)
7721         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7722           IID = II->getIntrinsicID(F);
7723 
7724       if (IID) {
7725         visitIntrinsicCall(I, IID);
7726         return;
7727       }
7728     }
7729 
7730     // Check for well-known libc/libm calls.  If the function is internal, it
7731     // can't be a library call.  Don't do the check if marked as nobuiltin for
7732     // some reason or the call site requires strict floating point semantics.
7733     LibFunc Func;
7734     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7735         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7736         LibInfo->hasOptimizedCodeGen(Func)) {
7737       switch (Func) {
7738       default: break;
7739       case LibFunc_bcmp:
7740         if (visitMemCmpBCmpCall(I))
7741           return;
7742         break;
7743       case LibFunc_copysign:
7744       case LibFunc_copysignf:
7745       case LibFunc_copysignl:
7746         // We already checked this call's prototype; verify it doesn't modify
7747         // errno.
7748         if (I.onlyReadsMemory()) {
7749           SDValue LHS = getValue(I.getArgOperand(0));
7750           SDValue RHS = getValue(I.getArgOperand(1));
7751           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7752                                    LHS.getValueType(), LHS, RHS));
7753           return;
7754         }
7755         break;
7756       case LibFunc_fabs:
7757       case LibFunc_fabsf:
7758       case LibFunc_fabsl:
7759         if (visitUnaryFloatCall(I, ISD::FABS))
7760           return;
7761         break;
7762       case LibFunc_fmin:
7763       case LibFunc_fminf:
7764       case LibFunc_fminl:
7765         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7766           return;
7767         break;
7768       case LibFunc_fmax:
7769       case LibFunc_fmaxf:
7770       case LibFunc_fmaxl:
7771         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7772           return;
7773         break;
7774       case LibFunc_sin:
7775       case LibFunc_sinf:
7776       case LibFunc_sinl:
7777         if (visitUnaryFloatCall(I, ISD::FSIN))
7778           return;
7779         break;
7780       case LibFunc_cos:
7781       case LibFunc_cosf:
7782       case LibFunc_cosl:
7783         if (visitUnaryFloatCall(I, ISD::FCOS))
7784           return;
7785         break;
7786       case LibFunc_sqrt:
7787       case LibFunc_sqrtf:
7788       case LibFunc_sqrtl:
7789       case LibFunc_sqrt_finite:
7790       case LibFunc_sqrtf_finite:
7791       case LibFunc_sqrtl_finite:
7792         if (visitUnaryFloatCall(I, ISD::FSQRT))
7793           return;
7794         break;
7795       case LibFunc_floor:
7796       case LibFunc_floorf:
7797       case LibFunc_floorl:
7798         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7799           return;
7800         break;
7801       case LibFunc_nearbyint:
7802       case LibFunc_nearbyintf:
7803       case LibFunc_nearbyintl:
7804         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7805           return;
7806         break;
7807       case LibFunc_ceil:
7808       case LibFunc_ceilf:
7809       case LibFunc_ceill:
7810         if (visitUnaryFloatCall(I, ISD::FCEIL))
7811           return;
7812         break;
7813       case LibFunc_rint:
7814       case LibFunc_rintf:
7815       case LibFunc_rintl:
7816         if (visitUnaryFloatCall(I, ISD::FRINT))
7817           return;
7818         break;
7819       case LibFunc_round:
7820       case LibFunc_roundf:
7821       case LibFunc_roundl:
7822         if (visitUnaryFloatCall(I, ISD::FROUND))
7823           return;
7824         break;
7825       case LibFunc_trunc:
7826       case LibFunc_truncf:
7827       case LibFunc_truncl:
7828         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7829           return;
7830         break;
7831       case LibFunc_log2:
7832       case LibFunc_log2f:
7833       case LibFunc_log2l:
7834         if (visitUnaryFloatCall(I, ISD::FLOG2))
7835           return;
7836         break;
7837       case LibFunc_exp2:
7838       case LibFunc_exp2f:
7839       case LibFunc_exp2l:
7840         if (visitUnaryFloatCall(I, ISD::FEXP2))
7841           return;
7842         break;
7843       case LibFunc_memcmp:
7844         if (visitMemCmpBCmpCall(I))
7845           return;
7846         break;
7847       case LibFunc_mempcpy:
7848         if (visitMemPCpyCall(I))
7849           return;
7850         break;
7851       case LibFunc_memchr:
7852         if (visitMemChrCall(I))
7853           return;
7854         break;
7855       case LibFunc_strcpy:
7856         if (visitStrCpyCall(I, false))
7857           return;
7858         break;
7859       case LibFunc_stpcpy:
7860         if (visitStrCpyCall(I, true))
7861           return;
7862         break;
7863       case LibFunc_strcmp:
7864         if (visitStrCmpCall(I))
7865           return;
7866         break;
7867       case LibFunc_strlen:
7868         if (visitStrLenCall(I))
7869           return;
7870         break;
7871       case LibFunc_strnlen:
7872         if (visitStrNLenCall(I))
7873           return;
7874         break;
7875       }
7876     }
7877   }
7878 
7879   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7880   // have to do anything here to lower funclet bundles.
7881   // CFGuardTarget bundles are lowered in LowerCallTo.
7882   assert(!I.hasOperandBundlesOtherThan(
7883              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
7884               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
7885               LLVMContext::OB_clang_arc_attachedcall}) &&
7886          "Cannot lower calls with arbitrary operand bundles!");
7887 
7888   SDValue Callee = getValue(I.getCalledOperand());
7889 
7890   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7891     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7892   else
7893     // Check if we can potentially perform a tail call. More detailed checking
7894     // is be done within LowerCallTo, after more information about the call is
7895     // known.
7896     LowerCallTo(I, Callee, I.isTailCall());
7897 }
7898 
7899 namespace {
7900 
7901 /// AsmOperandInfo - This contains information for each constraint that we are
7902 /// lowering.
7903 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7904 public:
7905   /// CallOperand - If this is the result output operand or a clobber
7906   /// this is null, otherwise it is the incoming operand to the CallInst.
7907   /// This gets modified as the asm is processed.
7908   SDValue CallOperand;
7909 
7910   /// AssignedRegs - If this is a register or register class operand, this
7911   /// contains the set of register corresponding to the operand.
7912   RegsForValue AssignedRegs;
7913 
7914   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7915     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7916   }
7917 
7918   /// Whether or not this operand accesses memory
7919   bool hasMemory(const TargetLowering &TLI) const {
7920     // Indirect operand accesses access memory.
7921     if (isIndirect)
7922       return true;
7923 
7924     for (const auto &Code : Codes)
7925       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7926         return true;
7927 
7928     return false;
7929   }
7930 
7931   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7932   /// corresponds to.  If there is no Value* for this operand, it returns
7933   /// MVT::Other.
7934   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7935                            const DataLayout &DL) const {
7936     if (!CallOperandVal) return MVT::Other;
7937 
7938     if (isa<BasicBlock>(CallOperandVal))
7939       return TLI.getProgramPointerTy(DL);
7940 
7941     llvm::Type *OpTy = CallOperandVal->getType();
7942 
7943     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7944     // If this is an indirect operand, the operand is a pointer to the
7945     // accessed type.
7946     if (isIndirect) {
7947       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7948       if (!PtrTy)
7949         report_fatal_error("Indirect operand for inline asm not a pointer!");
7950       OpTy = PtrTy->getElementType();
7951     }
7952 
7953     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7954     if (StructType *STy = dyn_cast<StructType>(OpTy))
7955       if (STy->getNumElements() == 1)
7956         OpTy = STy->getElementType(0);
7957 
7958     // If OpTy is not a single value, it may be a struct/union that we
7959     // can tile with integers.
7960     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7961       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7962       switch (BitSize) {
7963       default: break;
7964       case 1:
7965       case 8:
7966       case 16:
7967       case 32:
7968       case 64:
7969       case 128:
7970         OpTy = IntegerType::get(Context, BitSize);
7971         break;
7972       }
7973     }
7974 
7975     return TLI.getValueType(DL, OpTy, true);
7976   }
7977 };
7978 
7979 
7980 } // end anonymous namespace
7981 
7982 /// Make sure that the output operand \p OpInfo and its corresponding input
7983 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7984 /// out).
7985 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7986                                SDISelAsmOperandInfo &MatchingOpInfo,
7987                                SelectionDAG &DAG) {
7988   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7989     return;
7990 
7991   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7992   const auto &TLI = DAG.getTargetLoweringInfo();
7993 
7994   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7995       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7996                                        OpInfo.ConstraintVT);
7997   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7998       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7999                                        MatchingOpInfo.ConstraintVT);
8000   if ((OpInfo.ConstraintVT.isInteger() !=
8001        MatchingOpInfo.ConstraintVT.isInteger()) ||
8002       (MatchRC.second != InputRC.second)) {
8003     // FIXME: error out in a more elegant fashion
8004     report_fatal_error("Unsupported asm: input constraint"
8005                        " with a matching output constraint of"
8006                        " incompatible type!");
8007   }
8008   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
8009 }
8010 
8011 /// Get a direct memory input to behave well as an indirect operand.
8012 /// This may introduce stores, hence the need for a \p Chain.
8013 /// \return The (possibly updated) chain.
8014 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
8015                                         SDISelAsmOperandInfo &OpInfo,
8016                                         SelectionDAG &DAG) {
8017   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8018 
8019   // If we don't have an indirect input, put it in the constpool if we can,
8020   // otherwise spill it to a stack slot.
8021   // TODO: This isn't quite right. We need to handle these according to
8022   // the addressing mode that the constraint wants. Also, this may take
8023   // an additional register for the computation and we don't want that
8024   // either.
8025 
8026   // If the operand is a float, integer, or vector constant, spill to a
8027   // constant pool entry to get its address.
8028   const Value *OpVal = OpInfo.CallOperandVal;
8029   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
8030       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
8031     OpInfo.CallOperand = DAG.getConstantPool(
8032         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
8033     return Chain;
8034   }
8035 
8036   // Otherwise, create a stack slot and emit a store to it before the asm.
8037   Type *Ty = OpVal->getType();
8038   auto &DL = DAG.getDataLayout();
8039   uint64_t TySize = DL.getTypeAllocSize(Ty);
8040   MachineFunction &MF = DAG.getMachineFunction();
8041   int SSFI = MF.getFrameInfo().CreateStackObject(
8042       TySize, DL.getPrefTypeAlign(Ty), false);
8043   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
8044   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
8045                             MachinePointerInfo::getFixedStack(MF, SSFI),
8046                             TLI.getMemValueType(DL, Ty));
8047   OpInfo.CallOperand = StackSlot;
8048 
8049   return Chain;
8050 }
8051 
8052 /// GetRegistersForValue - Assign registers (virtual or physical) for the
8053 /// specified operand.  We prefer to assign virtual registers, to allow the
8054 /// register allocator to handle the assignment process.  However, if the asm
8055 /// uses features that we can't model on machineinstrs, we have SDISel do the
8056 /// allocation.  This produces generally horrible, but correct, code.
8057 ///
8058 ///   OpInfo describes the operand
8059 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8060 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8061                                  SDISelAsmOperandInfo &OpInfo,
8062                                  SDISelAsmOperandInfo &RefOpInfo) {
8063   LLVMContext &Context = *DAG.getContext();
8064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8065 
8066   MachineFunction &MF = DAG.getMachineFunction();
8067   SmallVector<unsigned, 4> Regs;
8068   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8069 
8070   // No work to do for memory operations.
8071   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8072     return;
8073 
8074   // If this is a constraint for a single physreg, or a constraint for a
8075   // register class, find it.
8076   unsigned AssignedReg;
8077   const TargetRegisterClass *RC;
8078   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8079       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8080   // RC is unset only on failure. Return immediately.
8081   if (!RC)
8082     return;
8083 
8084   // Get the actual register value type.  This is important, because the user
8085   // may have asked for (e.g.) the AX register in i32 type.  We need to
8086   // remember that AX is actually i16 to get the right extension.
8087   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8088 
8089   if (OpInfo.ConstraintVT != MVT::Other) {
8090     // If this is an FP operand in an integer register (or visa versa), or more
8091     // generally if the operand value disagrees with the register class we plan
8092     // to stick it in, fix the operand type.
8093     //
8094     // If this is an input value, the bitcast to the new type is done now.
8095     // Bitcast for output value is done at the end of visitInlineAsm().
8096     if ((OpInfo.Type == InlineAsm::isOutput ||
8097          OpInfo.Type == InlineAsm::isInput) &&
8098         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8099       // Try to convert to the first EVT that the reg class contains.  If the
8100       // types are identical size, use a bitcast to convert (e.g. two differing
8101       // vector types).  Note: output bitcast is done at the end of
8102       // visitInlineAsm().
8103       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8104         // Exclude indirect inputs while they are unsupported because the code
8105         // to perform the load is missing and thus OpInfo.CallOperand still
8106         // refers to the input address rather than the pointed-to value.
8107         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8108           OpInfo.CallOperand =
8109               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8110         OpInfo.ConstraintVT = RegVT;
8111         // If the operand is an FP value and we want it in integer registers,
8112         // use the corresponding integer type. This turns an f64 value into
8113         // i64, which can be passed with two i32 values on a 32-bit machine.
8114       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8115         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8116         if (OpInfo.Type == InlineAsm::isInput)
8117           OpInfo.CallOperand =
8118               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8119         OpInfo.ConstraintVT = VT;
8120       }
8121     }
8122   }
8123 
8124   // No need to allocate a matching input constraint since the constraint it's
8125   // matching to has already been allocated.
8126   if (OpInfo.isMatchingInputConstraint())
8127     return;
8128 
8129   EVT ValueVT = OpInfo.ConstraintVT;
8130   if (OpInfo.ConstraintVT == MVT::Other)
8131     ValueVT = RegVT;
8132 
8133   // Initialize NumRegs.
8134   unsigned NumRegs = 1;
8135   if (OpInfo.ConstraintVT != MVT::Other)
8136     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8137 
8138   // If this is a constraint for a specific physical register, like {r17},
8139   // assign it now.
8140 
8141   // If this associated to a specific register, initialize iterator to correct
8142   // place. If virtual, make sure we have enough registers
8143 
8144   // Initialize iterator if necessary
8145   TargetRegisterClass::iterator I = RC->begin();
8146   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8147 
8148   // Do not check for single registers.
8149   if (AssignedReg) {
8150       for (; *I != AssignedReg; ++I)
8151         assert(I != RC->end() && "AssignedReg should be member of RC");
8152   }
8153 
8154   for (; NumRegs; --NumRegs, ++I) {
8155     assert(I != RC->end() && "Ran out of registers to allocate!");
8156     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8157     Regs.push_back(R);
8158   }
8159 
8160   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8161 }
8162 
8163 static unsigned
8164 findMatchingInlineAsmOperand(unsigned OperandNo,
8165                              const std::vector<SDValue> &AsmNodeOperands) {
8166   // Scan until we find the definition we already emitted of this operand.
8167   unsigned CurOp = InlineAsm::Op_FirstOperand;
8168   for (; OperandNo; --OperandNo) {
8169     // Advance to the next operand.
8170     unsigned OpFlag =
8171         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8172     assert((InlineAsm::isRegDefKind(OpFlag) ||
8173             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8174             InlineAsm::isMemKind(OpFlag)) &&
8175            "Skipped past definitions?");
8176     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8177   }
8178   return CurOp;
8179 }
8180 
8181 namespace {
8182 
8183 class ExtraFlags {
8184   unsigned Flags = 0;
8185 
8186 public:
8187   explicit ExtraFlags(const CallBase &Call) {
8188     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8189     if (IA->hasSideEffects())
8190       Flags |= InlineAsm::Extra_HasSideEffects;
8191     if (IA->isAlignStack())
8192       Flags |= InlineAsm::Extra_IsAlignStack;
8193     if (Call.isConvergent())
8194       Flags |= InlineAsm::Extra_IsConvergent;
8195     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8196   }
8197 
8198   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8199     // Ideally, we would only check against memory constraints.  However, the
8200     // meaning of an Other constraint can be target-specific and we can't easily
8201     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8202     // for Other constraints as well.
8203     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8204         OpInfo.ConstraintType == TargetLowering::C_Other) {
8205       if (OpInfo.Type == InlineAsm::isInput)
8206         Flags |= InlineAsm::Extra_MayLoad;
8207       else if (OpInfo.Type == InlineAsm::isOutput)
8208         Flags |= InlineAsm::Extra_MayStore;
8209       else if (OpInfo.Type == InlineAsm::isClobber)
8210         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8211     }
8212   }
8213 
8214   unsigned get() const { return Flags; }
8215 };
8216 
8217 } // end anonymous namespace
8218 
8219 /// visitInlineAsm - Handle a call to an InlineAsm object.
8220 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call) {
8221   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
8222 
8223   /// ConstraintOperands - Information about all of the constraints.
8224   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
8225 
8226   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8227   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8228       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
8229 
8230   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8231   // AsmDialect, MayLoad, MayStore).
8232   bool HasSideEffect = IA->hasSideEffects();
8233   ExtraFlags ExtraInfo(Call);
8234 
8235   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8236   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8237   unsigned NumMatchingOps = 0;
8238   for (auto &T : TargetConstraints) {
8239     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8240     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8241 
8242     // Compute the value type for each operand.
8243     if (OpInfo.Type == InlineAsm::isInput ||
8244         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8245       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
8246 
8247       // Process the call argument. BasicBlocks are labels, currently appearing
8248       // only in asm's.
8249       if (isa<CallBrInst>(Call) &&
8250           ArgNo - 1 >= (cast<CallBrInst>(&Call)->getNumArgOperands() -
8251                         cast<CallBrInst>(&Call)->getNumIndirectDests() -
8252                         NumMatchingOps) &&
8253           (NumMatchingOps == 0 ||
8254            ArgNo - 1 < (cast<CallBrInst>(&Call)->getNumArgOperands() -
8255                         NumMatchingOps))) {
8256         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8257         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8258         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8259       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8260         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8261       } else {
8262         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8263       }
8264 
8265       EVT VT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI,
8266                                            DAG.getDataLayout());
8267       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
8268     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8269       // The return value of the call is this value.  As such, there is no
8270       // corresponding argument.
8271       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8272       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
8273         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8274             DAG.getDataLayout(), STy->getElementType(ResNo));
8275       } else {
8276         assert(ResNo == 0 && "Asm only has one result!");
8277         OpInfo.ConstraintVT =
8278             TLI.getSimpleValueType(DAG.getDataLayout(), Call.getType());
8279       }
8280       ++ResNo;
8281     } else {
8282       OpInfo.ConstraintVT = MVT::Other;
8283     }
8284 
8285     if (OpInfo.hasMatchingInput())
8286       ++NumMatchingOps;
8287 
8288     if (!HasSideEffect)
8289       HasSideEffect = OpInfo.hasMemory(TLI);
8290 
8291     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8292     // FIXME: Could we compute this on OpInfo rather than T?
8293 
8294     // Compute the constraint code and ConstraintType to use.
8295     TLI.ComputeConstraintToUse(T, SDValue());
8296 
8297     if (T.ConstraintType == TargetLowering::C_Immediate &&
8298         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8299       // We've delayed emitting a diagnostic like the "n" constraint because
8300       // inlining could cause an integer showing up.
8301       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
8302                                           "' expects an integer constant "
8303                                           "expression");
8304 
8305     ExtraInfo.update(T);
8306   }
8307 
8308 
8309   // We won't need to flush pending loads if this asm doesn't touch
8310   // memory and is nonvolatile.
8311   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8312 
8313   bool IsCallBr = isa<CallBrInst>(Call);
8314   if (IsCallBr) {
8315     // If this is a callbr we need to flush pending exports since inlineasm_br
8316     // is a terminator. We need to do this before nodes are glued to
8317     // the inlineasm_br node.
8318     Chain = getControlRoot();
8319   }
8320 
8321   // Second pass over the constraints: compute which constraint option to use.
8322   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8323     // If this is an output operand with a matching input operand, look up the
8324     // matching input. If their types mismatch, e.g. one is an integer, the
8325     // other is floating point, or their sizes are different, flag it as an
8326     // error.
8327     if (OpInfo.hasMatchingInput()) {
8328       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8329       patchMatchingInput(OpInfo, Input, DAG);
8330     }
8331 
8332     // Compute the constraint code and ConstraintType to use.
8333     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8334 
8335     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8336         OpInfo.Type == InlineAsm::isClobber)
8337       continue;
8338 
8339     // If this is a memory input, and if the operand is not indirect, do what we
8340     // need to provide an address for the memory input.
8341     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8342         !OpInfo.isIndirect) {
8343       assert((OpInfo.isMultipleAlternative ||
8344               (OpInfo.Type == InlineAsm::isInput)) &&
8345              "Can only indirectify direct input operands!");
8346 
8347       // Memory operands really want the address of the value.
8348       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8349 
8350       // There is no longer a Value* corresponding to this operand.
8351       OpInfo.CallOperandVal = nullptr;
8352 
8353       // It is now an indirect operand.
8354       OpInfo.isIndirect = true;
8355     }
8356 
8357   }
8358 
8359   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8360   std::vector<SDValue> AsmNodeOperands;
8361   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8362   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8363       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
8364 
8365   // If we have a !srcloc metadata node associated with it, we want to attach
8366   // this to the ultimately generated inline asm machineinstr.  To do this, we
8367   // pass in the third operand as this (potentially null) inline asm MDNode.
8368   const MDNode *SrcLoc = Call.getMetadata("srcloc");
8369   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8370 
8371   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8372   // bits as operand 3.
8373   AsmNodeOperands.push_back(DAG.getTargetConstant(
8374       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8375 
8376   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8377   // this, assign virtual and physical registers for inputs and otput.
8378   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8379     // Assign Registers.
8380     SDISelAsmOperandInfo &RefOpInfo =
8381         OpInfo.isMatchingInputConstraint()
8382             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8383             : OpInfo;
8384     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8385 
8386     auto DetectWriteToReservedRegister = [&]() {
8387       const MachineFunction &MF = DAG.getMachineFunction();
8388       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8389       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
8390         if (Register::isPhysicalRegister(Reg) &&
8391             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
8392           const char *RegName = TRI.getName(Reg);
8393           emitInlineAsmError(Call, "write to reserved register '" +
8394                                        Twine(RegName) + "'");
8395           return true;
8396         }
8397       }
8398       return false;
8399     };
8400 
8401     switch (OpInfo.Type) {
8402     case InlineAsm::isOutput:
8403       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8404         unsigned ConstraintID =
8405             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8406         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8407                "Failed to convert memory constraint code to constraint id.");
8408 
8409         // Add information to the INLINEASM node to know about this output.
8410         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8411         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8412         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8413                                                         MVT::i32));
8414         AsmNodeOperands.push_back(OpInfo.CallOperand);
8415       } else {
8416         // Otherwise, this outputs to a register (directly for C_Register /
8417         // C_RegisterClass, and a target-defined fashion for
8418         // C_Immediate/C_Other). Find a register that we can use.
8419         if (OpInfo.AssignedRegs.Regs.empty()) {
8420           emitInlineAsmError(
8421               Call, "couldn't allocate output register for constraint '" +
8422                         Twine(OpInfo.ConstraintCode) + "'");
8423           return;
8424         }
8425 
8426         if (DetectWriteToReservedRegister())
8427           return;
8428 
8429         // Add information to the INLINEASM node to know that this register is
8430         // set.
8431         OpInfo.AssignedRegs.AddInlineAsmOperands(
8432             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8433                                   : InlineAsm::Kind_RegDef,
8434             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8435       }
8436       break;
8437 
8438     case InlineAsm::isInput: {
8439       SDValue InOperandVal = OpInfo.CallOperand;
8440 
8441       if (OpInfo.isMatchingInputConstraint()) {
8442         // If this is required to match an output register we have already set,
8443         // just use its register.
8444         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8445                                                   AsmNodeOperands);
8446         unsigned OpFlag =
8447           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8448         if (InlineAsm::isRegDefKind(OpFlag) ||
8449             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8450           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8451           if (OpInfo.isIndirect) {
8452             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8453             emitInlineAsmError(Call, "inline asm not supported yet: "
8454                                      "don't know how to handle tied "
8455                                      "indirect register inputs");
8456             return;
8457           }
8458 
8459           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8460           SmallVector<unsigned, 4> Regs;
8461 
8462           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8463             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8464             MachineRegisterInfo &RegInfo =
8465                 DAG.getMachineFunction().getRegInfo();
8466             for (unsigned i = 0; i != NumRegs; ++i)
8467               Regs.push_back(RegInfo.createVirtualRegister(RC));
8468           } else {
8469             emitInlineAsmError(Call,
8470                                "inline asm error: This value type register "
8471                                "class is not natively supported!");
8472             return;
8473           }
8474 
8475           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8476 
8477           SDLoc dl = getCurSDLoc();
8478           // Use the produced MatchedRegs object to
8479           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag, &Call);
8480           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8481                                            true, OpInfo.getMatchedOperand(), dl,
8482                                            DAG, AsmNodeOperands);
8483           break;
8484         }
8485 
8486         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8487         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8488                "Unexpected number of operands");
8489         // Add information to the INLINEASM node to know about this input.
8490         // See InlineAsm.h isUseOperandTiedToDef.
8491         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8492         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8493                                                     OpInfo.getMatchedOperand());
8494         AsmNodeOperands.push_back(DAG.getTargetConstant(
8495             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8496         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8497         break;
8498       }
8499 
8500       // Treat indirect 'X' constraint as memory.
8501       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8502           OpInfo.isIndirect)
8503         OpInfo.ConstraintType = TargetLowering::C_Memory;
8504 
8505       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8506           OpInfo.ConstraintType == TargetLowering::C_Other) {
8507         std::vector<SDValue> Ops;
8508         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8509                                           Ops, DAG);
8510         if (Ops.empty()) {
8511           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8512             if (isa<ConstantSDNode>(InOperandVal)) {
8513               emitInlineAsmError(Call, "value out of range for constraint '" +
8514                                            Twine(OpInfo.ConstraintCode) + "'");
8515               return;
8516             }
8517 
8518           emitInlineAsmError(Call,
8519                              "invalid operand for inline asm constraint '" +
8520                                  Twine(OpInfo.ConstraintCode) + "'");
8521           return;
8522         }
8523 
8524         // Add information to the INLINEASM node to know about this input.
8525         unsigned ResOpType =
8526           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8527         AsmNodeOperands.push_back(DAG.getTargetConstant(
8528             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8529         llvm::append_range(AsmNodeOperands, Ops);
8530         break;
8531       }
8532 
8533       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8534         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8535         assert(InOperandVal.getValueType() ==
8536                    TLI.getPointerTy(DAG.getDataLayout()) &&
8537                "Memory operands expect pointer values");
8538 
8539         unsigned ConstraintID =
8540             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8541         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8542                "Failed to convert memory constraint code to constraint id.");
8543 
8544         // Add information to the INLINEASM node to know about this input.
8545         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8546         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8547         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8548                                                         getCurSDLoc(),
8549                                                         MVT::i32));
8550         AsmNodeOperands.push_back(InOperandVal);
8551         break;
8552       }
8553 
8554       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8555               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8556              "Unknown constraint type!");
8557 
8558       // TODO: Support this.
8559       if (OpInfo.isIndirect) {
8560         emitInlineAsmError(
8561             Call, "Don't know how to handle indirect register inputs yet "
8562                   "for constraint '" +
8563                       Twine(OpInfo.ConstraintCode) + "'");
8564         return;
8565       }
8566 
8567       // Copy the input into the appropriate registers.
8568       if (OpInfo.AssignedRegs.Regs.empty()) {
8569         emitInlineAsmError(Call,
8570                            "couldn't allocate input reg for constraint '" +
8571                                Twine(OpInfo.ConstraintCode) + "'");
8572         return;
8573       }
8574 
8575       if (DetectWriteToReservedRegister())
8576         return;
8577 
8578       SDLoc dl = getCurSDLoc();
8579 
8580       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8581                                         &Call);
8582 
8583       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8584                                                dl, DAG, AsmNodeOperands);
8585       break;
8586     }
8587     case InlineAsm::isClobber:
8588       // Add the clobbered value to the operand list, so that the register
8589       // allocator is aware that the physreg got clobbered.
8590       if (!OpInfo.AssignedRegs.Regs.empty())
8591         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8592                                                  false, 0, getCurSDLoc(), DAG,
8593                                                  AsmNodeOperands);
8594       break;
8595     }
8596   }
8597 
8598   // Finish up input operands.  Set the input chain and add the flag last.
8599   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8600   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8601 
8602   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8603   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8604                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8605   Flag = Chain.getValue(1);
8606 
8607   // Do additional work to generate outputs.
8608 
8609   SmallVector<EVT, 1> ResultVTs;
8610   SmallVector<SDValue, 1> ResultValues;
8611   SmallVector<SDValue, 8> OutChains;
8612 
8613   llvm::Type *CallResultType = Call.getType();
8614   ArrayRef<Type *> ResultTypes;
8615   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
8616     ResultTypes = StructResult->elements();
8617   else if (!CallResultType->isVoidTy())
8618     ResultTypes = makeArrayRef(CallResultType);
8619 
8620   auto CurResultType = ResultTypes.begin();
8621   auto handleRegAssign = [&](SDValue V) {
8622     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8623     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8624     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8625     ++CurResultType;
8626     // If the type of the inline asm call site return value is different but has
8627     // same size as the type of the asm output bitcast it.  One example of this
8628     // is for vectors with different width / number of elements.  This can
8629     // happen for register classes that can contain multiple different value
8630     // types.  The preg or vreg allocated may not have the same VT as was
8631     // expected.
8632     //
8633     // This can also happen for a return value that disagrees with the register
8634     // class it is put in, eg. a double in a general-purpose register on a
8635     // 32-bit machine.
8636     if (ResultVT != V.getValueType() &&
8637         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8638       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8639     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8640              V.getValueType().isInteger()) {
8641       // If a result value was tied to an input value, the computed result
8642       // may have a wider width than the expected result.  Extract the
8643       // relevant portion.
8644       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8645     }
8646     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8647     ResultVTs.push_back(ResultVT);
8648     ResultValues.push_back(V);
8649   };
8650 
8651   // Deal with output operands.
8652   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8653     if (OpInfo.Type == InlineAsm::isOutput) {
8654       SDValue Val;
8655       // Skip trivial output operands.
8656       if (OpInfo.AssignedRegs.Regs.empty())
8657         continue;
8658 
8659       switch (OpInfo.ConstraintType) {
8660       case TargetLowering::C_Register:
8661       case TargetLowering::C_RegisterClass:
8662         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
8663                                                   Chain, &Flag, &Call);
8664         break;
8665       case TargetLowering::C_Immediate:
8666       case TargetLowering::C_Other:
8667         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8668                                               OpInfo, DAG);
8669         break;
8670       case TargetLowering::C_Memory:
8671         break; // Already handled.
8672       case TargetLowering::C_Unknown:
8673         assert(false && "Unexpected unknown constraint");
8674       }
8675 
8676       // Indirect output manifest as stores. Record output chains.
8677       if (OpInfo.isIndirect) {
8678         const Value *Ptr = OpInfo.CallOperandVal;
8679         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8680         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8681                                      MachinePointerInfo(Ptr));
8682         OutChains.push_back(Store);
8683       } else {
8684         // generate CopyFromRegs to associated registers.
8685         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
8686         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8687           for (const SDValue &V : Val->op_values())
8688             handleRegAssign(V);
8689         } else
8690           handleRegAssign(Val);
8691       }
8692     }
8693   }
8694 
8695   // Set results.
8696   if (!ResultValues.empty()) {
8697     assert(CurResultType == ResultTypes.end() &&
8698            "Mismatch in number of ResultTypes");
8699     assert(ResultValues.size() == ResultTypes.size() &&
8700            "Mismatch in number of output operands in asm result");
8701 
8702     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8703                             DAG.getVTList(ResultVTs), ResultValues);
8704     setValue(&Call, V);
8705   }
8706 
8707   // Collect store chains.
8708   if (!OutChains.empty())
8709     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8710 
8711   // Only Update Root if inline assembly has a memory effect.
8712   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8713     DAG.setRoot(Chain);
8714 }
8715 
8716 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
8717                                              const Twine &Message) {
8718   LLVMContext &Ctx = *DAG.getContext();
8719   Ctx.emitError(&Call, Message);
8720 
8721   // Make sure we leave the DAG in a valid state
8722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8723   SmallVector<EVT, 1> ValueVTs;
8724   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
8725 
8726   if (ValueVTs.empty())
8727     return;
8728 
8729   SmallVector<SDValue, 1> Ops;
8730   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8731     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8732 
8733   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
8734 }
8735 
8736 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8737   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8738                           MVT::Other, getRoot(),
8739                           getValue(I.getArgOperand(0)),
8740                           DAG.getSrcValue(I.getArgOperand(0))));
8741 }
8742 
8743 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8745   const DataLayout &DL = DAG.getDataLayout();
8746   SDValue V = DAG.getVAArg(
8747       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8748       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8749       DL.getABITypeAlign(I.getType()).value());
8750   DAG.setRoot(V.getValue(1));
8751 
8752   if (I.getType()->isPointerTy())
8753     V = DAG.getPtrExtOrTrunc(
8754         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8755   setValue(&I, V);
8756 }
8757 
8758 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8759   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8760                           MVT::Other, getRoot(),
8761                           getValue(I.getArgOperand(0)),
8762                           DAG.getSrcValue(I.getArgOperand(0))));
8763 }
8764 
8765 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8766   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8767                           MVT::Other, getRoot(),
8768                           getValue(I.getArgOperand(0)),
8769                           getValue(I.getArgOperand(1)),
8770                           DAG.getSrcValue(I.getArgOperand(0)),
8771                           DAG.getSrcValue(I.getArgOperand(1))));
8772 }
8773 
8774 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8775                                                     const Instruction &I,
8776                                                     SDValue Op) {
8777   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8778   if (!Range)
8779     return Op;
8780 
8781   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8782   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8783     return Op;
8784 
8785   APInt Lo = CR.getUnsignedMin();
8786   if (!Lo.isMinValue())
8787     return Op;
8788 
8789   APInt Hi = CR.getUnsignedMax();
8790   unsigned Bits = std::max(Hi.getActiveBits(),
8791                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8792 
8793   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8794 
8795   SDLoc SL = getCurSDLoc();
8796 
8797   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8798                              DAG.getValueType(SmallVT));
8799   unsigned NumVals = Op.getNode()->getNumValues();
8800   if (NumVals == 1)
8801     return ZExt;
8802 
8803   SmallVector<SDValue, 4> Ops;
8804 
8805   Ops.push_back(ZExt);
8806   for (unsigned I = 1; I != NumVals; ++I)
8807     Ops.push_back(Op.getValue(I));
8808 
8809   return DAG.getMergeValues(Ops, SL);
8810 }
8811 
8812 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8813 /// the call being lowered.
8814 ///
8815 /// This is a helper for lowering intrinsics that follow a target calling
8816 /// convention or require stack pointer adjustment. Only a subset of the
8817 /// intrinsic's operands need to participate in the calling convention.
8818 void SelectionDAGBuilder::populateCallLoweringInfo(
8819     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8820     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8821     bool IsPatchPoint) {
8822   TargetLowering::ArgListTy Args;
8823   Args.reserve(NumArgs);
8824 
8825   // Populate the argument list.
8826   // Attributes for args start at offset 1, after the return attribute.
8827   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8828        ArgI != ArgE; ++ArgI) {
8829     const Value *V = Call->getOperand(ArgI);
8830 
8831     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8832 
8833     TargetLowering::ArgListEntry Entry;
8834     Entry.Node = getValue(V);
8835     Entry.Ty = V->getType();
8836     Entry.setAttributes(Call, ArgI);
8837     Args.push_back(Entry);
8838   }
8839 
8840   CLI.setDebugLoc(getCurSDLoc())
8841       .setChain(getRoot())
8842       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8843       .setDiscardResult(Call->use_empty())
8844       .setIsPatchPoint(IsPatchPoint)
8845       .setIsPreallocated(
8846           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
8847 }
8848 
8849 /// Add a stack map intrinsic call's live variable operands to a stackmap
8850 /// or patchpoint target node's operand list.
8851 ///
8852 /// Constants are converted to TargetConstants purely as an optimization to
8853 /// avoid constant materialization and register allocation.
8854 ///
8855 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8856 /// generate addess computation nodes, and so FinalizeISel can convert the
8857 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8858 /// address materialization and register allocation, but may also be required
8859 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8860 /// alloca in the entry block, then the runtime may assume that the alloca's
8861 /// StackMap location can be read immediately after compilation and that the
8862 /// location is valid at any point during execution (this is similar to the
8863 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8864 /// only available in a register, then the runtime would need to trap when
8865 /// execution reaches the StackMap in order to read the alloca's location.
8866 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
8867                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8868                                 SelectionDAGBuilder &Builder) {
8869   for (unsigned i = StartIdx, e = Call.arg_size(); i != e; ++i) {
8870     SDValue OpVal = Builder.getValue(Call.getArgOperand(i));
8871     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8872       Ops.push_back(
8873         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8874       Ops.push_back(
8875         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8876     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8877       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8878       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8879           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8880     } else
8881       Ops.push_back(OpVal);
8882   }
8883 }
8884 
8885 /// Lower llvm.experimental.stackmap directly to its target opcode.
8886 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8887   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8888   //                                  [live variables...])
8889 
8890   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8891 
8892   SDValue Chain, InFlag, Callee, NullPtr;
8893   SmallVector<SDValue, 32> Ops;
8894 
8895   SDLoc DL = getCurSDLoc();
8896   Callee = getValue(CI.getCalledOperand());
8897   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8898 
8899   // The stackmap intrinsic only records the live variables (the arguments
8900   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8901   // intrinsic, this won't be lowered to a function call. This means we don't
8902   // have to worry about calling conventions and target specific lowering code.
8903   // Instead we perform the call lowering right here.
8904   //
8905   // chain, flag = CALLSEQ_START(chain, 0, 0)
8906   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8907   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8908   //
8909   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8910   InFlag = Chain.getValue(1);
8911 
8912   // Add the <id> and <numBytes> constants.
8913   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8914   Ops.push_back(DAG.getTargetConstant(
8915                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8916   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8917   Ops.push_back(DAG.getTargetConstant(
8918                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8919                   MVT::i32));
8920 
8921   // Push live variables for the stack map.
8922   addStackMapLiveVars(CI, 2, DL, Ops, *this);
8923 
8924   // We are not pushing any register mask info here on the operands list,
8925   // because the stackmap doesn't clobber anything.
8926 
8927   // Push the chain and the glue flag.
8928   Ops.push_back(Chain);
8929   Ops.push_back(InFlag);
8930 
8931   // Create the STACKMAP node.
8932   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8933   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8934   Chain = SDValue(SM, 0);
8935   InFlag = Chain.getValue(1);
8936 
8937   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8938 
8939   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8940 
8941   // Set the root to the target-lowered call chain.
8942   DAG.setRoot(Chain);
8943 
8944   // Inform the Frame Information that we have a stackmap in this function.
8945   FuncInfo.MF->getFrameInfo().setHasStackMap();
8946 }
8947 
8948 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8949 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
8950                                           const BasicBlock *EHPadBB) {
8951   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8952   //                                                 i32 <numBytes>,
8953   //                                                 i8* <target>,
8954   //                                                 i32 <numArgs>,
8955   //                                                 [Args...],
8956   //                                                 [live variables...])
8957 
8958   CallingConv::ID CC = CB.getCallingConv();
8959   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8960   bool HasDef = !CB.getType()->isVoidTy();
8961   SDLoc dl = getCurSDLoc();
8962   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
8963 
8964   // Handle immediate and symbolic callees.
8965   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8966     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8967                                    /*isTarget=*/true);
8968   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8969     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8970                                          SDLoc(SymbolicCallee),
8971                                          SymbolicCallee->getValueType(0));
8972 
8973   // Get the real number of arguments participating in the call <numArgs>
8974   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
8975   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8976 
8977   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8978   // Intrinsics include all meta-operands up to but not including CC.
8979   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8980   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
8981          "Not enough arguments provided to the patchpoint intrinsic");
8982 
8983   // For AnyRegCC the arguments are lowered later on manually.
8984   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8985   Type *ReturnTy =
8986       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
8987 
8988   TargetLowering::CallLoweringInfo CLI(DAG);
8989   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
8990                            ReturnTy, true);
8991   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8992 
8993   SDNode *CallEnd = Result.second.getNode();
8994   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8995     CallEnd = CallEnd->getOperand(0).getNode();
8996 
8997   /// Get a call instruction from the call sequence chain.
8998   /// Tail calls are not allowed.
8999   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
9000          "Expected a callseq node.");
9001   SDNode *Call = CallEnd->getOperand(0).getNode();
9002   bool HasGlue = Call->getGluedNode();
9003 
9004   // Replace the target specific call node with the patchable intrinsic.
9005   SmallVector<SDValue, 8> Ops;
9006 
9007   // Add the <id> and <numBytes> constants.
9008   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
9009   Ops.push_back(DAG.getTargetConstant(
9010                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
9011   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
9012   Ops.push_back(DAG.getTargetConstant(
9013                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
9014                   MVT::i32));
9015 
9016   // Add the callee.
9017   Ops.push_back(Callee);
9018 
9019   // Adjust <numArgs> to account for any arguments that have been passed on the
9020   // stack instead.
9021   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
9022   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
9023   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
9024   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
9025 
9026   // Add the calling convention
9027   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
9028 
9029   // Add the arguments we omitted previously. The register allocator should
9030   // place these in any free register.
9031   if (IsAnyRegCC)
9032     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
9033       Ops.push_back(getValue(CB.getArgOperand(i)));
9034 
9035   // Push the arguments from the call instruction up to the register mask.
9036   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
9037   Ops.append(Call->op_begin() + 2, e);
9038 
9039   // Push live variables for the stack map.
9040   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
9041 
9042   // Push the register mask info.
9043   if (HasGlue)
9044     Ops.push_back(*(Call->op_end()-2));
9045   else
9046     Ops.push_back(*(Call->op_end()-1));
9047 
9048   // Push the chain (this is originally the first operand of the call, but
9049   // becomes now the last or second to last operand).
9050   Ops.push_back(*(Call->op_begin()));
9051 
9052   // Push the glue flag (last operand).
9053   if (HasGlue)
9054     Ops.push_back(*(Call->op_end()-1));
9055 
9056   SDVTList NodeTys;
9057   if (IsAnyRegCC && HasDef) {
9058     // Create the return types based on the intrinsic definition
9059     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9060     SmallVector<EVT, 3> ValueVTs;
9061     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
9062     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
9063 
9064     // There is always a chain and a glue type at the end
9065     ValueVTs.push_back(MVT::Other);
9066     ValueVTs.push_back(MVT::Glue);
9067     NodeTys = DAG.getVTList(ValueVTs);
9068   } else
9069     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9070 
9071   // Replace the target specific call node with a PATCHPOINT node.
9072   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
9073                                          dl, NodeTys, Ops);
9074 
9075   // Update the NodeMap.
9076   if (HasDef) {
9077     if (IsAnyRegCC)
9078       setValue(&CB, SDValue(MN, 0));
9079     else
9080       setValue(&CB, Result.first);
9081   }
9082 
9083   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
9084   // call sequence. Furthermore the location of the chain and glue can change
9085   // when the AnyReg calling convention is used and the intrinsic returns a
9086   // value.
9087   if (IsAnyRegCC && HasDef) {
9088     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
9089     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9090     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9091   } else
9092     DAG.ReplaceAllUsesWith(Call, MN);
9093   DAG.DeleteNode(Call);
9094 
9095   // Inform the Frame Information that we have a patchpoint in this function.
9096   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9097 }
9098 
9099 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9100                                             unsigned Intrinsic) {
9101   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9102   SDValue Op1 = getValue(I.getArgOperand(0));
9103   SDValue Op2;
9104   if (I.getNumArgOperands() > 1)
9105     Op2 = getValue(I.getArgOperand(1));
9106   SDLoc dl = getCurSDLoc();
9107   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9108   SDValue Res;
9109   SDNodeFlags SDFlags;
9110   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
9111     SDFlags.copyFMF(*FPMO);
9112 
9113   switch (Intrinsic) {
9114   case Intrinsic::vector_reduce_fadd:
9115     if (SDFlags.hasAllowReassociation())
9116       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9117                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
9118                         SDFlags);
9119     else
9120       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
9121     break;
9122   case Intrinsic::vector_reduce_fmul:
9123     if (SDFlags.hasAllowReassociation())
9124       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9125                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
9126                         SDFlags);
9127     else
9128       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
9129     break;
9130   case Intrinsic::vector_reduce_add:
9131     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9132     break;
9133   case Intrinsic::vector_reduce_mul:
9134     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9135     break;
9136   case Intrinsic::vector_reduce_and:
9137     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9138     break;
9139   case Intrinsic::vector_reduce_or:
9140     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9141     break;
9142   case Intrinsic::vector_reduce_xor:
9143     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9144     break;
9145   case Intrinsic::vector_reduce_smax:
9146     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9147     break;
9148   case Intrinsic::vector_reduce_smin:
9149     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9150     break;
9151   case Intrinsic::vector_reduce_umax:
9152     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9153     break;
9154   case Intrinsic::vector_reduce_umin:
9155     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9156     break;
9157   case Intrinsic::vector_reduce_fmax:
9158     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
9159     break;
9160   case Intrinsic::vector_reduce_fmin:
9161     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
9162     break;
9163   default:
9164     llvm_unreachable("Unhandled vector reduce intrinsic");
9165   }
9166   setValue(&I, Res);
9167 }
9168 
9169 /// Returns an AttributeList representing the attributes applied to the return
9170 /// value of the given call.
9171 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9172   SmallVector<Attribute::AttrKind, 2> Attrs;
9173   if (CLI.RetSExt)
9174     Attrs.push_back(Attribute::SExt);
9175   if (CLI.RetZExt)
9176     Attrs.push_back(Attribute::ZExt);
9177   if (CLI.IsInReg)
9178     Attrs.push_back(Attribute::InReg);
9179 
9180   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9181                             Attrs);
9182 }
9183 
9184 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9185 /// implementation, which just calls LowerCall.
9186 /// FIXME: When all targets are
9187 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9188 std::pair<SDValue, SDValue>
9189 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9190   // Handle the incoming return values from the call.
9191   CLI.Ins.clear();
9192   Type *OrigRetTy = CLI.RetTy;
9193   SmallVector<EVT, 4> RetTys;
9194   SmallVector<uint64_t, 4> Offsets;
9195   auto &DL = CLI.DAG.getDataLayout();
9196   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9197 
9198   if (CLI.IsPostTypeLegalization) {
9199     // If we are lowering a libcall after legalization, split the return type.
9200     SmallVector<EVT, 4> OldRetTys;
9201     SmallVector<uint64_t, 4> OldOffsets;
9202     RetTys.swap(OldRetTys);
9203     Offsets.swap(OldOffsets);
9204 
9205     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9206       EVT RetVT = OldRetTys[i];
9207       uint64_t Offset = OldOffsets[i];
9208       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9209       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9210       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9211       RetTys.append(NumRegs, RegisterVT);
9212       for (unsigned j = 0; j != NumRegs; ++j)
9213         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9214     }
9215   }
9216 
9217   SmallVector<ISD::OutputArg, 4> Outs;
9218   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9219 
9220   bool CanLowerReturn =
9221       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9222                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9223 
9224   SDValue DemoteStackSlot;
9225   int DemoteStackIdx = -100;
9226   if (!CanLowerReturn) {
9227     // FIXME: equivalent assert?
9228     // assert(!CS.hasInAllocaArgument() &&
9229     //        "sret demotion is incompatible with inalloca");
9230     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9231     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
9232     MachineFunction &MF = CLI.DAG.getMachineFunction();
9233     DemoteStackIdx =
9234         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
9235     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9236                                               DL.getAllocaAddrSpace());
9237 
9238     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9239     ArgListEntry Entry;
9240     Entry.Node = DemoteStackSlot;
9241     Entry.Ty = StackSlotPtrType;
9242     Entry.IsSExt = false;
9243     Entry.IsZExt = false;
9244     Entry.IsInReg = false;
9245     Entry.IsSRet = true;
9246     Entry.IsNest = false;
9247     Entry.IsByVal = false;
9248     Entry.IsByRef = false;
9249     Entry.IsReturned = false;
9250     Entry.IsSwiftSelf = false;
9251     Entry.IsSwiftError = false;
9252     Entry.IsCFGuardTarget = false;
9253     Entry.Alignment = Alignment;
9254     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9255     CLI.NumFixedArgs += 1;
9256     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9257 
9258     // sret demotion isn't compatible with tail-calls, since the sret argument
9259     // points into the callers stack frame.
9260     CLI.IsTailCall = false;
9261   } else {
9262     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9263         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9264     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9265       ISD::ArgFlagsTy Flags;
9266       if (NeedsRegBlock) {
9267         Flags.setInConsecutiveRegs();
9268         if (I == RetTys.size() - 1)
9269           Flags.setInConsecutiveRegsLast();
9270       }
9271       EVT VT = RetTys[I];
9272       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9273                                                      CLI.CallConv, VT);
9274       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9275                                                        CLI.CallConv, VT);
9276       for (unsigned i = 0; i != NumRegs; ++i) {
9277         ISD::InputArg MyFlags;
9278         MyFlags.Flags = Flags;
9279         MyFlags.VT = RegisterVT;
9280         MyFlags.ArgVT = VT;
9281         MyFlags.Used = CLI.IsReturnValueUsed;
9282         if (CLI.RetTy->isPointerTy()) {
9283           MyFlags.Flags.setPointer();
9284           MyFlags.Flags.setPointerAddrSpace(
9285               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9286         }
9287         if (CLI.RetSExt)
9288           MyFlags.Flags.setSExt();
9289         if (CLI.RetZExt)
9290           MyFlags.Flags.setZExt();
9291         if (CLI.IsInReg)
9292           MyFlags.Flags.setInReg();
9293         CLI.Ins.push_back(MyFlags);
9294       }
9295     }
9296   }
9297 
9298   // We push in swifterror return as the last element of CLI.Ins.
9299   ArgListTy &Args = CLI.getArgs();
9300   if (supportSwiftError()) {
9301     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9302       if (Args[i].IsSwiftError) {
9303         ISD::InputArg MyFlags;
9304         MyFlags.VT = getPointerTy(DL);
9305         MyFlags.ArgVT = EVT(getPointerTy(DL));
9306         MyFlags.Flags.setSwiftError();
9307         CLI.Ins.push_back(MyFlags);
9308       }
9309     }
9310   }
9311 
9312   // Handle all of the outgoing arguments.
9313   CLI.Outs.clear();
9314   CLI.OutVals.clear();
9315   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9316     SmallVector<EVT, 4> ValueVTs;
9317     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9318     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9319     Type *FinalType = Args[i].Ty;
9320     if (Args[i].IsByVal)
9321       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9322     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9323         FinalType, CLI.CallConv, CLI.IsVarArg);
9324     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9325          ++Value) {
9326       EVT VT = ValueVTs[Value];
9327       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9328       SDValue Op = SDValue(Args[i].Node.getNode(),
9329                            Args[i].Node.getResNo() + Value);
9330       ISD::ArgFlagsTy Flags;
9331 
9332       // Certain targets (such as MIPS), may have a different ABI alignment
9333       // for a type depending on the context. Give the target a chance to
9334       // specify the alignment it wants.
9335       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9336 
9337       if (Args[i].Ty->isPointerTy()) {
9338         Flags.setPointer();
9339         Flags.setPointerAddrSpace(
9340             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9341       }
9342       if (Args[i].IsZExt)
9343         Flags.setZExt();
9344       if (Args[i].IsSExt)
9345         Flags.setSExt();
9346       if (Args[i].IsInReg) {
9347         // If we are using vectorcall calling convention, a structure that is
9348         // passed InReg - is surely an HVA
9349         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9350             isa<StructType>(FinalType)) {
9351           // The first value of a structure is marked
9352           if (0 == Value)
9353             Flags.setHvaStart();
9354           Flags.setHva();
9355         }
9356         // Set InReg Flag
9357         Flags.setInReg();
9358       }
9359       if (Args[i].IsSRet)
9360         Flags.setSRet();
9361       if (Args[i].IsSwiftSelf)
9362         Flags.setSwiftSelf();
9363       if (Args[i].IsSwiftError)
9364         Flags.setSwiftError();
9365       if (Args[i].IsCFGuardTarget)
9366         Flags.setCFGuardTarget();
9367       if (Args[i].IsByVal)
9368         Flags.setByVal();
9369       if (Args[i].IsByRef)
9370         Flags.setByRef();
9371       if (Args[i].IsPreallocated) {
9372         Flags.setPreallocated();
9373         // Set the byval flag for CCAssignFn callbacks that don't know about
9374         // preallocated.  This way we can know how many bytes we should've
9375         // allocated and how many bytes a callee cleanup function will pop.  If
9376         // we port preallocated to more targets, we'll have to add custom
9377         // preallocated handling in the various CC lowering callbacks.
9378         Flags.setByVal();
9379       }
9380       if (Args[i].IsInAlloca) {
9381         Flags.setInAlloca();
9382         // Set the byval flag for CCAssignFn callbacks that don't know about
9383         // inalloca.  This way we can know how many bytes we should've allocated
9384         // and how many bytes a callee cleanup function will pop.  If we port
9385         // inalloca to more targets, we'll have to add custom inalloca handling
9386         // in the various CC lowering callbacks.
9387         Flags.setByVal();
9388       }
9389       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
9390         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9391         Type *ElementTy = Ty->getElementType();
9392 
9393         unsigned FrameSize = DL.getTypeAllocSize(
9394             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9395         Flags.setByValSize(FrameSize);
9396 
9397         // info is not there but there are cases it cannot get right.
9398         Align FrameAlign;
9399         if (auto MA = Args[i].Alignment)
9400           FrameAlign = *MA;
9401         else
9402           FrameAlign = Align(getByValTypeAlignment(ElementTy, DL));
9403         Flags.setByValAlign(FrameAlign);
9404       }
9405       if (Args[i].IsNest)
9406         Flags.setNest();
9407       if (NeedsRegBlock)
9408         Flags.setInConsecutiveRegs();
9409       Flags.setOrigAlign(OriginalAlignment);
9410 
9411       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9412                                                  CLI.CallConv, VT);
9413       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9414                                                         CLI.CallConv, VT);
9415       SmallVector<SDValue, 4> Parts(NumParts);
9416       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9417 
9418       if (Args[i].IsSExt)
9419         ExtendKind = ISD::SIGN_EXTEND;
9420       else if (Args[i].IsZExt)
9421         ExtendKind = ISD::ZERO_EXTEND;
9422 
9423       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9424       // for now.
9425       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9426           CanLowerReturn) {
9427         assert((CLI.RetTy == Args[i].Ty ||
9428                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9429                  CLI.RetTy->getPointerAddressSpace() ==
9430                      Args[i].Ty->getPointerAddressSpace())) &&
9431                RetTys.size() == NumValues && "unexpected use of 'returned'");
9432         // Before passing 'returned' to the target lowering code, ensure that
9433         // either the register MVT and the actual EVT are the same size or that
9434         // the return value and argument are extended in the same way; in these
9435         // cases it's safe to pass the argument register value unchanged as the
9436         // return register value (although it's at the target's option whether
9437         // to do so)
9438         // TODO: allow code generation to take advantage of partially preserved
9439         // registers rather than clobbering the entire register when the
9440         // parameter extension method is not compatible with the return
9441         // extension method
9442         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9443             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9444              CLI.RetZExt == Args[i].IsZExt))
9445           Flags.setReturned();
9446       }
9447 
9448       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
9449                      CLI.CallConv, ExtendKind);
9450 
9451       for (unsigned j = 0; j != NumParts; ++j) {
9452         // if it isn't first piece, alignment must be 1
9453         // For scalable vectors the scalable part is currently handled
9454         // by individual targets, so we just use the known minimum size here.
9455         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9456                     i < CLI.NumFixedArgs, i,
9457                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9458         if (NumParts > 1 && j == 0)
9459           MyFlags.Flags.setSplit();
9460         else if (j != 0) {
9461           MyFlags.Flags.setOrigAlign(Align(1));
9462           if (j == NumParts - 1)
9463             MyFlags.Flags.setSplitEnd();
9464         }
9465 
9466         CLI.Outs.push_back(MyFlags);
9467         CLI.OutVals.push_back(Parts[j]);
9468       }
9469 
9470       if (NeedsRegBlock && Value == NumValues - 1)
9471         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9472     }
9473   }
9474 
9475   SmallVector<SDValue, 4> InVals;
9476   CLI.Chain = LowerCall(CLI, InVals);
9477 
9478   // Update CLI.InVals to use outside of this function.
9479   CLI.InVals = InVals;
9480 
9481   // Verify that the target's LowerCall behaved as expected.
9482   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9483          "LowerCall didn't return a valid chain!");
9484   assert((!CLI.IsTailCall || InVals.empty()) &&
9485          "LowerCall emitted a return value for a tail call!");
9486   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9487          "LowerCall didn't emit the correct number of values!");
9488 
9489   // For a tail call, the return value is merely live-out and there aren't
9490   // any nodes in the DAG representing it. Return a special value to
9491   // indicate that a tail call has been emitted and no more Instructions
9492   // should be processed in the current block.
9493   if (CLI.IsTailCall) {
9494     CLI.DAG.setRoot(CLI.Chain);
9495     return std::make_pair(SDValue(), SDValue());
9496   }
9497 
9498 #ifndef NDEBUG
9499   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9500     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9501     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9502            "LowerCall emitted a value with the wrong type!");
9503   }
9504 #endif
9505 
9506   SmallVector<SDValue, 4> ReturnValues;
9507   if (!CanLowerReturn) {
9508     // The instruction result is the result of loading from the
9509     // hidden sret parameter.
9510     SmallVector<EVT, 1> PVTs;
9511     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9512 
9513     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9514     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9515     EVT PtrVT = PVTs[0];
9516 
9517     unsigned NumValues = RetTys.size();
9518     ReturnValues.resize(NumValues);
9519     SmallVector<SDValue, 4> Chains(NumValues);
9520 
9521     // An aggregate return value cannot wrap around the address space, so
9522     // offsets to its parts don't wrap either.
9523     SDNodeFlags Flags;
9524     Flags.setNoUnsignedWrap(true);
9525 
9526     MachineFunction &MF = CLI.DAG.getMachineFunction();
9527     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
9528     for (unsigned i = 0; i < NumValues; ++i) {
9529       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9530                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9531                                                         PtrVT), Flags);
9532       SDValue L = CLI.DAG.getLoad(
9533           RetTys[i], CLI.DL, CLI.Chain, Add,
9534           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9535                                             DemoteStackIdx, Offsets[i]),
9536           HiddenSRetAlign);
9537       ReturnValues[i] = L;
9538       Chains[i] = L.getValue(1);
9539     }
9540 
9541     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9542   } else {
9543     // Collect the legal value parts into potentially illegal values
9544     // that correspond to the original function's return values.
9545     Optional<ISD::NodeType> AssertOp;
9546     if (CLI.RetSExt)
9547       AssertOp = ISD::AssertSext;
9548     else if (CLI.RetZExt)
9549       AssertOp = ISD::AssertZext;
9550     unsigned CurReg = 0;
9551     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9552       EVT VT = RetTys[I];
9553       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9554                                                      CLI.CallConv, VT);
9555       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9556                                                        CLI.CallConv, VT);
9557 
9558       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9559                                               NumRegs, RegisterVT, VT, nullptr,
9560                                               CLI.CallConv, AssertOp));
9561       CurReg += NumRegs;
9562     }
9563 
9564     // For a function returning void, there is no return value. We can't create
9565     // such a node, so we just return a null return value in that case. In
9566     // that case, nothing will actually look at the value.
9567     if (ReturnValues.empty())
9568       return std::make_pair(SDValue(), CLI.Chain);
9569   }
9570 
9571   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9572                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9573   return std::make_pair(Res, CLI.Chain);
9574 }
9575 
9576 /// Places new result values for the node in Results (their number
9577 /// and types must exactly match those of the original return values of
9578 /// the node), or leaves Results empty, which indicates that the node is not
9579 /// to be custom lowered after all.
9580 void TargetLowering::LowerOperationWrapper(SDNode *N,
9581                                            SmallVectorImpl<SDValue> &Results,
9582                                            SelectionDAG &DAG) const {
9583   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
9584 
9585   if (!Res.getNode())
9586     return;
9587 
9588   // If the original node has one result, take the return value from
9589   // LowerOperation as is. It might not be result number 0.
9590   if (N->getNumValues() == 1) {
9591     Results.push_back(Res);
9592     return;
9593   }
9594 
9595   // If the original node has multiple results, then the return node should
9596   // have the same number of results.
9597   assert((N->getNumValues() == Res->getNumValues()) &&
9598       "Lowering returned the wrong number of results!");
9599 
9600   // Places new result values base on N result number.
9601   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
9602     Results.push_back(Res.getValue(I));
9603 }
9604 
9605 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9606   llvm_unreachable("LowerOperation not implemented for this target!");
9607 }
9608 
9609 void
9610 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9611   SDValue Op = getNonRegisterValue(V);
9612   assert((Op.getOpcode() != ISD::CopyFromReg ||
9613           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9614          "Copy from a reg to the same reg!");
9615   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9616 
9617   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9618   // If this is an InlineAsm we have to match the registers required, not the
9619   // notional registers required by the type.
9620 
9621   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9622                    None); // This is not an ABI copy.
9623   SDValue Chain = DAG.getEntryNode();
9624 
9625   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9626                               FuncInfo.PreferredExtendType.end())
9627                                  ? ISD::ANY_EXTEND
9628                                  : FuncInfo.PreferredExtendType[V];
9629   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9630   PendingExports.push_back(Chain);
9631 }
9632 
9633 #include "llvm/CodeGen/SelectionDAGISel.h"
9634 
9635 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9636 /// entry block, return true.  This includes arguments used by switches, since
9637 /// the switch may expand into multiple basic blocks.
9638 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9639   // With FastISel active, we may be splitting blocks, so force creation
9640   // of virtual registers for all non-dead arguments.
9641   if (FastISel)
9642     return A->use_empty();
9643 
9644   const BasicBlock &Entry = A->getParent()->front();
9645   for (const User *U : A->users())
9646     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9647       return false;  // Use not in entry block.
9648 
9649   return true;
9650 }
9651 
9652 using ArgCopyElisionMapTy =
9653     DenseMap<const Argument *,
9654              std::pair<const AllocaInst *, const StoreInst *>>;
9655 
9656 /// Scan the entry block of the function in FuncInfo for arguments that look
9657 /// like copies into a local alloca. Record any copied arguments in
9658 /// ArgCopyElisionCandidates.
9659 static void
9660 findArgumentCopyElisionCandidates(const DataLayout &DL,
9661                                   FunctionLoweringInfo *FuncInfo,
9662                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9663   // Record the state of every static alloca used in the entry block. Argument
9664   // allocas are all used in the entry block, so we need approximately as many
9665   // entries as we have arguments.
9666   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9667   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9668   unsigned NumArgs = FuncInfo->Fn->arg_size();
9669   StaticAllocas.reserve(NumArgs * 2);
9670 
9671   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9672     if (!V)
9673       return nullptr;
9674     V = V->stripPointerCasts();
9675     const auto *AI = dyn_cast<AllocaInst>(V);
9676     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9677       return nullptr;
9678     auto Iter = StaticAllocas.insert({AI, Unknown});
9679     return &Iter.first->second;
9680   };
9681 
9682   // Look for stores of arguments to static allocas. Look through bitcasts and
9683   // GEPs to handle type coercions, as long as the alloca is fully initialized
9684   // by the store. Any non-store use of an alloca escapes it and any subsequent
9685   // unanalyzed store might write it.
9686   // FIXME: Handle structs initialized with multiple stores.
9687   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9688     // Look for stores, and handle non-store uses conservatively.
9689     const auto *SI = dyn_cast<StoreInst>(&I);
9690     if (!SI) {
9691       // We will look through cast uses, so ignore them completely.
9692       if (I.isCast())
9693         continue;
9694       // Ignore debug info and pseudo op intrinsics, they don't escape or store
9695       // to allocas.
9696       if (I.isDebugOrPseudoInst())
9697         continue;
9698       // This is an unknown instruction. Assume it escapes or writes to all
9699       // static alloca operands.
9700       for (const Use &U : I.operands()) {
9701         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9702           *Info = StaticAllocaInfo::Clobbered;
9703       }
9704       continue;
9705     }
9706 
9707     // If the stored value is a static alloca, mark it as escaped.
9708     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9709       *Info = StaticAllocaInfo::Clobbered;
9710 
9711     // Check if the destination is a static alloca.
9712     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9713     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9714     if (!Info)
9715       continue;
9716     const AllocaInst *AI = cast<AllocaInst>(Dst);
9717 
9718     // Skip allocas that have been initialized or clobbered.
9719     if (*Info != StaticAllocaInfo::Unknown)
9720       continue;
9721 
9722     // Check if the stored value is an argument, and that this store fully
9723     // initializes the alloca. Don't elide copies from the same argument twice.
9724     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9725     const auto *Arg = dyn_cast<Argument>(Val);
9726     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
9727         Arg->getType()->isEmptyTy() ||
9728         DL.getTypeStoreSize(Arg->getType()) !=
9729             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9730         ArgCopyElisionCandidates.count(Arg)) {
9731       *Info = StaticAllocaInfo::Clobbered;
9732       continue;
9733     }
9734 
9735     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9736                       << '\n');
9737 
9738     // Mark this alloca and store for argument copy elision.
9739     *Info = StaticAllocaInfo::Elidable;
9740     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9741 
9742     // Stop scanning if we've seen all arguments. This will happen early in -O0
9743     // builds, which is useful, because -O0 builds have large entry blocks and
9744     // many allocas.
9745     if (ArgCopyElisionCandidates.size() == NumArgs)
9746       break;
9747   }
9748 }
9749 
9750 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9751 /// ArgVal is a load from a suitable fixed stack object.
9752 static void tryToElideArgumentCopy(
9753     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9754     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9755     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9756     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9757     SDValue ArgVal, bool &ArgHasUses) {
9758   // Check if this is a load from a fixed stack object.
9759   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9760   if (!LNode)
9761     return;
9762   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9763   if (!FINode)
9764     return;
9765 
9766   // Check that the fixed stack object is the right size and alignment.
9767   // Look at the alignment that the user wrote on the alloca instead of looking
9768   // at the stack object.
9769   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9770   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9771   const AllocaInst *AI = ArgCopyIter->second.first;
9772   int FixedIndex = FINode->getIndex();
9773   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9774   int OldIndex = AllocaIndex;
9775   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9776   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9777     LLVM_DEBUG(
9778         dbgs() << "  argument copy elision failed due to bad fixed stack "
9779                   "object size\n");
9780     return;
9781   }
9782   Align RequiredAlignment = AI->getAlign();
9783   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
9784     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9785                          "greater than stack argument alignment ("
9786                       << DebugStr(RequiredAlignment) << " vs "
9787                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
9788     return;
9789   }
9790 
9791   // Perform the elision. Delete the old stack object and replace its only use
9792   // in the variable info map. Mark the stack object as mutable.
9793   LLVM_DEBUG({
9794     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9795            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9796            << '\n';
9797   });
9798   MFI.RemoveStackObject(OldIndex);
9799   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9800   AllocaIndex = FixedIndex;
9801   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9802   Chains.push_back(ArgVal.getValue(1));
9803 
9804   // Avoid emitting code for the store implementing the copy.
9805   const StoreInst *SI = ArgCopyIter->second.second;
9806   ElidedArgCopyInstrs.insert(SI);
9807 
9808   // Check for uses of the argument again so that we can avoid exporting ArgVal
9809   // if it is't used by anything other than the store.
9810   for (const Value *U : Arg.users()) {
9811     if (U != SI) {
9812       ArgHasUses = true;
9813       break;
9814     }
9815   }
9816 }
9817 
9818 void SelectionDAGISel::LowerArguments(const Function &F) {
9819   SelectionDAG &DAG = SDB->DAG;
9820   SDLoc dl = SDB->getCurSDLoc();
9821   const DataLayout &DL = DAG.getDataLayout();
9822   SmallVector<ISD::InputArg, 16> Ins;
9823 
9824   // In Naked functions we aren't going to save any registers.
9825   if (F.hasFnAttribute(Attribute::Naked))
9826     return;
9827 
9828   if (!FuncInfo->CanLowerReturn) {
9829     // Put in an sret pointer parameter before all the other parameters.
9830     SmallVector<EVT, 1> ValueVTs;
9831     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9832                     F.getReturnType()->getPointerTo(
9833                         DAG.getDataLayout().getAllocaAddrSpace()),
9834                     ValueVTs);
9835 
9836     // NOTE: Assuming that a pointer will never break down to more than one VT
9837     // or one register.
9838     ISD::ArgFlagsTy Flags;
9839     Flags.setSRet();
9840     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9841     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9842                          ISD::InputArg::NoArgIndex, 0);
9843     Ins.push_back(RetArg);
9844   }
9845 
9846   // Look for stores of arguments to static allocas. Mark such arguments with a
9847   // flag to ask the target to give us the memory location of that argument if
9848   // available.
9849   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9850   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9851                                     ArgCopyElisionCandidates);
9852 
9853   // Set up the incoming argument description vector.
9854   for (const Argument &Arg : F.args()) {
9855     unsigned ArgNo = Arg.getArgNo();
9856     SmallVector<EVT, 4> ValueVTs;
9857     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9858     bool isArgValueUsed = !Arg.use_empty();
9859     unsigned PartBase = 0;
9860     Type *FinalType = Arg.getType();
9861     if (Arg.hasAttribute(Attribute::ByVal))
9862       FinalType = Arg.getParamByValType();
9863     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9864         FinalType, F.getCallingConv(), F.isVarArg());
9865     for (unsigned Value = 0, NumValues = ValueVTs.size();
9866          Value != NumValues; ++Value) {
9867       EVT VT = ValueVTs[Value];
9868       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9869       ISD::ArgFlagsTy Flags;
9870 
9871       // Certain targets (such as MIPS), may have a different ABI alignment
9872       // for a type depending on the context. Give the target a chance to
9873       // specify the alignment it wants.
9874       const Align OriginalAlignment(
9875           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9876 
9877       if (Arg.getType()->isPointerTy()) {
9878         Flags.setPointer();
9879         Flags.setPointerAddrSpace(
9880             cast<PointerType>(Arg.getType())->getAddressSpace());
9881       }
9882       if (Arg.hasAttribute(Attribute::ZExt))
9883         Flags.setZExt();
9884       if (Arg.hasAttribute(Attribute::SExt))
9885         Flags.setSExt();
9886       if (Arg.hasAttribute(Attribute::InReg)) {
9887         // If we are using vectorcall calling convention, a structure that is
9888         // passed InReg - is surely an HVA
9889         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9890             isa<StructType>(Arg.getType())) {
9891           // The first value of a structure is marked
9892           if (0 == Value)
9893             Flags.setHvaStart();
9894           Flags.setHva();
9895         }
9896         // Set InReg Flag
9897         Flags.setInReg();
9898       }
9899       if (Arg.hasAttribute(Attribute::StructRet))
9900         Flags.setSRet();
9901       if (Arg.hasAttribute(Attribute::SwiftSelf))
9902         Flags.setSwiftSelf();
9903       if (Arg.hasAttribute(Attribute::SwiftError))
9904         Flags.setSwiftError();
9905       if (Arg.hasAttribute(Attribute::ByVal))
9906         Flags.setByVal();
9907       if (Arg.hasAttribute(Attribute::ByRef))
9908         Flags.setByRef();
9909       if (Arg.hasAttribute(Attribute::InAlloca)) {
9910         Flags.setInAlloca();
9911         // Set the byval flag for CCAssignFn callbacks that don't know about
9912         // inalloca.  This way we can know how many bytes we should've allocated
9913         // and how many bytes a callee cleanup function will pop.  If we port
9914         // inalloca to more targets, we'll have to add custom inalloca handling
9915         // in the various CC lowering callbacks.
9916         Flags.setByVal();
9917       }
9918       if (Arg.hasAttribute(Attribute::Preallocated)) {
9919         Flags.setPreallocated();
9920         // Set the byval flag for CCAssignFn callbacks that don't know about
9921         // preallocated.  This way we can know how many bytes we should've
9922         // allocated and how many bytes a callee cleanup function will pop.  If
9923         // we port preallocated to more targets, we'll have to add custom
9924         // preallocated handling in the various CC lowering callbacks.
9925         Flags.setByVal();
9926       }
9927 
9928       Type *ArgMemTy = nullptr;
9929       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
9930           Flags.isByRef()) {
9931         if (!ArgMemTy)
9932           ArgMemTy = Arg.getPointeeInMemoryValueType();
9933 
9934         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
9935 
9936         // For in-memory arguments, size and alignment should be passed from FE.
9937         // BE will guess if this info is not there but there are cases it cannot
9938         // get right.
9939         MaybeAlign MemAlign = Arg.getParamAlign();
9940         if (!MemAlign)
9941           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
9942 
9943         if (Flags.isByRef()) {
9944           Flags.setByRefSize(MemSize);
9945           Flags.setByRefAlign(*MemAlign);
9946         } else {
9947           Flags.setByValSize(MemSize);
9948           Flags.setByValAlign(*MemAlign);
9949         }
9950       }
9951 
9952       if (Arg.hasAttribute(Attribute::Nest))
9953         Flags.setNest();
9954       if (NeedsRegBlock)
9955         Flags.setInConsecutiveRegs();
9956       Flags.setOrigAlign(OriginalAlignment);
9957       if (ArgCopyElisionCandidates.count(&Arg))
9958         Flags.setCopyElisionCandidate();
9959       if (Arg.hasAttribute(Attribute::Returned))
9960         Flags.setReturned();
9961 
9962       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9963           *CurDAG->getContext(), F.getCallingConv(), VT);
9964       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9965           *CurDAG->getContext(), F.getCallingConv(), VT);
9966       for (unsigned i = 0; i != NumRegs; ++i) {
9967         // For scalable vectors, use the minimum size; individual targets
9968         // are responsible for handling scalable vector arguments and
9969         // return values.
9970         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9971                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9972         if (NumRegs > 1 && i == 0)
9973           MyFlags.Flags.setSplit();
9974         // if it isn't first piece, alignment must be 1
9975         else if (i > 0) {
9976           MyFlags.Flags.setOrigAlign(Align(1));
9977           if (i == NumRegs - 1)
9978             MyFlags.Flags.setSplitEnd();
9979         }
9980         Ins.push_back(MyFlags);
9981       }
9982       if (NeedsRegBlock && Value == NumValues - 1)
9983         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9984       PartBase += VT.getStoreSize().getKnownMinSize();
9985     }
9986   }
9987 
9988   // Call the target to set up the argument values.
9989   SmallVector<SDValue, 8> InVals;
9990   SDValue NewRoot = TLI->LowerFormalArguments(
9991       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9992 
9993   // Verify that the target's LowerFormalArguments behaved as expected.
9994   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9995          "LowerFormalArguments didn't return a valid chain!");
9996   assert(InVals.size() == Ins.size() &&
9997          "LowerFormalArguments didn't emit the correct number of values!");
9998   LLVM_DEBUG({
9999     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
10000       assert(InVals[i].getNode() &&
10001              "LowerFormalArguments emitted a null value!");
10002       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
10003              "LowerFormalArguments emitted a value with the wrong type!");
10004     }
10005   });
10006 
10007   // Update the DAG with the new chain value resulting from argument lowering.
10008   DAG.setRoot(NewRoot);
10009 
10010   // Set up the argument values.
10011   unsigned i = 0;
10012   if (!FuncInfo->CanLowerReturn) {
10013     // Create a virtual register for the sret pointer, and put in a copy
10014     // from the sret argument into it.
10015     SmallVector<EVT, 1> ValueVTs;
10016     ComputeValueVTs(*TLI, DAG.getDataLayout(),
10017                     F.getReturnType()->getPointerTo(
10018                         DAG.getDataLayout().getAllocaAddrSpace()),
10019                     ValueVTs);
10020     MVT VT = ValueVTs[0].getSimpleVT();
10021     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
10022     Optional<ISD::NodeType> AssertOp = None;
10023     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
10024                                         nullptr, F.getCallingConv(), AssertOp);
10025 
10026     MachineFunction& MF = SDB->DAG.getMachineFunction();
10027     MachineRegisterInfo& RegInfo = MF.getRegInfo();
10028     Register SRetReg =
10029         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
10030     FuncInfo->DemoteRegister = SRetReg;
10031     NewRoot =
10032         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
10033     DAG.setRoot(NewRoot);
10034 
10035     // i indexes lowered arguments.  Bump it past the hidden sret argument.
10036     ++i;
10037   }
10038 
10039   SmallVector<SDValue, 4> Chains;
10040   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
10041   for (const Argument &Arg : F.args()) {
10042     SmallVector<SDValue, 4> ArgValues;
10043     SmallVector<EVT, 4> ValueVTs;
10044     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
10045     unsigned NumValues = ValueVTs.size();
10046     if (NumValues == 0)
10047       continue;
10048 
10049     bool ArgHasUses = !Arg.use_empty();
10050 
10051     // Elide the copying store if the target loaded this argument from a
10052     // suitable fixed stack object.
10053     if (Ins[i].Flags.isCopyElisionCandidate()) {
10054       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
10055                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
10056                              InVals[i], ArgHasUses);
10057     }
10058 
10059     // If this argument is unused then remember its value. It is used to generate
10060     // debugging information.
10061     bool isSwiftErrorArg =
10062         TLI->supportSwiftError() &&
10063         Arg.hasAttribute(Attribute::SwiftError);
10064     if (!ArgHasUses && !isSwiftErrorArg) {
10065       SDB->setUnusedArgValue(&Arg, InVals[i]);
10066 
10067       // Also remember any frame index for use in FastISel.
10068       if (FrameIndexSDNode *FI =
10069           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
10070         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10071     }
10072 
10073     for (unsigned Val = 0; Val != NumValues; ++Val) {
10074       EVT VT = ValueVTs[Val];
10075       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
10076                                                       F.getCallingConv(), VT);
10077       unsigned NumParts = TLI->getNumRegistersForCallingConv(
10078           *CurDAG->getContext(), F.getCallingConv(), VT);
10079 
10080       // Even an apparent 'unused' swifterror argument needs to be returned. So
10081       // we do generate a copy for it that can be used on return from the
10082       // function.
10083       if (ArgHasUses || isSwiftErrorArg) {
10084         Optional<ISD::NodeType> AssertOp;
10085         if (Arg.hasAttribute(Attribute::SExt))
10086           AssertOp = ISD::AssertSext;
10087         else if (Arg.hasAttribute(Attribute::ZExt))
10088           AssertOp = ISD::AssertZext;
10089 
10090         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
10091                                              PartVT, VT, nullptr,
10092                                              F.getCallingConv(), AssertOp));
10093       }
10094 
10095       i += NumParts;
10096     }
10097 
10098     // We don't need to do anything else for unused arguments.
10099     if (ArgValues.empty())
10100       continue;
10101 
10102     // Note down frame index.
10103     if (FrameIndexSDNode *FI =
10104         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
10105       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10106 
10107     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
10108                                      SDB->getCurSDLoc());
10109 
10110     SDB->setValue(&Arg, Res);
10111     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
10112       // We want to associate the argument with the frame index, among
10113       // involved operands, that correspond to the lowest address. The
10114       // getCopyFromParts function, called earlier, is swapping the order of
10115       // the operands to BUILD_PAIR depending on endianness. The result of
10116       // that swapping is that the least significant bits of the argument will
10117       // be in the first operand of the BUILD_PAIR node, and the most
10118       // significant bits will be in the second operand.
10119       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
10120       if (LoadSDNode *LNode =
10121           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
10122         if (FrameIndexSDNode *FI =
10123             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
10124           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
10125     }
10126 
10127     // Analyses past this point are naive and don't expect an assertion.
10128     if (Res.getOpcode() == ISD::AssertZext)
10129       Res = Res.getOperand(0);
10130 
10131     // Update the SwiftErrorVRegDefMap.
10132     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
10133       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10134       if (Register::isVirtualRegister(Reg))
10135         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
10136                                    Reg);
10137     }
10138 
10139     // If this argument is live outside of the entry block, insert a copy from
10140     // wherever we got it to the vreg that other BB's will reference it as.
10141     if (Res.getOpcode() == ISD::CopyFromReg) {
10142       // If we can, though, try to skip creating an unnecessary vreg.
10143       // FIXME: This isn't very clean... it would be nice to make this more
10144       // general.
10145       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10146       if (Register::isVirtualRegister(Reg)) {
10147         FuncInfo->ValueMap[&Arg] = Reg;
10148         continue;
10149       }
10150     }
10151     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10152       FuncInfo->InitializeRegForValue(&Arg);
10153       SDB->CopyToExportRegsIfNeeded(&Arg);
10154     }
10155   }
10156 
10157   if (!Chains.empty()) {
10158     Chains.push_back(NewRoot);
10159     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10160   }
10161 
10162   DAG.setRoot(NewRoot);
10163 
10164   assert(i == InVals.size() && "Argument register count mismatch!");
10165 
10166   // If any argument copy elisions occurred and we have debug info, update the
10167   // stale frame indices used in the dbg.declare variable info table.
10168   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10169   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10170     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10171       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10172       if (I != ArgCopyElisionFrameIndexMap.end())
10173         VI.Slot = I->second;
10174     }
10175   }
10176 
10177   // Finally, if the target has anything special to do, allow it to do so.
10178   emitFunctionEntryCode();
10179 }
10180 
10181 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10182 /// ensure constants are generated when needed.  Remember the virtual registers
10183 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10184 /// directly add them, because expansion might result in multiple MBB's for one
10185 /// BB.  As such, the start of the BB might correspond to a different MBB than
10186 /// the end.
10187 void
10188 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10189   const Instruction *TI = LLVMBB->getTerminator();
10190 
10191   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10192 
10193   // Check PHI nodes in successors that expect a value to be available from this
10194   // block.
10195   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10196     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10197     if (!isa<PHINode>(SuccBB->begin())) continue;
10198     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10199 
10200     // If this terminator has multiple identical successors (common for
10201     // switches), only handle each succ once.
10202     if (!SuccsHandled.insert(SuccMBB).second)
10203       continue;
10204 
10205     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10206 
10207     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10208     // nodes and Machine PHI nodes, but the incoming operands have not been
10209     // emitted yet.
10210     for (const PHINode &PN : SuccBB->phis()) {
10211       // Ignore dead phi's.
10212       if (PN.use_empty())
10213         continue;
10214 
10215       // Skip empty types
10216       if (PN.getType()->isEmptyTy())
10217         continue;
10218 
10219       unsigned Reg;
10220       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10221 
10222       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10223         unsigned &RegOut = ConstantsOut[C];
10224         if (RegOut == 0) {
10225           RegOut = FuncInfo.CreateRegs(C);
10226           CopyValueToVirtualRegister(C, RegOut);
10227         }
10228         Reg = RegOut;
10229       } else {
10230         DenseMap<const Value *, Register>::iterator I =
10231           FuncInfo.ValueMap.find(PHIOp);
10232         if (I != FuncInfo.ValueMap.end())
10233           Reg = I->second;
10234         else {
10235           assert(isa<AllocaInst>(PHIOp) &&
10236                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10237                  "Didn't codegen value into a register!??");
10238           Reg = FuncInfo.CreateRegs(PHIOp);
10239           CopyValueToVirtualRegister(PHIOp, Reg);
10240         }
10241       }
10242 
10243       // Remember that this register needs to added to the machine PHI node as
10244       // the input for this MBB.
10245       SmallVector<EVT, 4> ValueVTs;
10246       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10247       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10248       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10249         EVT VT = ValueVTs[vti];
10250         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10251         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10252           FuncInfo.PHINodesToUpdate.push_back(
10253               std::make_pair(&*MBBI++, Reg + i));
10254         Reg += NumRegisters;
10255       }
10256     }
10257   }
10258 
10259   ConstantsOut.clear();
10260 }
10261 
10262 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10263 /// is 0.
10264 MachineBasicBlock *
10265 SelectionDAGBuilder::StackProtectorDescriptor::
10266 AddSuccessorMBB(const BasicBlock *BB,
10267                 MachineBasicBlock *ParentMBB,
10268                 bool IsLikely,
10269                 MachineBasicBlock *SuccMBB) {
10270   // If SuccBB has not been created yet, create it.
10271   if (!SuccMBB) {
10272     MachineFunction *MF = ParentMBB->getParent();
10273     MachineFunction::iterator BBI(ParentMBB);
10274     SuccMBB = MF->CreateMachineBasicBlock(BB);
10275     MF->insert(++BBI, SuccMBB);
10276   }
10277   // Add it as a successor of ParentMBB.
10278   ParentMBB->addSuccessor(
10279       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10280   return SuccMBB;
10281 }
10282 
10283 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10284   MachineFunction::iterator I(MBB);
10285   if (++I == FuncInfo.MF->end())
10286     return nullptr;
10287   return &*I;
10288 }
10289 
10290 /// During lowering new call nodes can be created (such as memset, etc.).
10291 /// Those will become new roots of the current DAG, but complications arise
10292 /// when they are tail calls. In such cases, the call lowering will update
10293 /// the root, but the builder still needs to know that a tail call has been
10294 /// lowered in order to avoid generating an additional return.
10295 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10296   // If the node is null, we do have a tail call.
10297   if (MaybeTC.getNode() != nullptr)
10298     DAG.setRoot(MaybeTC);
10299   else
10300     HasTailCall = true;
10301 }
10302 
10303 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10304                                         MachineBasicBlock *SwitchMBB,
10305                                         MachineBasicBlock *DefaultMBB) {
10306   MachineFunction *CurMF = FuncInfo.MF;
10307   MachineBasicBlock *NextMBB = nullptr;
10308   MachineFunction::iterator BBI(W.MBB);
10309   if (++BBI != FuncInfo.MF->end())
10310     NextMBB = &*BBI;
10311 
10312   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10313 
10314   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10315 
10316   if (Size == 2 && W.MBB == SwitchMBB) {
10317     // If any two of the cases has the same destination, and if one value
10318     // is the same as the other, but has one bit unset that the other has set,
10319     // use bit manipulation to do two compares at once.  For example:
10320     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10321     // TODO: This could be extended to merge any 2 cases in switches with 3
10322     // cases.
10323     // TODO: Handle cases where W.CaseBB != SwitchBB.
10324     CaseCluster &Small = *W.FirstCluster;
10325     CaseCluster &Big = *W.LastCluster;
10326 
10327     if (Small.Low == Small.High && Big.Low == Big.High &&
10328         Small.MBB == Big.MBB) {
10329       const APInt &SmallValue = Small.Low->getValue();
10330       const APInt &BigValue = Big.Low->getValue();
10331 
10332       // Check that there is only one bit different.
10333       APInt CommonBit = BigValue ^ SmallValue;
10334       if (CommonBit.isPowerOf2()) {
10335         SDValue CondLHS = getValue(Cond);
10336         EVT VT = CondLHS.getValueType();
10337         SDLoc DL = getCurSDLoc();
10338 
10339         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10340                                  DAG.getConstant(CommonBit, DL, VT));
10341         SDValue Cond = DAG.getSetCC(
10342             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10343             ISD::SETEQ);
10344 
10345         // Update successor info.
10346         // Both Small and Big will jump to Small.BB, so we sum up the
10347         // probabilities.
10348         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10349         if (BPI)
10350           addSuccessorWithProb(
10351               SwitchMBB, DefaultMBB,
10352               // The default destination is the first successor in IR.
10353               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10354         else
10355           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10356 
10357         // Insert the true branch.
10358         SDValue BrCond =
10359             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10360                         DAG.getBasicBlock(Small.MBB));
10361         // Insert the false branch.
10362         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10363                              DAG.getBasicBlock(DefaultMBB));
10364 
10365         DAG.setRoot(BrCond);
10366         return;
10367       }
10368     }
10369   }
10370 
10371   if (TM.getOptLevel() != CodeGenOpt::None) {
10372     // Here, we order cases by probability so the most likely case will be
10373     // checked first. However, two clusters can have the same probability in
10374     // which case their relative ordering is non-deterministic. So we use Low
10375     // as a tie-breaker as clusters are guaranteed to never overlap.
10376     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10377                [](const CaseCluster &a, const CaseCluster &b) {
10378       return a.Prob != b.Prob ?
10379              a.Prob > b.Prob :
10380              a.Low->getValue().slt(b.Low->getValue());
10381     });
10382 
10383     // Rearrange the case blocks so that the last one falls through if possible
10384     // without changing the order of probabilities.
10385     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10386       --I;
10387       if (I->Prob > W.LastCluster->Prob)
10388         break;
10389       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10390         std::swap(*I, *W.LastCluster);
10391         break;
10392       }
10393     }
10394   }
10395 
10396   // Compute total probability.
10397   BranchProbability DefaultProb = W.DefaultProb;
10398   BranchProbability UnhandledProbs = DefaultProb;
10399   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10400     UnhandledProbs += I->Prob;
10401 
10402   MachineBasicBlock *CurMBB = W.MBB;
10403   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10404     bool FallthroughUnreachable = false;
10405     MachineBasicBlock *Fallthrough;
10406     if (I == W.LastCluster) {
10407       // For the last cluster, fall through to the default destination.
10408       Fallthrough = DefaultMBB;
10409       FallthroughUnreachable = isa<UnreachableInst>(
10410           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10411     } else {
10412       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10413       CurMF->insert(BBI, Fallthrough);
10414       // Put Cond in a virtual register to make it available from the new blocks.
10415       ExportFromCurrentBlock(Cond);
10416     }
10417     UnhandledProbs -= I->Prob;
10418 
10419     switch (I->Kind) {
10420       case CC_JumpTable: {
10421         // FIXME: Optimize away range check based on pivot comparisons.
10422         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10423         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10424 
10425         // The jump block hasn't been inserted yet; insert it here.
10426         MachineBasicBlock *JumpMBB = JT->MBB;
10427         CurMF->insert(BBI, JumpMBB);
10428 
10429         auto JumpProb = I->Prob;
10430         auto FallthroughProb = UnhandledProbs;
10431 
10432         // If the default statement is a target of the jump table, we evenly
10433         // distribute the default probability to successors of CurMBB. Also
10434         // update the probability on the edge from JumpMBB to Fallthrough.
10435         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10436                                               SE = JumpMBB->succ_end();
10437              SI != SE; ++SI) {
10438           if (*SI == DefaultMBB) {
10439             JumpProb += DefaultProb / 2;
10440             FallthroughProb -= DefaultProb / 2;
10441             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10442             JumpMBB->normalizeSuccProbs();
10443             break;
10444           }
10445         }
10446 
10447         if (FallthroughUnreachable) {
10448           // Skip the range check if the fallthrough block is unreachable.
10449           JTH->OmitRangeCheck = true;
10450         }
10451 
10452         if (!JTH->OmitRangeCheck)
10453           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10454         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10455         CurMBB->normalizeSuccProbs();
10456 
10457         // The jump table header will be inserted in our current block, do the
10458         // range check, and fall through to our fallthrough block.
10459         JTH->HeaderBB = CurMBB;
10460         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10461 
10462         // If we're in the right place, emit the jump table header right now.
10463         if (CurMBB == SwitchMBB) {
10464           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10465           JTH->Emitted = true;
10466         }
10467         break;
10468       }
10469       case CC_BitTests: {
10470         // FIXME: Optimize away range check based on pivot comparisons.
10471         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10472 
10473         // The bit test blocks haven't been inserted yet; insert them here.
10474         for (BitTestCase &BTC : BTB->Cases)
10475           CurMF->insert(BBI, BTC.ThisBB);
10476 
10477         // Fill in fields of the BitTestBlock.
10478         BTB->Parent = CurMBB;
10479         BTB->Default = Fallthrough;
10480 
10481         BTB->DefaultProb = UnhandledProbs;
10482         // If the cases in bit test don't form a contiguous range, we evenly
10483         // distribute the probability on the edge to Fallthrough to two
10484         // successors of CurMBB.
10485         if (!BTB->ContiguousRange) {
10486           BTB->Prob += DefaultProb / 2;
10487           BTB->DefaultProb -= DefaultProb / 2;
10488         }
10489 
10490         if (FallthroughUnreachable) {
10491           // Skip the range check if the fallthrough block is unreachable.
10492           BTB->OmitRangeCheck = true;
10493         }
10494 
10495         // If we're in the right place, emit the bit test header right now.
10496         if (CurMBB == SwitchMBB) {
10497           visitBitTestHeader(*BTB, SwitchMBB);
10498           BTB->Emitted = true;
10499         }
10500         break;
10501       }
10502       case CC_Range: {
10503         const Value *RHS, *LHS, *MHS;
10504         ISD::CondCode CC;
10505         if (I->Low == I->High) {
10506           // Check Cond == I->Low.
10507           CC = ISD::SETEQ;
10508           LHS = Cond;
10509           RHS=I->Low;
10510           MHS = nullptr;
10511         } else {
10512           // Check I->Low <= Cond <= I->High.
10513           CC = ISD::SETLE;
10514           LHS = I->Low;
10515           MHS = Cond;
10516           RHS = I->High;
10517         }
10518 
10519         // If Fallthrough is unreachable, fold away the comparison.
10520         if (FallthroughUnreachable)
10521           CC = ISD::SETTRUE;
10522 
10523         // The false probability is the sum of all unhandled cases.
10524         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10525                      getCurSDLoc(), I->Prob, UnhandledProbs);
10526 
10527         if (CurMBB == SwitchMBB)
10528           visitSwitchCase(CB, SwitchMBB);
10529         else
10530           SL->SwitchCases.push_back(CB);
10531 
10532         break;
10533       }
10534     }
10535     CurMBB = Fallthrough;
10536   }
10537 }
10538 
10539 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10540                                               CaseClusterIt First,
10541                                               CaseClusterIt Last) {
10542   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10543     if (X.Prob != CC.Prob)
10544       return X.Prob > CC.Prob;
10545 
10546     // Ties are broken by comparing the case value.
10547     return X.Low->getValue().slt(CC.Low->getValue());
10548   });
10549 }
10550 
10551 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10552                                         const SwitchWorkListItem &W,
10553                                         Value *Cond,
10554                                         MachineBasicBlock *SwitchMBB) {
10555   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10556          "Clusters not sorted?");
10557 
10558   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10559 
10560   // Balance the tree based on branch probabilities to create a near-optimal (in
10561   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10562   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10563   CaseClusterIt LastLeft = W.FirstCluster;
10564   CaseClusterIt FirstRight = W.LastCluster;
10565   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10566   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10567 
10568   // Move LastLeft and FirstRight towards each other from opposite directions to
10569   // find a partitioning of the clusters which balances the probability on both
10570   // sides. If LeftProb and RightProb are equal, alternate which side is
10571   // taken to ensure 0-probability nodes are distributed evenly.
10572   unsigned I = 0;
10573   while (LastLeft + 1 < FirstRight) {
10574     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10575       LeftProb += (++LastLeft)->Prob;
10576     else
10577       RightProb += (--FirstRight)->Prob;
10578     I++;
10579   }
10580 
10581   while (true) {
10582     // Our binary search tree differs from a typical BST in that ours can have up
10583     // to three values in each leaf. The pivot selection above doesn't take that
10584     // into account, which means the tree might require more nodes and be less
10585     // efficient. We compensate for this here.
10586 
10587     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10588     unsigned NumRight = W.LastCluster - FirstRight + 1;
10589 
10590     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10591       // If one side has less than 3 clusters, and the other has more than 3,
10592       // consider taking a cluster from the other side.
10593 
10594       if (NumLeft < NumRight) {
10595         // Consider moving the first cluster on the right to the left side.
10596         CaseCluster &CC = *FirstRight;
10597         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10598         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10599         if (LeftSideRank <= RightSideRank) {
10600           // Moving the cluster to the left does not demote it.
10601           ++LastLeft;
10602           ++FirstRight;
10603           continue;
10604         }
10605       } else {
10606         assert(NumRight < NumLeft);
10607         // Consider moving the last element on the left to the right side.
10608         CaseCluster &CC = *LastLeft;
10609         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10610         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10611         if (RightSideRank <= LeftSideRank) {
10612           // Moving the cluster to the right does not demot it.
10613           --LastLeft;
10614           --FirstRight;
10615           continue;
10616         }
10617       }
10618     }
10619     break;
10620   }
10621 
10622   assert(LastLeft + 1 == FirstRight);
10623   assert(LastLeft >= W.FirstCluster);
10624   assert(FirstRight <= W.LastCluster);
10625 
10626   // Use the first element on the right as pivot since we will make less-than
10627   // comparisons against it.
10628   CaseClusterIt PivotCluster = FirstRight;
10629   assert(PivotCluster > W.FirstCluster);
10630   assert(PivotCluster <= W.LastCluster);
10631 
10632   CaseClusterIt FirstLeft = W.FirstCluster;
10633   CaseClusterIt LastRight = W.LastCluster;
10634 
10635   const ConstantInt *Pivot = PivotCluster->Low;
10636 
10637   // New blocks will be inserted immediately after the current one.
10638   MachineFunction::iterator BBI(W.MBB);
10639   ++BBI;
10640 
10641   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10642   // we can branch to its destination directly if it's squeezed exactly in
10643   // between the known lower bound and Pivot - 1.
10644   MachineBasicBlock *LeftMBB;
10645   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10646       FirstLeft->Low == W.GE &&
10647       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10648     LeftMBB = FirstLeft->MBB;
10649   } else {
10650     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10651     FuncInfo.MF->insert(BBI, LeftMBB);
10652     WorkList.push_back(
10653         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10654     // Put Cond in a virtual register to make it available from the new blocks.
10655     ExportFromCurrentBlock(Cond);
10656   }
10657 
10658   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10659   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10660   // directly if RHS.High equals the current upper bound.
10661   MachineBasicBlock *RightMBB;
10662   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10663       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10664     RightMBB = FirstRight->MBB;
10665   } else {
10666     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10667     FuncInfo.MF->insert(BBI, RightMBB);
10668     WorkList.push_back(
10669         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10670     // Put Cond in a virtual register to make it available from the new blocks.
10671     ExportFromCurrentBlock(Cond);
10672   }
10673 
10674   // Create the CaseBlock record that will be used to lower the branch.
10675   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10676                getCurSDLoc(), LeftProb, RightProb);
10677 
10678   if (W.MBB == SwitchMBB)
10679     visitSwitchCase(CB, SwitchMBB);
10680   else
10681     SL->SwitchCases.push_back(CB);
10682 }
10683 
10684 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10685 // from the swith statement.
10686 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10687                                             BranchProbability PeeledCaseProb) {
10688   if (PeeledCaseProb == BranchProbability::getOne())
10689     return BranchProbability::getZero();
10690   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10691 
10692   uint32_t Numerator = CaseProb.getNumerator();
10693   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10694   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10695 }
10696 
10697 // Try to peel the top probability case if it exceeds the threshold.
10698 // Return current MachineBasicBlock for the switch statement if the peeling
10699 // does not occur.
10700 // If the peeling is performed, return the newly created MachineBasicBlock
10701 // for the peeled switch statement. Also update Clusters to remove the peeled
10702 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10703 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10704     const SwitchInst &SI, CaseClusterVector &Clusters,
10705     BranchProbability &PeeledCaseProb) {
10706   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10707   // Don't perform if there is only one cluster or optimizing for size.
10708   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10709       TM.getOptLevel() == CodeGenOpt::None ||
10710       SwitchMBB->getParent()->getFunction().hasMinSize())
10711     return SwitchMBB;
10712 
10713   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10714   unsigned PeeledCaseIndex = 0;
10715   bool SwitchPeeled = false;
10716   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10717     CaseCluster &CC = Clusters[Index];
10718     if (CC.Prob < TopCaseProb)
10719       continue;
10720     TopCaseProb = CC.Prob;
10721     PeeledCaseIndex = Index;
10722     SwitchPeeled = true;
10723   }
10724   if (!SwitchPeeled)
10725     return SwitchMBB;
10726 
10727   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10728                     << TopCaseProb << "\n");
10729 
10730   // Record the MBB for the peeled switch statement.
10731   MachineFunction::iterator BBI(SwitchMBB);
10732   ++BBI;
10733   MachineBasicBlock *PeeledSwitchMBB =
10734       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10735   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10736 
10737   ExportFromCurrentBlock(SI.getCondition());
10738   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10739   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10740                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10741   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10742 
10743   Clusters.erase(PeeledCaseIt);
10744   for (CaseCluster &CC : Clusters) {
10745     LLVM_DEBUG(
10746         dbgs() << "Scale the probablity for one cluster, before scaling: "
10747                << CC.Prob << "\n");
10748     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10749     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10750   }
10751   PeeledCaseProb = TopCaseProb;
10752   return PeeledSwitchMBB;
10753 }
10754 
10755 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10756   // Extract cases from the switch.
10757   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10758   CaseClusterVector Clusters;
10759   Clusters.reserve(SI.getNumCases());
10760   for (auto I : SI.cases()) {
10761     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10762     const ConstantInt *CaseVal = I.getCaseValue();
10763     BranchProbability Prob =
10764         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10765             : BranchProbability(1, SI.getNumCases() + 1);
10766     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10767   }
10768 
10769   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10770 
10771   // Cluster adjacent cases with the same destination. We do this at all
10772   // optimization levels because it's cheap to do and will make codegen faster
10773   // if there are many clusters.
10774   sortAndRangeify(Clusters);
10775 
10776   // The branch probablity of the peeled case.
10777   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10778   MachineBasicBlock *PeeledSwitchMBB =
10779       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10780 
10781   // If there is only the default destination, jump there directly.
10782   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10783   if (Clusters.empty()) {
10784     assert(PeeledSwitchMBB == SwitchMBB);
10785     SwitchMBB->addSuccessor(DefaultMBB);
10786     if (DefaultMBB != NextBlock(SwitchMBB)) {
10787       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10788                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10789     }
10790     return;
10791   }
10792 
10793   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10794   SL->findBitTestClusters(Clusters, &SI);
10795 
10796   LLVM_DEBUG({
10797     dbgs() << "Case clusters: ";
10798     for (const CaseCluster &C : Clusters) {
10799       if (C.Kind == CC_JumpTable)
10800         dbgs() << "JT:";
10801       if (C.Kind == CC_BitTests)
10802         dbgs() << "BT:";
10803 
10804       C.Low->getValue().print(dbgs(), true);
10805       if (C.Low != C.High) {
10806         dbgs() << '-';
10807         C.High->getValue().print(dbgs(), true);
10808       }
10809       dbgs() << ' ';
10810     }
10811     dbgs() << '\n';
10812   });
10813 
10814   assert(!Clusters.empty());
10815   SwitchWorkList WorkList;
10816   CaseClusterIt First = Clusters.begin();
10817   CaseClusterIt Last = Clusters.end() - 1;
10818   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10819   // Scale the branchprobability for DefaultMBB if the peel occurs and
10820   // DefaultMBB is not replaced.
10821   if (PeeledCaseProb != BranchProbability::getZero() &&
10822       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10823     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10824   WorkList.push_back(
10825       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10826 
10827   while (!WorkList.empty()) {
10828     SwitchWorkListItem W = WorkList.pop_back_val();
10829     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10830 
10831     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10832         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10833       // For optimized builds, lower large range as a balanced binary tree.
10834       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10835       continue;
10836     }
10837 
10838     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10839   }
10840 }
10841 
10842 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
10843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10844   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10845 
10846   SDLoc DL = getCurSDLoc();
10847   SDValue V = getValue(I.getOperand(0));
10848   assert(VT == V.getValueType() && "Malformed vector.reverse!");
10849 
10850   if (VT.isScalableVector()) {
10851     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
10852     return;
10853   }
10854 
10855   // Use VECTOR_SHUFFLE for the fixed-length vector
10856   // to maintain existing behavior.
10857   SmallVector<int, 8> Mask;
10858   unsigned NumElts = VT.getVectorMinNumElements();
10859   for (unsigned i = 0; i != NumElts; ++i)
10860     Mask.push_back(NumElts - 1 - i);
10861 
10862   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
10863 }
10864 
10865 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10866   SmallVector<EVT, 4> ValueVTs;
10867   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
10868                   ValueVTs);
10869   unsigned NumValues = ValueVTs.size();
10870   if (NumValues == 0) return;
10871 
10872   SmallVector<SDValue, 4> Values(NumValues);
10873   SDValue Op = getValue(I.getOperand(0));
10874 
10875   for (unsigned i = 0; i != NumValues; ++i)
10876     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
10877                             SDValue(Op.getNode(), Op.getResNo() + i));
10878 
10879   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10880                            DAG.getVTList(ValueVTs), Values));
10881 }
10882