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