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