xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 6e561d1c94edc2ecaab7b79f6b3f1a06f515d531)
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/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/Analysis/AliasAnalysis.h"
30 #include "llvm/Analysis/BlockFrequencyInfo.h"
31 #include "llvm/Analysis/BranchProbabilityInfo.h"
32 #include "llvm/Analysis/ConstantFolding.h"
33 #include "llvm/Analysis/EHPersonalities.h"
34 #include "llvm/Analysis/Loads.h"
35 #include "llvm/Analysis/MemoryLocation.h"
36 #include "llvm/Analysis/ProfileSummaryInfo.h"
37 #include "llvm/Analysis/TargetLibraryInfo.h"
38 #include "llvm/Analysis/ValueTracking.h"
39 #include "llvm/Analysis/VectorUtils.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/FunctionLoweringInfo.h"
42 #include "llvm/CodeGen/GCMetadata.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineJumpTableInfo.h"
50 #include "llvm/CodeGen/MachineMemOperand.h"
51 #include "llvm/CodeGen/MachineModuleInfo.h"
52 #include "llvm/CodeGen/MachineOperand.h"
53 #include "llvm/CodeGen/MachineRegisterInfo.h"
54 #include "llvm/CodeGen/RuntimeLibcalls.h"
55 #include "llvm/CodeGen/SelectionDAG.h"
56 #include "llvm/CodeGen/SelectionDAGNodes.h"
57 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
58 #include "llvm/CodeGen/StackMaps.h"
59 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
60 #include "llvm/CodeGen/TargetFrameLowering.h"
61 #include "llvm/CodeGen/TargetInstrInfo.h"
62 #include "llvm/CodeGen/TargetLowering.h"
63 #include "llvm/CodeGen/TargetOpcodes.h"
64 #include "llvm/CodeGen/TargetRegisterInfo.h"
65 #include "llvm/CodeGen/TargetSubtargetInfo.h"
66 #include "llvm/CodeGen/ValueTypes.h"
67 #include "llvm/CodeGen/WinEHFuncInfo.h"
68 #include "llvm/IR/Argument.h"
69 #include "llvm/IR/Attributes.h"
70 #include "llvm/IR/BasicBlock.h"
71 #include "llvm/IR/CFG.h"
72 #include "llvm/IR/CallSite.h"
73 #include "llvm/IR/CallingConv.h"
74 #include "llvm/IR/Constant.h"
75 #include "llvm/IR/ConstantRange.h"
76 #include "llvm/IR/Constants.h"
77 #include "llvm/IR/DataLayout.h"
78 #include "llvm/IR/DebugInfoMetadata.h"
79 #include "llvm/IR/DebugLoc.h"
80 #include "llvm/IR/DerivedTypes.h"
81 #include "llvm/IR/Function.h"
82 #include "llvm/IR/GetElementPtrTypeIterator.h"
83 #include "llvm/IR/InlineAsm.h"
84 #include "llvm/IR/InstrTypes.h"
85 #include "llvm/IR/Instruction.h"
86 #include "llvm/IR/Instructions.h"
87 #include "llvm/IR/IntrinsicInst.h"
88 #include "llvm/IR/Intrinsics.h"
89 #include "llvm/IR/IntrinsicsAArch64.h"
90 #include "llvm/IR/IntrinsicsWebAssembly.h"
91 #include "llvm/IR/LLVMContext.h"
92 #include "llvm/IR/Metadata.h"
93 #include "llvm/IR/Module.h"
94 #include "llvm/IR/Operator.h"
95 #include "llvm/IR/PatternMatch.h"
96 #include "llvm/IR/Statepoint.h"
97 #include "llvm/IR/Type.h"
98 #include "llvm/IR/User.h"
99 #include "llvm/IR/Value.h"
100 #include "llvm/MC/MCContext.h"
101 #include "llvm/MC/MCSymbol.h"
102 #include "llvm/Support/AtomicOrdering.h"
103 #include "llvm/Support/BranchProbability.h"
104 #include "llvm/Support/Casting.h"
105 #include "llvm/Support/CodeGen.h"
106 #include "llvm/Support/CommandLine.h"
107 #include "llvm/Support/Compiler.h"
108 #include "llvm/Support/Debug.h"
109 #include "llvm/Support/ErrorHandling.h"
110 #include "llvm/Support/MachineValueType.h"
111 #include "llvm/Support/MathExtras.h"
112 #include "llvm/Support/raw_ostream.h"
113 #include "llvm/Target/TargetIntrinsicInfo.h"
114 #include "llvm/Target/TargetMachine.h"
115 #include "llvm/Target/TargetOptions.h"
116 #include "llvm/Transforms/Utils/Local.h"
117 #include <algorithm>
118 #include <cassert>
119 #include <cstddef>
120 #include <cstdint>
121 #include <cstring>
122 #include <iterator>
123 #include <limits>
124 #include <numeric>
125 #include <tuple>
126 #include <utility>
127 #include <vector>
128 
129 using namespace llvm;
130 using namespace PatternMatch;
131 using namespace SwitchCG;
132 
133 #define DEBUG_TYPE "isel"
134 
135 /// LimitFloatPrecision - Generate low-precision inline sequences for
136 /// some float libcalls (6, 8 or 12 bits).
137 static unsigned LimitFloatPrecision;
138 
139 static cl::opt<unsigned, true>
140     LimitFPPrecision("limit-float-precision",
141                      cl::desc("Generate low-precision inline sequences "
142                               "for some float libcalls"),
143                      cl::location(LimitFloatPrecision), cl::Hidden,
144                      cl::init(0));
145 
146 static cl::opt<unsigned> SwitchPeelThreshold(
147     "switch-peel-threshold", cl::Hidden, cl::init(66),
148     cl::desc("Set the case probability threshold for peeling the case from a "
149              "switch statement. A value greater than 100 will void this "
150              "optimization"));
151 
152 // Limit the width of DAG chains. This is important in general to prevent
153 // DAG-based analysis from blowing up. For example, alias analysis and
154 // load clustering may not complete in reasonable time. It is difficult to
155 // recognize and avoid this situation within each individual analysis, and
156 // future analyses are likely to have the same behavior. Limiting DAG width is
157 // the safe approach and will be especially important with global DAGs.
158 //
159 // MaxParallelChains default is arbitrarily high to avoid affecting
160 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
161 // sequence over this should have been converted to llvm.memcpy by the
162 // frontend. It is easy to induce this behavior with .ll code such as:
163 // %buffer = alloca [4096 x i8]
164 // %data = load [4096 x i8]* %argPtr
165 // store [4096 x i8] %data, [4096 x i8]* %buffer
166 static const unsigned MaxParallelChains = 64;
167 
168 // Return the calling convention if the Value passed requires ABI mangling as it
169 // is a parameter to a function or a return value from a function which is not
170 // an intrinsic.
171 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
172   if (auto *R = dyn_cast<ReturnInst>(V))
173     return R->getParent()->getParent()->getCallingConv();
174 
175   if (auto *CI = dyn_cast<CallInst>(V)) {
176     const bool IsInlineAsm = CI->isInlineAsm();
177     const bool IsIndirectFunctionCall =
178         !IsInlineAsm && !CI->getCalledFunction();
179 
180     // It is possible that the call instruction is an inline asm statement or an
181     // indirect function call in which case the return value of
182     // getCalledFunction() would be nullptr.
183     const bool IsInstrinsicCall =
184         !IsInlineAsm && !IsIndirectFunctionCall &&
185         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
186 
187     if (!IsInlineAsm && !IsInstrinsicCall)
188       return CI->getCallingConv();
189   }
190 
191   return None;
192 }
193 
194 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
195                                       const SDValue *Parts, unsigned NumParts,
196                                       MVT PartVT, EVT ValueVT, const Value *V,
197                                       Optional<CallingConv::ID> CC);
198 
199 /// getCopyFromParts - Create a value that contains the specified legal parts
200 /// combined into the value they represent.  If the parts combine to a type
201 /// larger than ValueVT then AssertOp can be used to specify whether the extra
202 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
203 /// (ISD::AssertSext).
204 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
205                                 const SDValue *Parts, unsigned NumParts,
206                                 MVT PartVT, EVT ValueVT, const Value *V,
207                                 Optional<CallingConv::ID> CC = None,
208                                 Optional<ISD::NodeType> AssertOp = None) {
209   if (ValueVT.isVector())
210     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
211                                   CC);
212 
213   assert(NumParts > 0 && "No parts to assemble!");
214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
215   SDValue Val = Parts[0];
216 
217   if (NumParts > 1) {
218     // Assemble the value from multiple parts.
219     if (ValueVT.isInteger()) {
220       unsigned PartBits = PartVT.getSizeInBits();
221       unsigned ValueBits = ValueVT.getSizeInBits();
222 
223       // Assemble the power of 2 part.
224       unsigned RoundParts =
225           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
226       unsigned RoundBits = PartBits * RoundParts;
227       EVT RoundVT = RoundBits == ValueBits ?
228         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
229       SDValue Lo, Hi;
230 
231       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
232 
233       if (RoundParts > 2) {
234         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
235                               PartVT, HalfVT, V);
236         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
237                               RoundParts / 2, PartVT, HalfVT, V);
238       } else {
239         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
240         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
241       }
242 
243       if (DAG.getDataLayout().isBigEndian())
244         std::swap(Lo, Hi);
245 
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
247 
248       if (RoundParts < NumParts) {
249         // Assemble the trailing non-power-of-2 part.
250         unsigned OddParts = NumParts - RoundParts;
251         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
252         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
253                               OddVT, V, CC);
254 
255         // Combine the round and odd parts.
256         Lo = Val;
257         if (DAG.getDataLayout().isBigEndian())
258           std::swap(Lo, Hi);
259         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
260         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
261         Hi =
262             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
263                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
264                                         TLI.getPointerTy(DAG.getDataLayout())));
265         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
266         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
267       }
268     } else if (PartVT.isFloatingPoint()) {
269       // FP split into multiple FP parts (for ppcf128)
270       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
271              "Unexpected split");
272       SDValue Lo, Hi;
273       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
274       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
275       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
276         std::swap(Lo, Hi);
277       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
278     } else {
279       // FP split into integer parts (soft fp)
280       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
281              !PartVT.isVector() && "Unexpected split");
282       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
283       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
284     }
285   }
286 
287   // There is now one part, held in Val.  Correct it to match ValueVT.
288   // PartEVT is the type of the register class that holds the value.
289   // ValueVT is the type of the inline asm operation.
290   EVT PartEVT = Val.getValueType();
291 
292   if (PartEVT == ValueVT)
293     return Val;
294 
295   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
296       ValueVT.bitsLT(PartEVT)) {
297     // For an FP value in an integer part, we need to truncate to the right
298     // width first.
299     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
300     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
301   }
302 
303   // Handle types that have the same size.
304   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
305     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
306 
307   // Handle types with different sizes.
308   if (PartEVT.isInteger() && ValueVT.isInteger()) {
309     if (ValueVT.bitsLT(PartEVT)) {
310       // For a truncate, see if we have any information to
311       // indicate whether the truncated bits will always be
312       // zero or sign-extension.
313       if (AssertOp.hasValue())
314         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
315                           DAG.getValueType(ValueVT));
316       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317     }
318     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
319   }
320 
321   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
322     // FP_ROUND's are always exact here.
323     if (ValueVT.bitsLT(Val.getValueType()))
324       return DAG.getNode(
325           ISD::FP_ROUND, DL, ValueVT, Val,
326           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
327 
328     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
329   }
330 
331   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
332   // then truncating.
333   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
334       ValueVT.bitsLT(PartEVT)) {
335     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
336     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
337   }
338 
339   report_fatal_error("Unknown mismatch in getCopyFromParts!");
340 }
341 
342 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
343                                               const Twine &ErrMsg) {
344   const Instruction *I = dyn_cast_or_null<Instruction>(V);
345   if (!V)
346     return Ctx.emitError(ErrMsg);
347 
348   const char *AsmError = ", possible invalid constraint for vector type";
349   if (const CallInst *CI = dyn_cast<CallInst>(I))
350     if (isa<InlineAsm>(CI->getCalledValue()))
351       return Ctx.emitError(I, ErrMsg + AsmError);
352 
353   return Ctx.emitError(I, ErrMsg);
354 }
355 
356 /// getCopyFromPartsVector - Create a value that contains the specified legal
357 /// parts combined into the value they represent.  If the parts combine to a
358 /// type larger than ValueVT then AssertOp can be used to specify whether the
359 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
360 /// ValueVT (ISD::AssertSext).
361 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
362                                       const SDValue *Parts, unsigned NumParts,
363                                       MVT PartVT, EVT ValueVT, const Value *V,
364                                       Optional<CallingConv::ID> CallConv) {
365   assert(ValueVT.isVector() && "Not a vector value");
366   assert(NumParts > 0 && "No parts to assemble!");
367   const bool IsABIRegCopy = CallConv.hasValue();
368 
369   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
370   SDValue Val = Parts[0];
371 
372   // Handle a multi-element vector.
373   if (NumParts > 1) {
374     EVT IntermediateVT;
375     MVT RegisterVT;
376     unsigned NumIntermediates;
377     unsigned NumRegs;
378 
379     if (IsABIRegCopy) {
380       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
381           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
382           NumIntermediates, RegisterVT);
383     } else {
384       NumRegs =
385           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
386                                      NumIntermediates, RegisterVT);
387     }
388 
389     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
390     NumParts = NumRegs; // Silence a compiler warning.
391     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
392     assert(RegisterVT.getSizeInBits() ==
393            Parts[0].getSimpleValueType().getSizeInBits() &&
394            "Part type sizes don't match!");
395 
396     // Assemble the parts into intermediate operands.
397     SmallVector<SDValue, 8> Ops(NumIntermediates);
398     if (NumIntermediates == NumParts) {
399       // If the register was not expanded, truncate or copy the value,
400       // as appropriate.
401       for (unsigned i = 0; i != NumParts; ++i)
402         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
403                                   PartVT, IntermediateVT, V);
404     } else if (NumParts > 0) {
405       // If the intermediate type was expanded, build the intermediate
406       // operands from the parts.
407       assert(NumParts % NumIntermediates == 0 &&
408              "Must expand into a divisible number of parts!");
409       unsigned Factor = NumParts / NumIntermediates;
410       for (unsigned i = 0; i != NumIntermediates; ++i)
411         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
412                                   PartVT, IntermediateVT, V);
413     }
414 
415     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
416     // intermediate operands.
417     EVT BuiltVectorTy =
418         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
419                          (IntermediateVT.isVector()
420                               ? IntermediateVT.getVectorNumElements() * NumParts
421                               : NumIntermediates));
422     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
423                                                 : ISD::BUILD_VECTOR,
424                       DL, BuiltVectorTy, Ops);
425   }
426 
427   // There is now one part, held in Val.  Correct it to match ValueVT.
428   EVT PartEVT = Val.getValueType();
429 
430   if (PartEVT == ValueVT)
431     return Val;
432 
433   if (PartEVT.isVector()) {
434     // If the element type of the source/dest vectors are the same, but the
435     // parts vector has more elements than the value vector, then we have a
436     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
437     // elements we want.
438     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
439       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
440              "Cannot narrow, it would be a lossy transformation");
441       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
442                          DAG.getVectorIdxConstant(0, DL));
443     }
444 
445     // Vector/Vector bitcast.
446     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
447       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
448 
449     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
450       "Cannot handle this kind of promotion");
451     // Promoted vector extract
452     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
453 
454   }
455 
456   // Trivial bitcast if the types are the same size and the destination
457   // vector type is legal.
458   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
459       TLI.isTypeLegal(ValueVT))
460     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
461 
462   if (ValueVT.getVectorNumElements() != 1) {
463      // Certain ABIs require that vectors are passed as integers. For vectors
464      // are the same size, this is an obvious bitcast.
465      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
466        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
467      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
468        // Bitcast Val back the original type and extract the corresponding
469        // vector we want.
470        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
471        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
472                                            ValueVT.getVectorElementType(), Elts);
473        Val = DAG.getBitcast(WiderVecType, Val);
474        return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
475                           DAG.getVectorIdxConstant(0, DL));
476      }
477 
478      diagnosePossiblyInvalidConstraint(
479          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
480      return DAG.getUNDEF(ValueVT);
481   }
482 
483   // Handle cases such as i8 -> <1 x i1>
484   EVT ValueSVT = ValueVT.getVectorElementType();
485   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
486     if (ValueSVT.getSizeInBits() == PartEVT.getSizeInBits())
487       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
488     else
489       Val = ValueVT.isFloatingPoint()
490                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
491                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
492   }
493 
494   return DAG.getBuildVector(ValueVT, DL, Val);
495 }
496 
497 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
498                                  SDValue Val, SDValue *Parts, unsigned NumParts,
499                                  MVT PartVT, const Value *V,
500                                  Optional<CallingConv::ID> CallConv);
501 
502 /// getCopyToParts - Create a series of nodes that contain the specified value
503 /// split into legal parts.  If the parts contain more bits than Val, then, for
504 /// integers, ExtendKind can be used to specify how to generate the extra bits.
505 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
506                            SDValue *Parts, unsigned NumParts, MVT PartVT,
507                            const Value *V,
508                            Optional<CallingConv::ID> CallConv = None,
509                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
510   EVT ValueVT = Val.getValueType();
511 
512   // Handle the vector case separately.
513   if (ValueVT.isVector())
514     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
515                                 CallConv);
516 
517   unsigned PartBits = PartVT.getSizeInBits();
518   unsigned OrigNumParts = NumParts;
519   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
520          "Copying to an illegal type!");
521 
522   if (NumParts == 0)
523     return;
524 
525   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
526   EVT PartEVT = PartVT;
527   if (PartEVT == ValueVT) {
528     assert(NumParts == 1 && "No-op copy with multiple parts!");
529     Parts[0] = Val;
530     return;
531   }
532 
533   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
534     // If the parts cover more bits than the value has, promote the value.
535     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
536       assert(NumParts == 1 && "Do not know what to promote to!");
537       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
538     } else {
539       if (ValueVT.isFloatingPoint()) {
540         // FP values need to be bitcast, then extended if they are being put
541         // into a larger container.
542         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
543         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
544       }
545       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
546              ValueVT.isInteger() &&
547              "Unknown mismatch!");
548       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
549       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
550       if (PartVT == MVT::x86mmx)
551         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
552     }
553   } else if (PartBits == ValueVT.getSizeInBits()) {
554     // Different types of the same size.
555     assert(NumParts == 1 && PartEVT != ValueVT);
556     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
557   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
558     // If the parts cover less bits than value has, truncate the value.
559     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
560            ValueVT.isInteger() &&
561            "Unknown mismatch!");
562     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
563     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
564     if (PartVT == MVT::x86mmx)
565       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
566   }
567 
568   // The value may have changed - recompute ValueVT.
569   ValueVT = Val.getValueType();
570   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
571          "Failed to tile the value with PartVT!");
572 
573   if (NumParts == 1) {
574     if (PartEVT != ValueVT) {
575       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
576                                         "scalar-to-vector conversion failed");
577       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
578     }
579 
580     Parts[0] = Val;
581     return;
582   }
583 
584   // Expand the value into multiple parts.
585   if (NumParts & (NumParts - 1)) {
586     // The number of parts is not a power of 2.  Split off and copy the tail.
587     assert(PartVT.isInteger() && ValueVT.isInteger() &&
588            "Do not know what to expand to!");
589     unsigned RoundParts = 1 << Log2_32(NumParts);
590     unsigned RoundBits = RoundParts * PartBits;
591     unsigned OddParts = NumParts - RoundParts;
592     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
593       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
594 
595     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
596                    CallConv);
597 
598     if (DAG.getDataLayout().isBigEndian())
599       // The odd parts were reversed by getCopyToParts - unreverse them.
600       std::reverse(Parts + RoundParts, Parts + NumParts);
601 
602     NumParts = RoundParts;
603     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
604     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
605   }
606 
607   // The number of parts is a power of 2.  Repeatedly bisect the value using
608   // EXTRACT_ELEMENT.
609   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
610                          EVT::getIntegerVT(*DAG.getContext(),
611                                            ValueVT.getSizeInBits()),
612                          Val);
613 
614   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
615     for (unsigned i = 0; i < NumParts; i += StepSize) {
616       unsigned ThisBits = StepSize * PartBits / 2;
617       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
618       SDValue &Part0 = Parts[i];
619       SDValue &Part1 = Parts[i+StepSize/2];
620 
621       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
622                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
623       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
624                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
625 
626       if (ThisBits == PartBits && ThisVT != PartVT) {
627         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
628         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
629       }
630     }
631   }
632 
633   if (DAG.getDataLayout().isBigEndian())
634     std::reverse(Parts, Parts + OrigNumParts);
635 }
636 
637 static SDValue widenVectorToPartType(SelectionDAG &DAG,
638                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
639   if (!PartVT.isVector())
640     return SDValue();
641 
642   EVT ValueVT = Val.getValueType();
643   unsigned PartNumElts = PartVT.getVectorNumElements();
644   unsigned ValueNumElts = ValueVT.getVectorNumElements();
645   if (PartNumElts > ValueNumElts &&
646       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
647     EVT ElementVT = PartVT.getVectorElementType();
648     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
649     // undef elements.
650     SmallVector<SDValue, 16> Ops;
651     DAG.ExtractVectorElements(Val, Ops);
652     SDValue EltUndef = DAG.getUNDEF(ElementVT);
653     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
654       Ops.push_back(EltUndef);
655 
656     // FIXME: Use CONCAT for 2x -> 4x.
657     return DAG.getBuildVector(PartVT, DL, Ops);
658   }
659 
660   return SDValue();
661 }
662 
663 /// getCopyToPartsVector - Create a series of nodes that contain the specified
664 /// value split into legal parts.
665 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
666                                  SDValue Val, SDValue *Parts, unsigned NumParts,
667                                  MVT PartVT, const Value *V,
668                                  Optional<CallingConv::ID> CallConv) {
669   EVT ValueVT = Val.getValueType();
670   assert(ValueVT.isVector() && "Not a vector");
671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
672   const bool IsABIRegCopy = CallConv.hasValue();
673 
674   if (NumParts == 1) {
675     EVT PartEVT = PartVT;
676     if (PartEVT == ValueVT) {
677       // Nothing to do.
678     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
679       // Bitconvert vector->vector case.
680       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
681     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
682       Val = Widened;
683     } else if (PartVT.isVector() &&
684                PartEVT.getVectorElementType().bitsGE(
685                  ValueVT.getVectorElementType()) &&
686                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
687 
688       // Promoted vector extract
689       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
690     } else {
691       if (ValueVT.getVectorNumElements() == 1) {
692         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
693                           DAG.getVectorIdxConstant(0, DL));
694       } else {
695         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
696                "lossy conversion of vector to scalar type");
697         EVT IntermediateType =
698             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
699         Val = DAG.getBitcast(IntermediateType, Val);
700         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
701       }
702     }
703 
704     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
705     Parts[0] = Val;
706     return;
707   }
708 
709   // Handle a multi-element vector.
710   EVT IntermediateVT;
711   MVT RegisterVT;
712   unsigned NumIntermediates;
713   unsigned NumRegs;
714   if (IsABIRegCopy) {
715     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
716         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
717         NumIntermediates, RegisterVT);
718   } else {
719     NumRegs =
720         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
721                                    NumIntermediates, RegisterVT);
722   }
723 
724   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
725   NumParts = NumRegs; // Silence a compiler warning.
726   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
727 
728   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
729     IntermediateVT.getVectorNumElements() : 1;
730 
731   // Convert the vector to the appropriate type if necessary.
732   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
733 
734   EVT BuiltVectorTy = EVT::getVectorVT(
735       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
736   if (ValueVT != BuiltVectorTy) {
737     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
738       Val = Widened;
739 
740     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
741   }
742 
743   // Split the vector into intermediate operands.
744   SmallVector<SDValue, 8> Ops(NumIntermediates);
745   for (unsigned i = 0; i != NumIntermediates; ++i) {
746     if (IntermediateVT.isVector()) {
747       Ops[i] =
748           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
749                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
750     } else {
751       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
752                            DAG.getVectorIdxConstant(i, DL));
753     }
754   }
755 
756   // Split the intermediate operands into legal parts.
757   if (NumParts == NumIntermediates) {
758     // If the register was not expanded, promote or copy the value,
759     // as appropriate.
760     for (unsigned i = 0; i != NumParts; ++i)
761       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
762   } else if (NumParts > 0) {
763     // If the intermediate type was expanded, split each the value into
764     // legal parts.
765     assert(NumIntermediates != 0 && "division by zero");
766     assert(NumParts % NumIntermediates == 0 &&
767            "Must expand into a divisible number of parts!");
768     unsigned Factor = NumParts / NumIntermediates;
769     for (unsigned i = 0; i != NumIntermediates; ++i)
770       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
771                      CallConv);
772   }
773 }
774 
775 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
776                            EVT valuevt, Optional<CallingConv::ID> CC)
777     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
778       RegCount(1, regs.size()), CallConv(CC) {}
779 
780 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
781                            const DataLayout &DL, unsigned Reg, Type *Ty,
782                            Optional<CallingConv::ID> CC) {
783   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
784 
785   CallConv = CC;
786 
787   for (EVT ValueVT : ValueVTs) {
788     unsigned NumRegs =
789         isABIMangled()
790             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
791             : TLI.getNumRegisters(Context, ValueVT);
792     MVT RegisterVT =
793         isABIMangled()
794             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
795             : TLI.getRegisterType(Context, ValueVT);
796     for (unsigned i = 0; i != NumRegs; ++i)
797       Regs.push_back(Reg + i);
798     RegVTs.push_back(RegisterVT);
799     RegCount.push_back(NumRegs);
800     Reg += NumRegs;
801   }
802 }
803 
804 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
805                                       FunctionLoweringInfo &FuncInfo,
806                                       const SDLoc &dl, SDValue &Chain,
807                                       SDValue *Flag, const Value *V) const {
808   // A Value with type {} or [0 x %t] needs no registers.
809   if (ValueVTs.empty())
810     return SDValue();
811 
812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
813 
814   // Assemble the legal parts into the final values.
815   SmallVector<SDValue, 4> Values(ValueVTs.size());
816   SmallVector<SDValue, 8> Parts;
817   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
818     // Copy the legal parts from the registers.
819     EVT ValueVT = ValueVTs[Value];
820     unsigned NumRegs = RegCount[Value];
821     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
822                                           *DAG.getContext(),
823                                           CallConv.getValue(), RegVTs[Value])
824                                     : RegVTs[Value];
825 
826     Parts.resize(NumRegs);
827     for (unsigned i = 0; i != NumRegs; ++i) {
828       SDValue P;
829       if (!Flag) {
830         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
831       } else {
832         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
833         *Flag = P.getValue(2);
834       }
835 
836       Chain = P.getValue(1);
837       Parts[i] = P;
838 
839       // If the source register was virtual and if we know something about it,
840       // add an assert node.
841       if (!Register::isVirtualRegister(Regs[Part + i]) ||
842           !RegisterVT.isInteger())
843         continue;
844 
845       const FunctionLoweringInfo::LiveOutInfo *LOI =
846         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
847       if (!LOI)
848         continue;
849 
850       unsigned RegSize = RegisterVT.getScalarSizeInBits();
851       unsigned NumSignBits = LOI->NumSignBits;
852       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
853 
854       if (NumZeroBits == RegSize) {
855         // The current value is a zero.
856         // Explicitly express that as it would be easier for
857         // optimizations to kick in.
858         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
859         continue;
860       }
861 
862       // FIXME: We capture more information than the dag can represent.  For
863       // now, just use the tightest assertzext/assertsext possible.
864       bool isSExt;
865       EVT FromVT(MVT::Other);
866       if (NumZeroBits) {
867         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
868         isSExt = false;
869       } else if (NumSignBits > 1) {
870         FromVT =
871             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
872         isSExt = true;
873       } else {
874         continue;
875       }
876       // Add an assertion node.
877       assert(FromVT != MVT::Other);
878       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
879                              RegisterVT, P, DAG.getValueType(FromVT));
880     }
881 
882     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
883                                      RegisterVT, ValueVT, V, CallConv);
884     Part += NumRegs;
885     Parts.clear();
886   }
887 
888   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
889 }
890 
891 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
892                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
893                                  const Value *V,
894                                  ISD::NodeType PreferredExtendType) const {
895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
896   ISD::NodeType ExtendKind = PreferredExtendType;
897 
898   // Get the list of the values's legal parts.
899   unsigned NumRegs = Regs.size();
900   SmallVector<SDValue, 8> Parts(NumRegs);
901   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
902     unsigned NumParts = RegCount[Value];
903 
904     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
905                                           *DAG.getContext(),
906                                           CallConv.getValue(), RegVTs[Value])
907                                     : RegVTs[Value];
908 
909     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
910       ExtendKind = ISD::ZERO_EXTEND;
911 
912     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
913                    NumParts, RegisterVT, V, CallConv, ExtendKind);
914     Part += NumParts;
915   }
916 
917   // Copy the parts into the registers.
918   SmallVector<SDValue, 8> Chains(NumRegs);
919   for (unsigned i = 0; i != NumRegs; ++i) {
920     SDValue Part;
921     if (!Flag) {
922       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
923     } else {
924       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
925       *Flag = Part.getValue(1);
926     }
927 
928     Chains[i] = Part.getValue(0);
929   }
930 
931   if (NumRegs == 1 || Flag)
932     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
933     // flagged to it. That is the CopyToReg nodes and the user are considered
934     // a single scheduling unit. If we create a TokenFactor and return it as
935     // chain, then the TokenFactor is both a predecessor (operand) of the
936     // user as well as a successor (the TF operands are flagged to the user).
937     // c1, f1 = CopyToReg
938     // c2, f2 = CopyToReg
939     // c3     = TokenFactor c1, c2
940     // ...
941     //        = op c3, ..., f2
942     Chain = Chains[NumRegs-1];
943   else
944     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
945 }
946 
947 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
948                                         unsigned MatchingIdx, const SDLoc &dl,
949                                         SelectionDAG &DAG,
950                                         std::vector<SDValue> &Ops) const {
951   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
952 
953   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
954   if (HasMatching)
955     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
956   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
957     // Put the register class of the virtual registers in the flag word.  That
958     // way, later passes can recompute register class constraints for inline
959     // assembly as well as normal instructions.
960     // Don't do this for tied operands that can use the regclass information
961     // from the def.
962     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
963     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
964     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
965   }
966 
967   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
968   Ops.push_back(Res);
969 
970   if (Code == InlineAsm::Kind_Clobber) {
971     // Clobbers should always have a 1:1 mapping with registers, and may
972     // reference registers that have illegal (e.g. vector) types. Hence, we
973     // shouldn't try to apply any sort of splitting logic to them.
974     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
975            "No 1:1 mapping from clobbers to regs?");
976     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
977     (void)SP;
978     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
979       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
980       assert(
981           (Regs[I] != SP ||
982            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
983           "If we clobbered the stack pointer, MFI should know about it.");
984     }
985     return;
986   }
987 
988   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
989     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
990     MVT RegisterVT = RegVTs[Value];
991     for (unsigned i = 0; i != NumRegs; ++i) {
992       assert(Reg < Regs.size() && "Mismatch in # registers expected");
993       unsigned TheReg = Regs[Reg++];
994       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
995     }
996   }
997 }
998 
999 SmallVector<std::pair<unsigned, unsigned>, 4>
1000 RegsForValue::getRegsAndSizes() const {
1001   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1002   unsigned I = 0;
1003   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1004     unsigned RegCount = std::get<0>(CountAndVT);
1005     MVT RegisterVT = std::get<1>(CountAndVT);
1006     unsigned RegisterSize = RegisterVT.getSizeInBits();
1007     for (unsigned E = I + RegCount; I != E; ++I)
1008       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1009   }
1010   return OutVec;
1011 }
1012 
1013 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1014                                const TargetLibraryInfo *li) {
1015   AA = aa;
1016   GFI = gfi;
1017   LibInfo = li;
1018   DL = &DAG.getDataLayout();
1019   Context = DAG.getContext();
1020   LPadToCallSiteMap.clear();
1021   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1022 }
1023 
1024 void SelectionDAGBuilder::clear() {
1025   NodeMap.clear();
1026   UnusedArgNodeMap.clear();
1027   PendingLoads.clear();
1028   PendingExports.clear();
1029   PendingConstrainedFP.clear();
1030   PendingConstrainedFPStrict.clear();
1031   CurInst = nullptr;
1032   HasTailCall = false;
1033   SDNodeOrder = LowestSDNodeOrder;
1034   StatepointLowering.clear();
1035 }
1036 
1037 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1038   DanglingDebugInfoMap.clear();
1039 }
1040 
1041 // Update DAG root to include dependencies on Pending chains.
1042 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1043   SDValue Root = DAG.getRoot();
1044 
1045   if (Pending.empty())
1046     return Root;
1047 
1048   // Add current root to PendingChains, unless we already indirectly
1049   // depend on it.
1050   if (Root.getOpcode() != ISD::EntryToken) {
1051     unsigned i = 0, e = Pending.size();
1052     for (; i != e; ++i) {
1053       assert(Pending[i].getNode()->getNumOperands() > 1);
1054       if (Pending[i].getNode()->getOperand(0) == Root)
1055         break;  // Don't add the root if we already indirectly depend on it.
1056     }
1057 
1058     if (i == e)
1059       Pending.push_back(Root);
1060   }
1061 
1062   if (Pending.size() == 1)
1063     Root = Pending[0];
1064   else
1065     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1066 
1067   DAG.setRoot(Root);
1068   Pending.clear();
1069   return Root;
1070 }
1071 
1072 SDValue SelectionDAGBuilder::getMemoryRoot() {
1073   return updateRoot(PendingLoads);
1074 }
1075 
1076 SDValue SelectionDAGBuilder::getRoot() {
1077   // Chain up all pending constrained intrinsics together with all
1078   // pending loads, by simply appending them to PendingLoads and
1079   // then calling getMemoryRoot().
1080   PendingLoads.reserve(PendingLoads.size() +
1081                        PendingConstrainedFP.size() +
1082                        PendingConstrainedFPStrict.size());
1083   PendingLoads.append(PendingConstrainedFP.begin(),
1084                       PendingConstrainedFP.end());
1085   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1086                       PendingConstrainedFPStrict.end());
1087   PendingConstrainedFP.clear();
1088   PendingConstrainedFPStrict.clear();
1089   return getMemoryRoot();
1090 }
1091 
1092 SDValue SelectionDAGBuilder::getControlRoot() {
1093   // We need to emit pending fpexcept.strict constrained intrinsics,
1094   // so append them to the PendingExports list.
1095   PendingExports.append(PendingConstrainedFPStrict.begin(),
1096                         PendingConstrainedFPStrict.end());
1097   PendingConstrainedFPStrict.clear();
1098   return updateRoot(PendingExports);
1099 }
1100 
1101 void SelectionDAGBuilder::visit(const Instruction &I) {
1102   // Set up outgoing PHI node register values before emitting the terminator.
1103   if (I.isTerminator()) {
1104     HandlePHINodesInSuccessorBlocks(I.getParent());
1105   }
1106 
1107   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1108   if (!isa<DbgInfoIntrinsic>(I))
1109     ++SDNodeOrder;
1110 
1111   CurInst = &I;
1112 
1113   visit(I.getOpcode(), I);
1114 
1115   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1116     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1117     // maps to this instruction.
1118     // TODO: We could handle all flags (nsw, etc) here.
1119     // TODO: If an IR instruction maps to >1 node, only the final node will have
1120     //       flags set.
1121     if (SDNode *Node = getNodeForIRValue(&I)) {
1122       SDNodeFlags IncomingFlags;
1123       IncomingFlags.copyFMF(*FPMO);
1124       if (!Node->getFlags().isDefined())
1125         Node->setFlags(IncomingFlags);
1126       else
1127         Node->intersectFlagsWith(IncomingFlags);
1128     }
1129   }
1130   // Constrained FP intrinsics with fpexcept.ignore should also get
1131   // the NoFPExcept flag.
1132   if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(&I))
1133     if (FPI->getExceptionBehavior() == fp::ExceptionBehavior::ebIgnore)
1134       if (SDNode *Node = getNodeForIRValue(&I)) {
1135         SDNodeFlags Flags = Node->getFlags();
1136         Flags.setNoFPExcept(true);
1137         Node->setFlags(Flags);
1138       }
1139 
1140   if (!I.isTerminator() && !HasTailCall &&
1141       !isStatepoint(&I)) // statepoints handle their exports internally
1142     CopyToExportRegsIfNeeded(&I);
1143 
1144   CurInst = nullptr;
1145 }
1146 
1147 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1148   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1149 }
1150 
1151 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1152   // Note: this doesn't use InstVisitor, because it has to work with
1153   // ConstantExpr's in addition to instructions.
1154   switch (Opcode) {
1155   default: llvm_unreachable("Unknown instruction type encountered!");
1156     // Build the switch statement using the Instruction.def file.
1157 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1158     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1159 #include "llvm/IR/Instruction.def"
1160   }
1161 }
1162 
1163 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1164                                                 const DIExpression *Expr) {
1165   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1166     const DbgValueInst *DI = DDI.getDI();
1167     DIVariable *DanglingVariable = DI->getVariable();
1168     DIExpression *DanglingExpr = DI->getExpression();
1169     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1170       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1171       return true;
1172     }
1173     return false;
1174   };
1175 
1176   for (auto &DDIMI : DanglingDebugInfoMap) {
1177     DanglingDebugInfoVector &DDIV = DDIMI.second;
1178 
1179     // If debug info is to be dropped, run it through final checks to see
1180     // whether it can be salvaged.
1181     for (auto &DDI : DDIV)
1182       if (isMatchingDbgValue(DDI))
1183         salvageUnresolvedDbgValue(DDI);
1184 
1185     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1186   }
1187 }
1188 
1189 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1190 // generate the debug data structures now that we've seen its definition.
1191 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1192                                                    SDValue Val) {
1193   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1194   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1195     return;
1196 
1197   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1198   for (auto &DDI : DDIV) {
1199     const DbgValueInst *DI = DDI.getDI();
1200     assert(DI && "Ill-formed DanglingDebugInfo");
1201     DebugLoc dl = DDI.getdl();
1202     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1203     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1204     DILocalVariable *Variable = DI->getVariable();
1205     DIExpression *Expr = DI->getExpression();
1206     assert(Variable->isValidLocationForIntrinsic(dl) &&
1207            "Expected inlined-at fields to agree");
1208     SDDbgValue *SDV;
1209     if (Val.getNode()) {
1210       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1211       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1212       // we couldn't resolve it directly when examining the DbgValue intrinsic
1213       // in the first place we should not be more successful here). Unless we
1214       // have some test case that prove this to be correct we should avoid
1215       // calling EmitFuncArgumentDbgValue here.
1216       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1217         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1218                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1219         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1220         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1221         // inserted after the definition of Val when emitting the instructions
1222         // after ISel. An alternative could be to teach
1223         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1224         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1225                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1226                    << ValSDNodeOrder << "\n");
1227         SDV = getDbgValue(Val, Variable, Expr, dl,
1228                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1229         DAG.AddDbgValue(SDV, Val.getNode(), false);
1230       } else
1231         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1232                           << "in EmitFuncArgumentDbgValue\n");
1233     } else {
1234       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1235       auto Undef =
1236           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1237       auto SDV =
1238           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1239       DAG.AddDbgValue(SDV, nullptr, false);
1240     }
1241   }
1242   DDIV.clear();
1243 }
1244 
1245 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1246   Value *V = DDI.getDI()->getValue();
1247   DILocalVariable *Var = DDI.getDI()->getVariable();
1248   DIExpression *Expr = DDI.getDI()->getExpression();
1249   DebugLoc DL = DDI.getdl();
1250   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1251   unsigned SDOrder = DDI.getSDNodeOrder();
1252 
1253   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1254   // that DW_OP_stack_value is desired.
1255   assert(isa<DbgValueInst>(DDI.getDI()));
1256   bool StackValue = true;
1257 
1258   // Can this Value can be encoded without any further work?
1259   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1260     return;
1261 
1262   // Attempt to salvage back through as many instructions as possible. Bail if
1263   // a non-instruction is seen, such as a constant expression or global
1264   // variable. FIXME: Further work could recover those too.
1265   while (isa<Instruction>(V)) {
1266     Instruction &VAsInst = *cast<Instruction>(V);
1267     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1268 
1269     // If we cannot salvage any further, and haven't yet found a suitable debug
1270     // expression, bail out.
1271     if (!NewExpr)
1272       break;
1273 
1274     // New value and expr now represent this debuginfo.
1275     V = VAsInst.getOperand(0);
1276     Expr = NewExpr;
1277 
1278     // Some kind of simplification occurred: check whether the operand of the
1279     // salvaged debug expression can be encoded in this DAG.
1280     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1281       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1282                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1283       return;
1284     }
1285   }
1286 
1287   // This was the final opportunity to salvage this debug information, and it
1288   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1289   // any earlier variable location.
1290   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1291   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1292   DAG.AddDbgValue(SDV, nullptr, false);
1293 
1294   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1295                     << "\n");
1296   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1297                     << "\n");
1298 }
1299 
1300 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1301                                            DIExpression *Expr, DebugLoc dl,
1302                                            DebugLoc InstDL, unsigned Order) {
1303   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1304   SDDbgValue *SDV;
1305   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1306       isa<ConstantPointerNull>(V)) {
1307     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1308     DAG.AddDbgValue(SDV, nullptr, false);
1309     return true;
1310   }
1311 
1312   // If the Value is a frame index, we can create a FrameIndex debug value
1313   // without relying on the DAG at all.
1314   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1315     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1316     if (SI != FuncInfo.StaticAllocaMap.end()) {
1317       auto SDV =
1318           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1319                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1320       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1321       // is still available even if the SDNode gets optimized out.
1322       DAG.AddDbgValue(SDV, nullptr, false);
1323       return true;
1324     }
1325   }
1326 
1327   // Do not use getValue() in here; we don't want to generate code at
1328   // this point if it hasn't been done yet.
1329   SDValue N = NodeMap[V];
1330   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1331     N = UnusedArgNodeMap[V];
1332   if (N.getNode()) {
1333     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1334       return true;
1335     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1336     DAG.AddDbgValue(SDV, N.getNode(), false);
1337     return true;
1338   }
1339 
1340   // Special rules apply for the first dbg.values of parameter variables in a
1341   // function. Identify them by the fact they reference Argument Values, that
1342   // they're parameters, and they are parameters of the current function. We
1343   // need to let them dangle until they get an SDNode.
1344   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1345                        !InstDL.getInlinedAt();
1346   if (!IsParamOfFunc) {
1347     // The value is not used in this block yet (or it would have an SDNode).
1348     // We still want the value to appear for the user if possible -- if it has
1349     // an associated VReg, we can refer to that instead.
1350     auto VMI = FuncInfo.ValueMap.find(V);
1351     if (VMI != FuncInfo.ValueMap.end()) {
1352       unsigned Reg = VMI->second;
1353       // If this is a PHI node, it may be split up into several MI PHI nodes
1354       // (in FunctionLoweringInfo::set).
1355       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1356                        V->getType(), None);
1357       if (RFV.occupiesMultipleRegs()) {
1358         unsigned Offset = 0;
1359         unsigned BitsToDescribe = 0;
1360         if (auto VarSize = Var->getSizeInBits())
1361           BitsToDescribe = *VarSize;
1362         if (auto Fragment = Expr->getFragmentInfo())
1363           BitsToDescribe = Fragment->SizeInBits;
1364         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1365           unsigned RegisterSize = RegAndSize.second;
1366           // Bail out if all bits are described already.
1367           if (Offset >= BitsToDescribe)
1368             break;
1369           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1370               ? BitsToDescribe - Offset
1371               : RegisterSize;
1372           auto FragmentExpr = DIExpression::createFragmentExpression(
1373               Expr, Offset, FragmentSize);
1374           if (!FragmentExpr)
1375               continue;
1376           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1377                                     false, dl, SDNodeOrder);
1378           DAG.AddDbgValue(SDV, nullptr, false);
1379           Offset += RegisterSize;
1380         }
1381       } else {
1382         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1383         DAG.AddDbgValue(SDV, nullptr, false);
1384       }
1385       return true;
1386     }
1387   }
1388 
1389   return false;
1390 }
1391 
1392 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1393   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1394   for (auto &Pair : DanglingDebugInfoMap)
1395     for (auto &DDI : Pair.second)
1396       salvageUnresolvedDbgValue(DDI);
1397   clearDanglingDebugInfo();
1398 }
1399 
1400 /// getCopyFromRegs - If there was virtual register allocated for the value V
1401 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1402 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1403   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1404   SDValue Result;
1405 
1406   if (It != FuncInfo.ValueMap.end()) {
1407     unsigned InReg = It->second;
1408 
1409     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1410                      DAG.getDataLayout(), InReg, Ty,
1411                      None); // This is not an ABI copy.
1412     SDValue Chain = DAG.getEntryNode();
1413     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1414                                  V);
1415     resolveDanglingDebugInfo(V, Result);
1416   }
1417 
1418   return Result;
1419 }
1420 
1421 /// getValue - Return an SDValue for the given Value.
1422 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1423   // If we already have an SDValue for this value, use it. It's important
1424   // to do this first, so that we don't create a CopyFromReg if we already
1425   // have a regular SDValue.
1426   SDValue &N = NodeMap[V];
1427   if (N.getNode()) return N;
1428 
1429   // If there's a virtual register allocated and initialized for this
1430   // value, use it.
1431   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1432     return copyFromReg;
1433 
1434   // Otherwise create a new SDValue and remember it.
1435   SDValue Val = getValueImpl(V);
1436   NodeMap[V] = Val;
1437   resolveDanglingDebugInfo(V, Val);
1438   return Val;
1439 }
1440 
1441 // Return true if SDValue exists for the given Value
1442 bool SelectionDAGBuilder::findValue(const Value *V) const {
1443   return (NodeMap.find(V) != NodeMap.end()) ||
1444     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1445 }
1446 
1447 /// getNonRegisterValue - Return an SDValue for the given Value, but
1448 /// don't look in FuncInfo.ValueMap for a virtual register.
1449 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1450   // If we already have an SDValue for this value, use it.
1451   SDValue &N = NodeMap[V];
1452   if (N.getNode()) {
1453     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1454       // Remove the debug location from the node as the node is about to be used
1455       // in a location which may differ from the original debug location.  This
1456       // is relevant to Constant and ConstantFP nodes because they can appear
1457       // as constant expressions inside PHI nodes.
1458       N->setDebugLoc(DebugLoc());
1459     }
1460     return N;
1461   }
1462 
1463   // Otherwise create a new SDValue and remember it.
1464   SDValue Val = getValueImpl(V);
1465   NodeMap[V] = Val;
1466   resolveDanglingDebugInfo(V, Val);
1467   return Val;
1468 }
1469 
1470 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1471 /// Create an SDValue for the given value.
1472 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1473   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1474 
1475   if (const Constant *C = dyn_cast<Constant>(V)) {
1476     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1477 
1478     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1479       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1480 
1481     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1482       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1483 
1484     if (isa<ConstantPointerNull>(C)) {
1485       unsigned AS = V->getType()->getPointerAddressSpace();
1486       return DAG.getConstant(0, getCurSDLoc(),
1487                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1488     }
1489 
1490     if (match(C, m_VScale(DAG.getDataLayout())))
1491       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1492 
1493     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1494       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1495 
1496     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1497       return DAG.getUNDEF(VT);
1498 
1499     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1500       visit(CE->getOpcode(), *CE);
1501       SDValue N1 = NodeMap[V];
1502       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1503       return N1;
1504     }
1505 
1506     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1507       SmallVector<SDValue, 4> Constants;
1508       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1509            OI != OE; ++OI) {
1510         SDNode *Val = getValue(*OI).getNode();
1511         // If the operand is an empty aggregate, there are no values.
1512         if (!Val) continue;
1513         // Add each leaf value from the operand to the Constants list
1514         // to form a flattened list of all the values.
1515         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1516           Constants.push_back(SDValue(Val, i));
1517       }
1518 
1519       return DAG.getMergeValues(Constants, getCurSDLoc());
1520     }
1521 
1522     if (const ConstantDataSequential *CDS =
1523           dyn_cast<ConstantDataSequential>(C)) {
1524       SmallVector<SDValue, 4> Ops;
1525       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1526         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1527         // Add each leaf value from the operand to the Constants list
1528         // to form a flattened list of all the values.
1529         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1530           Ops.push_back(SDValue(Val, i));
1531       }
1532 
1533       if (isa<ArrayType>(CDS->getType()))
1534         return DAG.getMergeValues(Ops, getCurSDLoc());
1535       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1536     }
1537 
1538     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1539       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1540              "Unknown struct or array constant!");
1541 
1542       SmallVector<EVT, 4> ValueVTs;
1543       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1544       unsigned NumElts = ValueVTs.size();
1545       if (NumElts == 0)
1546         return SDValue(); // empty struct
1547       SmallVector<SDValue, 4> Constants(NumElts);
1548       for (unsigned i = 0; i != NumElts; ++i) {
1549         EVT EltVT = ValueVTs[i];
1550         if (isa<UndefValue>(C))
1551           Constants[i] = DAG.getUNDEF(EltVT);
1552         else if (EltVT.isFloatingPoint())
1553           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1554         else
1555           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1556       }
1557 
1558       return DAG.getMergeValues(Constants, getCurSDLoc());
1559     }
1560 
1561     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1562       return DAG.getBlockAddress(BA, VT);
1563 
1564     VectorType *VecTy = cast<VectorType>(V->getType());
1565     unsigned NumElements = VecTy->getNumElements();
1566 
1567     // Now that we know the number and type of the elements, get that number of
1568     // elements into the Ops array based on what kind of constant it is.
1569     SmallVector<SDValue, 16> Ops;
1570     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1571       for (unsigned i = 0; i != NumElements; ++i)
1572         Ops.push_back(getValue(CV->getOperand(i)));
1573     } else {
1574       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1575       EVT EltVT =
1576           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1577 
1578       SDValue Op;
1579       if (EltVT.isFloatingPoint())
1580         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1581       else
1582         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1583       Ops.assign(NumElements, Op);
1584     }
1585 
1586     // Create a BUILD_VECTOR node.
1587     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1588   }
1589 
1590   // If this is a static alloca, generate it as the frameindex instead of
1591   // computation.
1592   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1593     DenseMap<const AllocaInst*, int>::iterator SI =
1594       FuncInfo.StaticAllocaMap.find(AI);
1595     if (SI != FuncInfo.StaticAllocaMap.end())
1596       return DAG.getFrameIndex(SI->second,
1597                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1598   }
1599 
1600   // If this is an instruction which fast-isel has deferred, select it now.
1601   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1602     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1603 
1604     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1605                      Inst->getType(), getABIRegCopyCC(V));
1606     SDValue Chain = DAG.getEntryNode();
1607     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1608   }
1609 
1610   llvm_unreachable("Can't get register for value!");
1611 }
1612 
1613 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1614   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1615   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1616   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1617   bool IsSEH = isAsynchronousEHPersonality(Pers);
1618   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1619   if (!IsSEH)
1620     CatchPadMBB->setIsEHScopeEntry();
1621   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1622   if (IsMSVCCXX || IsCoreCLR)
1623     CatchPadMBB->setIsEHFuncletEntry();
1624 }
1625 
1626 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1627   // Update machine-CFG edge.
1628   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1629   FuncInfo.MBB->addSuccessor(TargetMBB);
1630 
1631   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1632   bool IsSEH = isAsynchronousEHPersonality(Pers);
1633   if (IsSEH) {
1634     // If this is not a fall-through branch or optimizations are switched off,
1635     // emit the branch.
1636     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1637         TM.getOptLevel() == CodeGenOpt::None)
1638       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1639                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1640     return;
1641   }
1642 
1643   // Figure out the funclet membership for the catchret's successor.
1644   // This will be used by the FuncletLayout pass to determine how to order the
1645   // BB's.
1646   // A 'catchret' returns to the outer scope's color.
1647   Value *ParentPad = I.getCatchSwitchParentPad();
1648   const BasicBlock *SuccessorColor;
1649   if (isa<ConstantTokenNone>(ParentPad))
1650     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1651   else
1652     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1653   assert(SuccessorColor && "No parent funclet for catchret!");
1654   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1655   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1656 
1657   // Create the terminator node.
1658   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1659                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1660                             DAG.getBasicBlock(SuccessorColorMBB));
1661   DAG.setRoot(Ret);
1662 }
1663 
1664 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1665   // Don't emit any special code for the cleanuppad instruction. It just marks
1666   // the start of an EH scope/funclet.
1667   FuncInfo.MBB->setIsEHScopeEntry();
1668   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1669   if (Pers != EHPersonality::Wasm_CXX) {
1670     FuncInfo.MBB->setIsEHFuncletEntry();
1671     FuncInfo.MBB->setIsCleanupFuncletEntry();
1672   }
1673 }
1674 
1675 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1676 // the control flow always stops at the single catch pad, as it does for a
1677 // cleanup pad. In case the exception caught is not of the types the catch pad
1678 // catches, it will be rethrown by a rethrow.
1679 static void findWasmUnwindDestinations(
1680     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1681     BranchProbability Prob,
1682     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1683         &UnwindDests) {
1684   while (EHPadBB) {
1685     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1686     if (isa<CleanupPadInst>(Pad)) {
1687       // Stop on cleanup pads.
1688       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1689       UnwindDests.back().first->setIsEHScopeEntry();
1690       break;
1691     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1692       // Add the catchpad handlers to the possible destinations. We don't
1693       // continue to the unwind destination of the catchswitch for wasm.
1694       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1695         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1696         UnwindDests.back().first->setIsEHScopeEntry();
1697       }
1698       break;
1699     } else {
1700       continue;
1701     }
1702   }
1703 }
1704 
1705 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1706 /// many places it could ultimately go. In the IR, we have a single unwind
1707 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1708 /// This function skips over imaginary basic blocks that hold catchswitch
1709 /// instructions, and finds all the "real" machine
1710 /// basic block destinations. As those destinations may not be successors of
1711 /// EHPadBB, here we also calculate the edge probability to those destinations.
1712 /// The passed-in Prob is the edge probability to EHPadBB.
1713 static void findUnwindDestinations(
1714     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1715     BranchProbability Prob,
1716     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1717         &UnwindDests) {
1718   EHPersonality Personality =
1719     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1720   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1721   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1722   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1723   bool IsSEH = isAsynchronousEHPersonality(Personality);
1724 
1725   if (IsWasmCXX) {
1726     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1727     assert(UnwindDests.size() <= 1 &&
1728            "There should be at most one unwind destination for wasm");
1729     return;
1730   }
1731 
1732   while (EHPadBB) {
1733     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1734     BasicBlock *NewEHPadBB = nullptr;
1735     if (isa<LandingPadInst>(Pad)) {
1736       // Stop on landingpads. They are not funclets.
1737       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1738       break;
1739     } else if (isa<CleanupPadInst>(Pad)) {
1740       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1741       // personalities.
1742       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1743       UnwindDests.back().first->setIsEHScopeEntry();
1744       UnwindDests.back().first->setIsEHFuncletEntry();
1745       break;
1746     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1747       // Add the catchpad handlers to the possible destinations.
1748       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1749         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1750         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1751         if (IsMSVCCXX || IsCoreCLR)
1752           UnwindDests.back().first->setIsEHFuncletEntry();
1753         if (!IsSEH)
1754           UnwindDests.back().first->setIsEHScopeEntry();
1755       }
1756       NewEHPadBB = CatchSwitch->getUnwindDest();
1757     } else {
1758       continue;
1759     }
1760 
1761     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1762     if (BPI && NewEHPadBB)
1763       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1764     EHPadBB = NewEHPadBB;
1765   }
1766 }
1767 
1768 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1769   // Update successor info.
1770   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1771   auto UnwindDest = I.getUnwindDest();
1772   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1773   BranchProbability UnwindDestProb =
1774       (BPI && UnwindDest)
1775           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1776           : BranchProbability::getZero();
1777   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1778   for (auto &UnwindDest : UnwindDests) {
1779     UnwindDest.first->setIsEHPad();
1780     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1781   }
1782   FuncInfo.MBB->normalizeSuccProbs();
1783 
1784   // Create the terminator node.
1785   SDValue Ret =
1786       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1787   DAG.setRoot(Ret);
1788 }
1789 
1790 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1791   report_fatal_error("visitCatchSwitch not yet implemented!");
1792 }
1793 
1794 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1796   auto &DL = DAG.getDataLayout();
1797   SDValue Chain = getControlRoot();
1798   SmallVector<ISD::OutputArg, 8> Outs;
1799   SmallVector<SDValue, 8> OutVals;
1800 
1801   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1802   // lower
1803   //
1804   //   %val = call <ty> @llvm.experimental.deoptimize()
1805   //   ret <ty> %val
1806   //
1807   // differently.
1808   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1809     LowerDeoptimizingReturn();
1810     return;
1811   }
1812 
1813   if (!FuncInfo.CanLowerReturn) {
1814     unsigned DemoteReg = FuncInfo.DemoteRegister;
1815     const Function *F = I.getParent()->getParent();
1816 
1817     // Emit a store of the return value through the virtual register.
1818     // Leave Outs empty so that LowerReturn won't try to load return
1819     // registers the usual way.
1820     SmallVector<EVT, 1> PtrValueVTs;
1821     ComputeValueVTs(TLI, DL,
1822                     F->getReturnType()->getPointerTo(
1823                         DAG.getDataLayout().getAllocaAddrSpace()),
1824                     PtrValueVTs);
1825 
1826     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1827                                         DemoteReg, PtrValueVTs[0]);
1828     SDValue RetOp = getValue(I.getOperand(0));
1829 
1830     SmallVector<EVT, 4> ValueVTs, MemVTs;
1831     SmallVector<uint64_t, 4> Offsets;
1832     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1833                     &Offsets);
1834     unsigned NumValues = ValueVTs.size();
1835 
1836     SmallVector<SDValue, 4> Chains(NumValues);
1837     for (unsigned i = 0; i != NumValues; ++i) {
1838       // An aggregate return value cannot wrap around the address space, so
1839       // offsets to its parts don't wrap either.
1840       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1841 
1842       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1843       if (MemVTs[i] != ValueVTs[i])
1844         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1845       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1846           // FIXME: better loc info would be nice.
1847           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1848     }
1849 
1850     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1851                         MVT::Other, Chains);
1852   } else if (I.getNumOperands() != 0) {
1853     SmallVector<EVT, 4> ValueVTs;
1854     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1855     unsigned NumValues = ValueVTs.size();
1856     if (NumValues) {
1857       SDValue RetOp = getValue(I.getOperand(0));
1858 
1859       const Function *F = I.getParent()->getParent();
1860 
1861       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1862           I.getOperand(0)->getType(), F->getCallingConv(),
1863           /*IsVarArg*/ false);
1864 
1865       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1866       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1867                                           Attribute::SExt))
1868         ExtendKind = ISD::SIGN_EXTEND;
1869       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1870                                                Attribute::ZExt))
1871         ExtendKind = ISD::ZERO_EXTEND;
1872 
1873       LLVMContext &Context = F->getContext();
1874       bool RetInReg = F->getAttributes().hasAttribute(
1875           AttributeList::ReturnIndex, Attribute::InReg);
1876 
1877       for (unsigned j = 0; j != NumValues; ++j) {
1878         EVT VT = ValueVTs[j];
1879 
1880         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1881           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1882 
1883         CallingConv::ID CC = F->getCallingConv();
1884 
1885         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1886         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1887         SmallVector<SDValue, 4> Parts(NumParts);
1888         getCopyToParts(DAG, getCurSDLoc(),
1889                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1890                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1891 
1892         // 'inreg' on function refers to return value
1893         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1894         if (RetInReg)
1895           Flags.setInReg();
1896 
1897         if (I.getOperand(0)->getType()->isPointerTy()) {
1898           Flags.setPointer();
1899           Flags.setPointerAddrSpace(
1900               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1901         }
1902 
1903         if (NeedsRegBlock) {
1904           Flags.setInConsecutiveRegs();
1905           if (j == NumValues - 1)
1906             Flags.setInConsecutiveRegsLast();
1907         }
1908 
1909         // Propagate extension type if any
1910         if (ExtendKind == ISD::SIGN_EXTEND)
1911           Flags.setSExt();
1912         else if (ExtendKind == ISD::ZERO_EXTEND)
1913           Flags.setZExt();
1914 
1915         for (unsigned i = 0; i < NumParts; ++i) {
1916           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1917                                         VT, /*isfixed=*/true, 0, 0));
1918           OutVals.push_back(Parts[i]);
1919         }
1920       }
1921     }
1922   }
1923 
1924   // Push in swifterror virtual register as the last element of Outs. This makes
1925   // sure swifterror virtual register will be returned in the swifterror
1926   // physical register.
1927   const Function *F = I.getParent()->getParent();
1928   if (TLI.supportSwiftError() &&
1929       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1930     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1931     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1932     Flags.setSwiftError();
1933     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1934                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1935                                   true /*isfixed*/, 1 /*origidx*/,
1936                                   0 /*partOffs*/));
1937     // Create SDNode for the swifterror virtual register.
1938     OutVals.push_back(
1939         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1940                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1941                         EVT(TLI.getPointerTy(DL))));
1942   }
1943 
1944   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1945   CallingConv::ID CallConv =
1946     DAG.getMachineFunction().getFunction().getCallingConv();
1947   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1948       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1949 
1950   // Verify that the target's LowerReturn behaved as expected.
1951   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1952          "LowerReturn didn't return a valid chain!");
1953 
1954   // Update the DAG with the new chain value resulting from return lowering.
1955   DAG.setRoot(Chain);
1956 }
1957 
1958 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1959 /// created for it, emit nodes to copy the value into the virtual
1960 /// registers.
1961 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1962   // Skip empty types
1963   if (V->getType()->isEmptyTy())
1964     return;
1965 
1966   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1967   if (VMI != FuncInfo.ValueMap.end()) {
1968     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1969     CopyValueToVirtualRegister(V, VMI->second);
1970   }
1971 }
1972 
1973 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1974 /// the current basic block, add it to ValueMap now so that we'll get a
1975 /// CopyTo/FromReg.
1976 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1977   // No need to export constants.
1978   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1979 
1980   // Already exported?
1981   if (FuncInfo.isExportedInst(V)) return;
1982 
1983   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1984   CopyValueToVirtualRegister(V, Reg);
1985 }
1986 
1987 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1988                                                      const BasicBlock *FromBB) {
1989   // The operands of the setcc have to be in this block.  We don't know
1990   // how to export them from some other block.
1991   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1992     // Can export from current BB.
1993     if (VI->getParent() == FromBB)
1994       return true;
1995 
1996     // Is already exported, noop.
1997     return FuncInfo.isExportedInst(V);
1998   }
1999 
2000   // If this is an argument, we can export it if the BB is the entry block or
2001   // if it is already exported.
2002   if (isa<Argument>(V)) {
2003     if (FromBB == &FromBB->getParent()->getEntryBlock())
2004       return true;
2005 
2006     // Otherwise, can only export this if it is already exported.
2007     return FuncInfo.isExportedInst(V);
2008   }
2009 
2010   // Otherwise, constants can always be exported.
2011   return true;
2012 }
2013 
2014 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2015 BranchProbability
2016 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2017                                         const MachineBasicBlock *Dst) const {
2018   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2019   const BasicBlock *SrcBB = Src->getBasicBlock();
2020   const BasicBlock *DstBB = Dst->getBasicBlock();
2021   if (!BPI) {
2022     // If BPI is not available, set the default probability as 1 / N, where N is
2023     // the number of successors.
2024     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2025     return BranchProbability(1, SuccSize);
2026   }
2027   return BPI->getEdgeProbability(SrcBB, DstBB);
2028 }
2029 
2030 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2031                                                MachineBasicBlock *Dst,
2032                                                BranchProbability Prob) {
2033   if (!FuncInfo.BPI)
2034     Src->addSuccessorWithoutProb(Dst);
2035   else {
2036     if (Prob.isUnknown())
2037       Prob = getEdgeProbability(Src, Dst);
2038     Src->addSuccessor(Dst, Prob);
2039   }
2040 }
2041 
2042 static bool InBlock(const Value *V, const BasicBlock *BB) {
2043   if (const Instruction *I = dyn_cast<Instruction>(V))
2044     return I->getParent() == BB;
2045   return true;
2046 }
2047 
2048 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2049 /// This function emits a branch and is used at the leaves of an OR or an
2050 /// AND operator tree.
2051 void
2052 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2053                                                   MachineBasicBlock *TBB,
2054                                                   MachineBasicBlock *FBB,
2055                                                   MachineBasicBlock *CurBB,
2056                                                   MachineBasicBlock *SwitchBB,
2057                                                   BranchProbability TProb,
2058                                                   BranchProbability FProb,
2059                                                   bool InvertCond) {
2060   const BasicBlock *BB = CurBB->getBasicBlock();
2061 
2062   // If the leaf of the tree is a comparison, merge the condition into
2063   // the caseblock.
2064   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2065     // The operands of the cmp have to be in this block.  We don't know
2066     // how to export them from some other block.  If this is the first block
2067     // of the sequence, no exporting is needed.
2068     if (CurBB == SwitchBB ||
2069         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2070          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2071       ISD::CondCode Condition;
2072       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2073         ICmpInst::Predicate Pred =
2074             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2075         Condition = getICmpCondCode(Pred);
2076       } else {
2077         const FCmpInst *FC = cast<FCmpInst>(Cond);
2078         FCmpInst::Predicate Pred =
2079             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2080         Condition = getFCmpCondCode(Pred);
2081         if (TM.Options.NoNaNsFPMath)
2082           Condition = getFCmpCodeWithoutNaN(Condition);
2083       }
2084 
2085       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2086                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2087       SL->SwitchCases.push_back(CB);
2088       return;
2089     }
2090   }
2091 
2092   // Create a CaseBlock record representing this branch.
2093   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2094   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2095                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2096   SL->SwitchCases.push_back(CB);
2097 }
2098 
2099 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2100                                                MachineBasicBlock *TBB,
2101                                                MachineBasicBlock *FBB,
2102                                                MachineBasicBlock *CurBB,
2103                                                MachineBasicBlock *SwitchBB,
2104                                                Instruction::BinaryOps Opc,
2105                                                BranchProbability TProb,
2106                                                BranchProbability FProb,
2107                                                bool InvertCond) {
2108   // Skip over not part of the tree and remember to invert op and operands at
2109   // next level.
2110   Value *NotCond;
2111   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2112       InBlock(NotCond, CurBB->getBasicBlock())) {
2113     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2114                          !InvertCond);
2115     return;
2116   }
2117 
2118   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2119   // Compute the effective opcode for Cond, taking into account whether it needs
2120   // to be inverted, e.g.
2121   //   and (not (or A, B)), C
2122   // gets lowered as
2123   //   and (and (not A, not B), C)
2124   unsigned BOpc = 0;
2125   if (BOp) {
2126     BOpc = BOp->getOpcode();
2127     if (InvertCond) {
2128       if (BOpc == Instruction::And)
2129         BOpc = Instruction::Or;
2130       else if (BOpc == Instruction::Or)
2131         BOpc = Instruction::And;
2132     }
2133   }
2134 
2135   // If this node is not part of the or/and tree, emit it as a branch.
2136   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2137       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2138       BOp->getParent() != CurBB->getBasicBlock() ||
2139       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2140       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2141     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2142                                  TProb, FProb, InvertCond);
2143     return;
2144   }
2145 
2146   //  Create TmpBB after CurBB.
2147   MachineFunction::iterator BBI(CurBB);
2148   MachineFunction &MF = DAG.getMachineFunction();
2149   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2150   CurBB->getParent()->insert(++BBI, TmpBB);
2151 
2152   if (Opc == Instruction::Or) {
2153     // Codegen X | Y as:
2154     // BB1:
2155     //   jmp_if_X TBB
2156     //   jmp TmpBB
2157     // TmpBB:
2158     //   jmp_if_Y TBB
2159     //   jmp FBB
2160     //
2161 
2162     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2163     // The requirement is that
2164     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2165     //     = TrueProb for original BB.
2166     // Assuming the original probabilities are A and B, one choice is to set
2167     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2168     // A/(1+B) and 2B/(1+B). This choice assumes that
2169     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2170     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2171     // TmpBB, but the math is more complicated.
2172 
2173     auto NewTrueProb = TProb / 2;
2174     auto NewFalseProb = TProb / 2 + FProb;
2175     // Emit the LHS condition.
2176     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2177                          NewTrueProb, NewFalseProb, InvertCond);
2178 
2179     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2180     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2181     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2182     // Emit the RHS condition into TmpBB.
2183     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2184                          Probs[0], Probs[1], InvertCond);
2185   } else {
2186     assert(Opc == Instruction::And && "Unknown merge op!");
2187     // Codegen X & Y as:
2188     // BB1:
2189     //   jmp_if_X TmpBB
2190     //   jmp FBB
2191     // TmpBB:
2192     //   jmp_if_Y TBB
2193     //   jmp FBB
2194     //
2195     //  This requires creation of TmpBB after CurBB.
2196 
2197     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2198     // The requirement is that
2199     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2200     //     = FalseProb for original BB.
2201     // Assuming the original probabilities are A and B, one choice is to set
2202     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2203     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2204     // TrueProb for BB1 * FalseProb for TmpBB.
2205 
2206     auto NewTrueProb = TProb + FProb / 2;
2207     auto NewFalseProb = FProb / 2;
2208     // Emit the LHS condition.
2209     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2210                          NewTrueProb, NewFalseProb, InvertCond);
2211 
2212     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2213     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2214     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2215     // Emit the RHS condition into TmpBB.
2216     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2217                          Probs[0], Probs[1], InvertCond);
2218   }
2219 }
2220 
2221 /// If the set of cases should be emitted as a series of branches, return true.
2222 /// If we should emit this as a bunch of and/or'd together conditions, return
2223 /// false.
2224 bool
2225 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2226   if (Cases.size() != 2) return true;
2227 
2228   // If this is two comparisons of the same values or'd or and'd together, they
2229   // will get folded into a single comparison, so don't emit two blocks.
2230   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2231        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2232       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2233        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2234     return false;
2235   }
2236 
2237   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2238   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2239   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2240       Cases[0].CC == Cases[1].CC &&
2241       isa<Constant>(Cases[0].CmpRHS) &&
2242       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2243     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2244       return false;
2245     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2246       return false;
2247   }
2248 
2249   return true;
2250 }
2251 
2252 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2253   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2254 
2255   // Update machine-CFG edges.
2256   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2257 
2258   if (I.isUnconditional()) {
2259     // Update machine-CFG edges.
2260     BrMBB->addSuccessor(Succ0MBB);
2261 
2262     // If this is not a fall-through branch or optimizations are switched off,
2263     // emit the branch.
2264     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2265       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2266                               MVT::Other, getControlRoot(),
2267                               DAG.getBasicBlock(Succ0MBB)));
2268 
2269     return;
2270   }
2271 
2272   // If this condition is one of the special cases we handle, do special stuff
2273   // now.
2274   const Value *CondVal = I.getCondition();
2275   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2276 
2277   // If this is a series of conditions that are or'd or and'd together, emit
2278   // this as a sequence of branches instead of setcc's with and/or operations.
2279   // As long as jumps are not expensive, this should improve performance.
2280   // For example, instead of something like:
2281   //     cmp A, B
2282   //     C = seteq
2283   //     cmp D, E
2284   //     F = setle
2285   //     or C, F
2286   //     jnz foo
2287   // Emit:
2288   //     cmp A, B
2289   //     je foo
2290   //     cmp D, E
2291   //     jle foo
2292   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2293     Instruction::BinaryOps Opcode = BOp->getOpcode();
2294     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2295         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2296         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2297       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2298                            Opcode,
2299                            getEdgeProbability(BrMBB, Succ0MBB),
2300                            getEdgeProbability(BrMBB, Succ1MBB),
2301                            /*InvertCond=*/false);
2302       // If the compares in later blocks need to use values not currently
2303       // exported from this block, export them now.  This block should always
2304       // be the first entry.
2305       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2306 
2307       // Allow some cases to be rejected.
2308       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2309         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2310           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2311           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2312         }
2313 
2314         // Emit the branch for this block.
2315         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2316         SL->SwitchCases.erase(SL->SwitchCases.begin());
2317         return;
2318       }
2319 
2320       // Okay, we decided not to do this, remove any inserted MBB's and clear
2321       // SwitchCases.
2322       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2323         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2324 
2325       SL->SwitchCases.clear();
2326     }
2327   }
2328 
2329   // Create a CaseBlock record representing this branch.
2330   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2331                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2332 
2333   // Use visitSwitchCase to actually insert the fast branch sequence for this
2334   // cond branch.
2335   visitSwitchCase(CB, BrMBB);
2336 }
2337 
2338 /// visitSwitchCase - Emits the necessary code to represent a single node in
2339 /// the binary search tree resulting from lowering a switch instruction.
2340 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2341                                           MachineBasicBlock *SwitchBB) {
2342   SDValue Cond;
2343   SDValue CondLHS = getValue(CB.CmpLHS);
2344   SDLoc dl = CB.DL;
2345 
2346   if (CB.CC == ISD::SETTRUE) {
2347     // Branch or fall through to TrueBB.
2348     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2349     SwitchBB->normalizeSuccProbs();
2350     if (CB.TrueBB != NextBlock(SwitchBB)) {
2351       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2352                               DAG.getBasicBlock(CB.TrueBB)));
2353     }
2354     return;
2355   }
2356 
2357   auto &TLI = DAG.getTargetLoweringInfo();
2358   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2359 
2360   // Build the setcc now.
2361   if (!CB.CmpMHS) {
2362     // Fold "(X == true)" to X and "(X == false)" to !X to
2363     // handle common cases produced by branch lowering.
2364     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2365         CB.CC == ISD::SETEQ)
2366       Cond = CondLHS;
2367     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2368              CB.CC == ISD::SETEQ) {
2369       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2370       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2371     } else {
2372       SDValue CondRHS = getValue(CB.CmpRHS);
2373 
2374       // If a pointer's DAG type is larger than its memory type then the DAG
2375       // values are zero-extended. This breaks signed comparisons so truncate
2376       // back to the underlying type before doing the compare.
2377       if (CondLHS.getValueType() != MemVT) {
2378         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2379         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2380       }
2381       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2382     }
2383   } else {
2384     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2385 
2386     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2387     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2388 
2389     SDValue CmpOp = getValue(CB.CmpMHS);
2390     EVT VT = CmpOp.getValueType();
2391 
2392     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2393       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2394                           ISD::SETLE);
2395     } else {
2396       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2397                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2398       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2399                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2400     }
2401   }
2402 
2403   // Update successor info
2404   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2405   // TrueBB and FalseBB are always different unless the incoming IR is
2406   // degenerate. This only happens when running llc on weird IR.
2407   if (CB.TrueBB != CB.FalseBB)
2408     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2409   SwitchBB->normalizeSuccProbs();
2410 
2411   // If the lhs block is the next block, invert the condition so that we can
2412   // fall through to the lhs instead of the rhs block.
2413   if (CB.TrueBB == NextBlock(SwitchBB)) {
2414     std::swap(CB.TrueBB, CB.FalseBB);
2415     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2416     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2417   }
2418 
2419   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2420                                MVT::Other, getControlRoot(), Cond,
2421                                DAG.getBasicBlock(CB.TrueBB));
2422 
2423   // Insert the false branch. Do this even if it's a fall through branch,
2424   // this makes it easier to do DAG optimizations which require inverting
2425   // the branch condition.
2426   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2427                        DAG.getBasicBlock(CB.FalseBB));
2428 
2429   DAG.setRoot(BrCond);
2430 }
2431 
2432 /// visitJumpTable - Emit JumpTable node in the current MBB
2433 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2434   // Emit the code for the jump table
2435   assert(JT.Reg != -1U && "Should lower JT Header first!");
2436   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2437   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2438                                      JT.Reg, PTy);
2439   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2440   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2441                                     MVT::Other, Index.getValue(1),
2442                                     Table, Index);
2443   DAG.setRoot(BrJumpTable);
2444 }
2445 
2446 /// visitJumpTableHeader - This function emits necessary code to produce index
2447 /// in the JumpTable from switch case.
2448 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2449                                                JumpTableHeader &JTH,
2450                                                MachineBasicBlock *SwitchBB) {
2451   SDLoc dl = getCurSDLoc();
2452 
2453   // Subtract the lowest switch case value from the value being switched on.
2454   SDValue SwitchOp = getValue(JTH.SValue);
2455   EVT VT = SwitchOp.getValueType();
2456   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2457                             DAG.getConstant(JTH.First, dl, VT));
2458 
2459   // The SDNode we just created, which holds the value being switched on minus
2460   // the smallest case value, needs to be copied to a virtual register so it
2461   // can be used as an index into the jump table in a subsequent basic block.
2462   // This value may be smaller or larger than the target's pointer type, and
2463   // therefore require extension or truncating.
2464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2465   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2466 
2467   unsigned JumpTableReg =
2468       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2469   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2470                                     JumpTableReg, SwitchOp);
2471   JT.Reg = JumpTableReg;
2472 
2473   if (!JTH.OmitRangeCheck) {
2474     // Emit the range check for the jump table, and branch to the default block
2475     // for the switch statement if the value being switched on exceeds the
2476     // largest case in the switch.
2477     SDValue CMP = DAG.getSetCC(
2478         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2479                                    Sub.getValueType()),
2480         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2481 
2482     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2483                                  MVT::Other, CopyTo, CMP,
2484                                  DAG.getBasicBlock(JT.Default));
2485 
2486     // Avoid emitting unnecessary branches to the next block.
2487     if (JT.MBB != NextBlock(SwitchBB))
2488       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2489                            DAG.getBasicBlock(JT.MBB));
2490 
2491     DAG.setRoot(BrCond);
2492   } else {
2493     // Avoid emitting unnecessary branches to the next block.
2494     if (JT.MBB != NextBlock(SwitchBB))
2495       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2496                               DAG.getBasicBlock(JT.MBB)));
2497     else
2498       DAG.setRoot(CopyTo);
2499   }
2500 }
2501 
2502 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2503 /// variable if there exists one.
2504 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2505                                  SDValue &Chain) {
2506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2507   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2508   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2509   MachineFunction &MF = DAG.getMachineFunction();
2510   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2511   MachineSDNode *Node =
2512       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2513   if (Global) {
2514     MachinePointerInfo MPInfo(Global);
2515     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2516                  MachineMemOperand::MODereferenceable;
2517     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2518         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2519     DAG.setNodeMemRefs(Node, {MemRef});
2520   }
2521   if (PtrTy != PtrMemTy)
2522     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2523   return SDValue(Node, 0);
2524 }
2525 
2526 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2527 /// tail spliced into a stack protector check success bb.
2528 ///
2529 /// For a high level explanation of how this fits into the stack protector
2530 /// generation see the comment on the declaration of class
2531 /// StackProtectorDescriptor.
2532 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2533                                                   MachineBasicBlock *ParentBB) {
2534 
2535   // First create the loads to the guard/stack slot for the comparison.
2536   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2537   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2538   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2539 
2540   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2541   int FI = MFI.getStackProtectorIndex();
2542 
2543   SDValue Guard;
2544   SDLoc dl = getCurSDLoc();
2545   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2546   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2547   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2548 
2549   // Generate code to load the content of the guard slot.
2550   SDValue GuardVal = DAG.getLoad(
2551       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2552       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2553       MachineMemOperand::MOVolatile);
2554 
2555   if (TLI.useStackGuardXorFP())
2556     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2557 
2558   // Retrieve guard check function, nullptr if instrumentation is inlined.
2559   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2560     // The target provides a guard check function to validate the guard value.
2561     // Generate a call to that function with the content of the guard slot as
2562     // argument.
2563     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2564     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2565 
2566     TargetLowering::ArgListTy Args;
2567     TargetLowering::ArgListEntry Entry;
2568     Entry.Node = GuardVal;
2569     Entry.Ty = FnTy->getParamType(0);
2570     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2571       Entry.IsInReg = true;
2572     Args.push_back(Entry);
2573 
2574     TargetLowering::CallLoweringInfo CLI(DAG);
2575     CLI.setDebugLoc(getCurSDLoc())
2576         .setChain(DAG.getEntryNode())
2577         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2578                    getValue(GuardCheckFn), std::move(Args));
2579 
2580     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2581     DAG.setRoot(Result.second);
2582     return;
2583   }
2584 
2585   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2586   // Otherwise, emit a volatile load to retrieve the stack guard value.
2587   SDValue Chain = DAG.getEntryNode();
2588   if (TLI.useLoadStackGuardNode()) {
2589     Guard = getLoadStackGuard(DAG, dl, Chain);
2590   } else {
2591     const Value *IRGuard = TLI.getSDagStackGuard(M);
2592     SDValue GuardPtr = getValue(IRGuard);
2593 
2594     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2595                         MachinePointerInfo(IRGuard, 0), Align,
2596                         MachineMemOperand::MOVolatile);
2597   }
2598 
2599   // Perform the comparison via a getsetcc.
2600   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2601                                                         *DAG.getContext(),
2602                                                         Guard.getValueType()),
2603                              Guard, GuardVal, ISD::SETNE);
2604 
2605   // If the guard/stackslot do not equal, branch to failure MBB.
2606   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2607                                MVT::Other, GuardVal.getOperand(0),
2608                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2609   // Otherwise branch to success MBB.
2610   SDValue Br = DAG.getNode(ISD::BR, dl,
2611                            MVT::Other, BrCond,
2612                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2613 
2614   DAG.setRoot(Br);
2615 }
2616 
2617 /// Codegen the failure basic block for a stack protector check.
2618 ///
2619 /// A failure stack protector machine basic block consists simply of a call to
2620 /// __stack_chk_fail().
2621 ///
2622 /// For a high level explanation of how this fits into the stack protector
2623 /// generation see the comment on the declaration of class
2624 /// StackProtectorDescriptor.
2625 void
2626 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2628   TargetLowering::MakeLibCallOptions CallOptions;
2629   CallOptions.setDiscardResult(true);
2630   SDValue Chain =
2631       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2632                       None, CallOptions, getCurSDLoc()).second;
2633   // On PS4, the "return address" must still be within the calling function,
2634   // even if it's at the very end, so emit an explicit TRAP here.
2635   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2636   if (TM.getTargetTriple().isPS4CPU())
2637     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2638 
2639   DAG.setRoot(Chain);
2640 }
2641 
2642 /// visitBitTestHeader - This function emits necessary code to produce value
2643 /// suitable for "bit tests"
2644 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2645                                              MachineBasicBlock *SwitchBB) {
2646   SDLoc dl = getCurSDLoc();
2647 
2648   // Subtract the minimum value.
2649   SDValue SwitchOp = getValue(B.SValue);
2650   EVT VT = SwitchOp.getValueType();
2651   SDValue RangeSub =
2652       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2653 
2654   // Determine the type of the test operands.
2655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2656   bool UsePtrType = false;
2657   if (!TLI.isTypeLegal(VT)) {
2658     UsePtrType = true;
2659   } else {
2660     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2661       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2662         // Switch table case range are encoded into series of masks.
2663         // Just use pointer type, it's guaranteed to fit.
2664         UsePtrType = true;
2665         break;
2666       }
2667   }
2668   SDValue Sub = RangeSub;
2669   if (UsePtrType) {
2670     VT = TLI.getPointerTy(DAG.getDataLayout());
2671     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2672   }
2673 
2674   B.RegVT = VT.getSimpleVT();
2675   B.Reg = FuncInfo.CreateReg(B.RegVT);
2676   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2677 
2678   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2679 
2680   if (!B.OmitRangeCheck)
2681     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2682   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2683   SwitchBB->normalizeSuccProbs();
2684 
2685   SDValue Root = CopyTo;
2686   if (!B.OmitRangeCheck) {
2687     // Conditional branch to the default block.
2688     SDValue RangeCmp = DAG.getSetCC(dl,
2689         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2690                                RangeSub.getValueType()),
2691         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2692         ISD::SETUGT);
2693 
2694     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2695                        DAG.getBasicBlock(B.Default));
2696   }
2697 
2698   // Avoid emitting unnecessary branches to the next block.
2699   if (MBB != NextBlock(SwitchBB))
2700     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2701 
2702   DAG.setRoot(Root);
2703 }
2704 
2705 /// visitBitTestCase - this function produces one "bit test"
2706 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2707                                            MachineBasicBlock* NextMBB,
2708                                            BranchProbability BranchProbToNext,
2709                                            unsigned Reg,
2710                                            BitTestCase &B,
2711                                            MachineBasicBlock *SwitchBB) {
2712   SDLoc dl = getCurSDLoc();
2713   MVT VT = BB.RegVT;
2714   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2715   SDValue Cmp;
2716   unsigned PopCount = countPopulation(B.Mask);
2717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2718   if (PopCount == 1) {
2719     // Testing for a single bit; just compare the shift count with what it
2720     // would need to be to shift a 1 bit in that position.
2721     Cmp = DAG.getSetCC(
2722         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2723         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2724         ISD::SETEQ);
2725   } else if (PopCount == BB.Range) {
2726     // There is only one zero bit in the range, test for it directly.
2727     Cmp = DAG.getSetCC(
2728         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2729         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2730         ISD::SETNE);
2731   } else {
2732     // Make desired shift
2733     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2734                                     DAG.getConstant(1, dl, VT), ShiftOp);
2735 
2736     // Emit bit tests and jumps
2737     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2738                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2739     Cmp = DAG.getSetCC(
2740         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2741         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2742   }
2743 
2744   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2745   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2746   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2747   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2748   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2749   // one as they are relative probabilities (and thus work more like weights),
2750   // and hence we need to normalize them to let the sum of them become one.
2751   SwitchBB->normalizeSuccProbs();
2752 
2753   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2754                               MVT::Other, getControlRoot(),
2755                               Cmp, DAG.getBasicBlock(B.TargetBB));
2756 
2757   // Avoid emitting unnecessary branches to the next block.
2758   if (NextMBB != NextBlock(SwitchBB))
2759     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2760                         DAG.getBasicBlock(NextMBB));
2761 
2762   DAG.setRoot(BrAnd);
2763 }
2764 
2765 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2766   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2767 
2768   // Retrieve successors. Look through artificial IR level blocks like
2769   // catchswitch for successors.
2770   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2771   const BasicBlock *EHPadBB = I.getSuccessor(1);
2772 
2773   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2774   // have to do anything here to lower funclet bundles.
2775   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2776                                         LLVMContext::OB_funclet,
2777                                         LLVMContext::OB_cfguardtarget}) &&
2778          "Cannot lower invokes with arbitrary operand bundles yet!");
2779 
2780   const Value *Callee(I.getCalledValue());
2781   const Function *Fn = dyn_cast<Function>(Callee);
2782   if (isa<InlineAsm>(Callee))
2783     visitInlineAsm(&I);
2784   else if (Fn && Fn->isIntrinsic()) {
2785     switch (Fn->getIntrinsicID()) {
2786     default:
2787       llvm_unreachable("Cannot invoke this intrinsic");
2788     case Intrinsic::donothing:
2789       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2790       break;
2791     case Intrinsic::experimental_patchpoint_void:
2792     case Intrinsic::experimental_patchpoint_i64:
2793       visitPatchpoint(&I, EHPadBB);
2794       break;
2795     case Intrinsic::experimental_gc_statepoint:
2796       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2797       break;
2798     case Intrinsic::wasm_rethrow_in_catch: {
2799       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2800       // special because it can be invoked, so we manually lower it to a DAG
2801       // node here.
2802       SmallVector<SDValue, 8> Ops;
2803       Ops.push_back(getRoot()); // inchain
2804       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2805       Ops.push_back(
2806           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2807                                 TLI.getPointerTy(DAG.getDataLayout())));
2808       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2809       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2810       break;
2811     }
2812     }
2813   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2814     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2815     // Eventually we will support lowering the @llvm.experimental.deoptimize
2816     // intrinsic, and right now there are no plans to support other intrinsics
2817     // with deopt state.
2818     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2819   } else {
2820     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2821   }
2822 
2823   // If the value of the invoke is used outside of its defining block, make it
2824   // available as a virtual register.
2825   // We already took care of the exported value for the statepoint instruction
2826   // during call to the LowerStatepoint.
2827   if (!isStatepoint(I)) {
2828     CopyToExportRegsIfNeeded(&I);
2829   }
2830 
2831   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2832   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2833   BranchProbability EHPadBBProb =
2834       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2835           : BranchProbability::getZero();
2836   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2837 
2838   // Update successor info.
2839   addSuccessorWithProb(InvokeMBB, Return);
2840   for (auto &UnwindDest : UnwindDests) {
2841     UnwindDest.first->setIsEHPad();
2842     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2843   }
2844   InvokeMBB->normalizeSuccProbs();
2845 
2846   // Drop into normal successor.
2847   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2848                           DAG.getBasicBlock(Return)));
2849 }
2850 
2851 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2852   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2853 
2854   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2855   // have to do anything here to lower funclet bundles.
2856   assert(!I.hasOperandBundlesOtherThan(
2857              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2858          "Cannot lower callbrs with arbitrary operand bundles yet!");
2859 
2860   assert(isa<InlineAsm>(I.getCalledValue()) &&
2861          "Only know how to handle inlineasm callbr");
2862   visitInlineAsm(&I);
2863 
2864   // Retrieve successors.
2865   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2866 
2867   // Update successor info.
2868   addSuccessorWithProb(CallBrMBB, Return);
2869   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2870     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2871     addSuccessorWithProb(CallBrMBB, Target);
2872   }
2873   CallBrMBB->normalizeSuccProbs();
2874 
2875   // Drop into default successor.
2876   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2877                           MVT::Other, getControlRoot(),
2878                           DAG.getBasicBlock(Return)));
2879 }
2880 
2881 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2882   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2883 }
2884 
2885 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2886   assert(FuncInfo.MBB->isEHPad() &&
2887          "Call to landingpad not in landing pad!");
2888 
2889   // If there aren't registers to copy the values into (e.g., during SjLj
2890   // exceptions), then don't bother to create these DAG nodes.
2891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2892   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2893   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2894       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2895     return;
2896 
2897   // If landingpad's return type is token type, we don't create DAG nodes
2898   // for its exception pointer and selector value. The extraction of exception
2899   // pointer or selector value from token type landingpads is not currently
2900   // supported.
2901   if (LP.getType()->isTokenTy())
2902     return;
2903 
2904   SmallVector<EVT, 2> ValueVTs;
2905   SDLoc dl = getCurSDLoc();
2906   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2907   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2908 
2909   // Get the two live-in registers as SDValues. The physregs have already been
2910   // copied into virtual registers.
2911   SDValue Ops[2];
2912   if (FuncInfo.ExceptionPointerVirtReg) {
2913     Ops[0] = DAG.getZExtOrTrunc(
2914         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2915                            FuncInfo.ExceptionPointerVirtReg,
2916                            TLI.getPointerTy(DAG.getDataLayout())),
2917         dl, ValueVTs[0]);
2918   } else {
2919     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2920   }
2921   Ops[1] = DAG.getZExtOrTrunc(
2922       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2923                          FuncInfo.ExceptionSelectorVirtReg,
2924                          TLI.getPointerTy(DAG.getDataLayout())),
2925       dl, ValueVTs[1]);
2926 
2927   // Merge into one.
2928   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2929                             DAG.getVTList(ValueVTs), Ops);
2930   setValue(&LP, Res);
2931 }
2932 
2933 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2934                                            MachineBasicBlock *Last) {
2935   // Update JTCases.
2936   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2937     if (SL->JTCases[i].first.HeaderBB == First)
2938       SL->JTCases[i].first.HeaderBB = Last;
2939 
2940   // Update BitTestCases.
2941   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2942     if (SL->BitTestCases[i].Parent == First)
2943       SL->BitTestCases[i].Parent = Last;
2944 }
2945 
2946 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2947   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2948 
2949   // Update machine-CFG edges with unique successors.
2950   SmallSet<BasicBlock*, 32> Done;
2951   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2952     BasicBlock *BB = I.getSuccessor(i);
2953     bool Inserted = Done.insert(BB).second;
2954     if (!Inserted)
2955         continue;
2956 
2957     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2958     addSuccessorWithProb(IndirectBrMBB, Succ);
2959   }
2960   IndirectBrMBB->normalizeSuccProbs();
2961 
2962   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2963                           MVT::Other, getControlRoot(),
2964                           getValue(I.getAddress())));
2965 }
2966 
2967 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2968   if (!DAG.getTarget().Options.TrapUnreachable)
2969     return;
2970 
2971   // We may be able to ignore unreachable behind a noreturn call.
2972   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2973     const BasicBlock &BB = *I.getParent();
2974     if (&I != &BB.front()) {
2975       BasicBlock::const_iterator PredI =
2976         std::prev(BasicBlock::const_iterator(&I));
2977       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2978         if (Call->doesNotReturn())
2979           return;
2980       }
2981     }
2982   }
2983 
2984   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2985 }
2986 
2987 void SelectionDAGBuilder::visitFSub(const User &I) {
2988   // -0.0 - X --> fneg
2989   Type *Ty = I.getType();
2990   if (isa<Constant>(I.getOperand(0)) &&
2991       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2992     SDValue Op2 = getValue(I.getOperand(1));
2993     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2994                              Op2.getValueType(), Op2));
2995     return;
2996   }
2997 
2998   visitBinary(I, ISD::FSUB);
2999 }
3000 
3001 /// Checks if the given instruction performs a vector reduction, in which case
3002 /// we have the freedom to alter the elements in the result as long as the
3003 /// reduction of them stays unchanged.
3004 static bool isVectorReductionOp(const User *I) {
3005   const Instruction *Inst = dyn_cast<Instruction>(I);
3006   if (!Inst || !Inst->getType()->isVectorTy())
3007     return false;
3008 
3009   auto OpCode = Inst->getOpcode();
3010   switch (OpCode) {
3011   case Instruction::Add:
3012   case Instruction::Mul:
3013   case Instruction::And:
3014   case Instruction::Or:
3015   case Instruction::Xor:
3016     break;
3017   case Instruction::FAdd:
3018   case Instruction::FMul:
3019     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3020       if (FPOp->getFastMathFlags().isFast())
3021         break;
3022     LLVM_FALLTHROUGH;
3023   default:
3024     return false;
3025   }
3026 
3027   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3028   // Ensure the reduction size is a power of 2.
3029   if (!isPowerOf2_32(ElemNum))
3030     return false;
3031 
3032   unsigned ElemNumToReduce = ElemNum;
3033 
3034   // Do DFS search on the def-use chain from the given instruction. We only
3035   // allow four kinds of operations during the search until we reach the
3036   // instruction that extracts the first element from the vector:
3037   //
3038   //   1. The reduction operation of the same opcode as the given instruction.
3039   //
3040   //   2. PHI node.
3041   //
3042   //   3. ShuffleVector instruction together with a reduction operation that
3043   //      does a partial reduction.
3044   //
3045   //   4. ExtractElement that extracts the first element from the vector, and we
3046   //      stop searching the def-use chain here.
3047   //
3048   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3049   // from 1-3 to the stack to continue the DFS. The given instruction is not
3050   // a reduction operation if we meet any other instructions other than those
3051   // listed above.
3052 
3053   SmallVector<const User *, 16> UsersToVisit{Inst};
3054   SmallPtrSet<const User *, 16> Visited;
3055   bool ReduxExtracted = false;
3056 
3057   while (!UsersToVisit.empty()) {
3058     auto User = UsersToVisit.back();
3059     UsersToVisit.pop_back();
3060     if (!Visited.insert(User).second)
3061       continue;
3062 
3063     for (const auto *U : User->users()) {
3064       auto Inst = dyn_cast<Instruction>(U);
3065       if (!Inst)
3066         return false;
3067 
3068       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3069         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3070           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3071             return false;
3072         UsersToVisit.push_back(U);
3073       } else if (const ShuffleVectorInst *ShufInst =
3074                      dyn_cast<ShuffleVectorInst>(U)) {
3075         // Detect the following pattern: A ShuffleVector instruction together
3076         // with a reduction that do partial reduction on the first and second
3077         // ElemNumToReduce / 2 elements, and store the result in
3078         // ElemNumToReduce / 2 elements in another vector.
3079 
3080         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3081         if (ResultElements < ElemNum)
3082           return false;
3083 
3084         if (ElemNumToReduce == 1)
3085           return false;
3086         if (!isa<UndefValue>(U->getOperand(1)))
3087           return false;
3088         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3089           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3090             return false;
3091         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3092           if (ShufInst->getMaskValue(i) != -1)
3093             return false;
3094 
3095         // There is only one user of this ShuffleVector instruction, which
3096         // must be a reduction operation.
3097         if (!U->hasOneUse())
3098           return false;
3099 
3100         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3101         if (!U2 || U2->getOpcode() != OpCode)
3102           return false;
3103 
3104         // Check operands of the reduction operation.
3105         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3106             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3107           UsersToVisit.push_back(U2);
3108           ElemNumToReduce /= 2;
3109         } else
3110           return false;
3111       } else if (isa<ExtractElementInst>(U)) {
3112         // At this moment we should have reduced all elements in the vector.
3113         if (ElemNumToReduce != 1)
3114           return false;
3115 
3116         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3117         if (!Val || !Val->isZero())
3118           return false;
3119 
3120         ReduxExtracted = true;
3121       } else
3122         return false;
3123     }
3124   }
3125   return ReduxExtracted;
3126 }
3127 
3128 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3129   SDNodeFlags Flags;
3130 
3131   SDValue Op = getValue(I.getOperand(0));
3132   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3133                                     Op, Flags);
3134   setValue(&I, UnNodeValue);
3135 }
3136 
3137 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3138   SDNodeFlags Flags;
3139   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3140     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3141     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3142   }
3143   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3144     Flags.setExact(ExactOp->isExact());
3145   }
3146   if (isVectorReductionOp(&I)) {
3147     Flags.setVectorReduction(true);
3148     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3149 
3150     // If no flags are set we will propagate the incoming flags, if any flags
3151     // are set, we will intersect them with the incoming flag and so we need to
3152     // copy the FMF flags here.
3153     if (auto *FPOp = dyn_cast<FPMathOperator>(&I)) {
3154       Flags.copyFMF(*FPOp);
3155     }
3156   }
3157 
3158   SDValue Op1 = getValue(I.getOperand(0));
3159   SDValue Op2 = getValue(I.getOperand(1));
3160   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3161                                      Op1, Op2, Flags);
3162   setValue(&I, BinNodeValue);
3163 }
3164 
3165 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3166   SDValue Op1 = getValue(I.getOperand(0));
3167   SDValue Op2 = getValue(I.getOperand(1));
3168 
3169   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3170       Op1.getValueType(), DAG.getDataLayout());
3171 
3172   // Coerce the shift amount to the right type if we can.
3173   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3174     unsigned ShiftSize = ShiftTy.getSizeInBits();
3175     unsigned Op2Size = Op2.getValueSizeInBits();
3176     SDLoc DL = getCurSDLoc();
3177 
3178     // If the operand is smaller than the shift count type, promote it.
3179     if (ShiftSize > Op2Size)
3180       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3181 
3182     // If the operand is larger than the shift count type but the shift
3183     // count type has enough bits to represent any shift value, truncate
3184     // it now. This is a common case and it exposes the truncate to
3185     // optimization early.
3186     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3187       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3188     // Otherwise we'll need to temporarily settle for some other convenient
3189     // type.  Type legalization will make adjustments once the shiftee is split.
3190     else
3191       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3192   }
3193 
3194   bool nuw = false;
3195   bool nsw = false;
3196   bool exact = false;
3197 
3198   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3199 
3200     if (const OverflowingBinaryOperator *OFBinOp =
3201             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3202       nuw = OFBinOp->hasNoUnsignedWrap();
3203       nsw = OFBinOp->hasNoSignedWrap();
3204     }
3205     if (const PossiblyExactOperator *ExactOp =
3206             dyn_cast<const PossiblyExactOperator>(&I))
3207       exact = ExactOp->isExact();
3208   }
3209   SDNodeFlags Flags;
3210   Flags.setExact(exact);
3211   Flags.setNoSignedWrap(nsw);
3212   Flags.setNoUnsignedWrap(nuw);
3213   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3214                             Flags);
3215   setValue(&I, Res);
3216 }
3217 
3218 void SelectionDAGBuilder::visitSDiv(const User &I) {
3219   SDValue Op1 = getValue(I.getOperand(0));
3220   SDValue Op2 = getValue(I.getOperand(1));
3221 
3222   SDNodeFlags Flags;
3223   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3224                  cast<PossiblyExactOperator>(&I)->isExact());
3225   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3226                            Op2, Flags));
3227 }
3228 
3229 void SelectionDAGBuilder::visitICmp(const User &I) {
3230   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3231   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3232     predicate = IC->getPredicate();
3233   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3234     predicate = ICmpInst::Predicate(IC->getPredicate());
3235   SDValue Op1 = getValue(I.getOperand(0));
3236   SDValue Op2 = getValue(I.getOperand(1));
3237   ISD::CondCode Opcode = getICmpCondCode(predicate);
3238 
3239   auto &TLI = DAG.getTargetLoweringInfo();
3240   EVT MemVT =
3241       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3242 
3243   // If a pointer's DAG type is larger than its memory type then the DAG values
3244   // are zero-extended. This breaks signed comparisons so truncate back to the
3245   // underlying type before doing the compare.
3246   if (Op1.getValueType() != MemVT) {
3247     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3248     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3249   }
3250 
3251   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3252                                                         I.getType());
3253   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3254 }
3255 
3256 void SelectionDAGBuilder::visitFCmp(const User &I) {
3257   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3258   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3259     predicate = FC->getPredicate();
3260   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3261     predicate = FCmpInst::Predicate(FC->getPredicate());
3262   SDValue Op1 = getValue(I.getOperand(0));
3263   SDValue Op2 = getValue(I.getOperand(1));
3264 
3265   ISD::CondCode Condition = getFCmpCondCode(predicate);
3266   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3267   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3268     Condition = getFCmpCodeWithoutNaN(Condition);
3269 
3270   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3271                                                         I.getType());
3272   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3273 }
3274 
3275 // Check if the condition of the select has one use or two users that are both
3276 // selects with the same condition.
3277 static bool hasOnlySelectUsers(const Value *Cond) {
3278   return llvm::all_of(Cond->users(), [](const Value *V) {
3279     return isa<SelectInst>(V);
3280   });
3281 }
3282 
3283 void SelectionDAGBuilder::visitSelect(const User &I) {
3284   SmallVector<EVT, 4> ValueVTs;
3285   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3286                   ValueVTs);
3287   unsigned NumValues = ValueVTs.size();
3288   if (NumValues == 0) return;
3289 
3290   SmallVector<SDValue, 4> Values(NumValues);
3291   SDValue Cond     = getValue(I.getOperand(0));
3292   SDValue LHSVal   = getValue(I.getOperand(1));
3293   SDValue RHSVal   = getValue(I.getOperand(2));
3294   SmallVector<SDValue, 1> BaseOps(1, Cond);
3295   ISD::NodeType OpCode =
3296       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3297 
3298   bool IsUnaryAbs = false;
3299 
3300   // Min/max matching is only viable if all output VTs are the same.
3301   if (is_splat(ValueVTs)) {
3302     EVT VT = ValueVTs[0];
3303     LLVMContext &Ctx = *DAG.getContext();
3304     auto &TLI = DAG.getTargetLoweringInfo();
3305 
3306     // We care about the legality of the operation after it has been type
3307     // legalized.
3308     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3309       VT = TLI.getTypeToTransformTo(Ctx, VT);
3310 
3311     // If the vselect is legal, assume we want to leave this as a vector setcc +
3312     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3313     // min/max is legal on the scalar type.
3314     bool UseScalarMinMax = VT.isVector() &&
3315       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3316 
3317     Value *LHS, *RHS;
3318     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3319     ISD::NodeType Opc = ISD::DELETED_NODE;
3320     switch (SPR.Flavor) {
3321     case SPF_UMAX:    Opc = ISD::UMAX; break;
3322     case SPF_UMIN:    Opc = ISD::UMIN; break;
3323     case SPF_SMAX:    Opc = ISD::SMAX; break;
3324     case SPF_SMIN:    Opc = ISD::SMIN; break;
3325     case SPF_FMINNUM:
3326       switch (SPR.NaNBehavior) {
3327       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3328       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3329       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3330       case SPNB_RETURNS_ANY: {
3331         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3332           Opc = ISD::FMINNUM;
3333         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3334           Opc = ISD::FMINIMUM;
3335         else if (UseScalarMinMax)
3336           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3337             ISD::FMINNUM : ISD::FMINIMUM;
3338         break;
3339       }
3340       }
3341       break;
3342     case SPF_FMAXNUM:
3343       switch (SPR.NaNBehavior) {
3344       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3345       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3346       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3347       case SPNB_RETURNS_ANY:
3348 
3349         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3350           Opc = ISD::FMAXNUM;
3351         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3352           Opc = ISD::FMAXIMUM;
3353         else if (UseScalarMinMax)
3354           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3355             ISD::FMAXNUM : ISD::FMAXIMUM;
3356         break;
3357       }
3358       break;
3359     case SPF_ABS:
3360       IsUnaryAbs = true;
3361       Opc = ISD::ABS;
3362       break;
3363     case SPF_NABS:
3364       // TODO: we need to produce sub(0, abs(X)).
3365     default: break;
3366     }
3367 
3368     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3369         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3370          (UseScalarMinMax &&
3371           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3372         // If the underlying comparison instruction is used by any other
3373         // instruction, the consumed instructions won't be destroyed, so it is
3374         // not profitable to convert to a min/max.
3375         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3376       OpCode = Opc;
3377       LHSVal = getValue(LHS);
3378       RHSVal = getValue(RHS);
3379       BaseOps.clear();
3380     }
3381 
3382     if (IsUnaryAbs) {
3383       OpCode = Opc;
3384       LHSVal = getValue(LHS);
3385       BaseOps.clear();
3386     }
3387   }
3388 
3389   if (IsUnaryAbs) {
3390     for (unsigned i = 0; i != NumValues; ++i) {
3391       Values[i] =
3392           DAG.getNode(OpCode, getCurSDLoc(),
3393                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3394                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3395     }
3396   } else {
3397     for (unsigned i = 0; i != NumValues; ++i) {
3398       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3399       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3400       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3401       Values[i] = DAG.getNode(
3402           OpCode, getCurSDLoc(),
3403           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3404     }
3405   }
3406 
3407   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3408                            DAG.getVTList(ValueVTs), Values));
3409 }
3410 
3411 void SelectionDAGBuilder::visitTrunc(const User &I) {
3412   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3413   SDValue N = getValue(I.getOperand(0));
3414   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3415                                                         I.getType());
3416   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3417 }
3418 
3419 void SelectionDAGBuilder::visitZExt(const User &I) {
3420   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3421   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3422   SDValue N = getValue(I.getOperand(0));
3423   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3424                                                         I.getType());
3425   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3426 }
3427 
3428 void SelectionDAGBuilder::visitSExt(const User &I) {
3429   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3430   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3431   SDValue N = getValue(I.getOperand(0));
3432   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3433                                                         I.getType());
3434   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3435 }
3436 
3437 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3438   // FPTrunc is never a no-op cast, no need to check
3439   SDValue N = getValue(I.getOperand(0));
3440   SDLoc dl = getCurSDLoc();
3441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3442   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3443   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3444                            DAG.getTargetConstant(
3445                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3446 }
3447 
3448 void SelectionDAGBuilder::visitFPExt(const User &I) {
3449   // FPExt is never a no-op cast, no need to check
3450   SDValue N = getValue(I.getOperand(0));
3451   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3452                                                         I.getType());
3453   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3454 }
3455 
3456 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3457   // FPToUI is never a no-op cast, no need to check
3458   SDValue N = getValue(I.getOperand(0));
3459   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3460                                                         I.getType());
3461   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3462 }
3463 
3464 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3465   // FPToSI is never a no-op cast, no need to check
3466   SDValue N = getValue(I.getOperand(0));
3467   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3468                                                         I.getType());
3469   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3470 }
3471 
3472 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3473   // UIToFP is never a no-op cast, no need to check
3474   SDValue N = getValue(I.getOperand(0));
3475   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3476                                                         I.getType());
3477   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3478 }
3479 
3480 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3481   // SIToFP is never a no-op cast, no need to check
3482   SDValue N = getValue(I.getOperand(0));
3483   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3484                                                         I.getType());
3485   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3486 }
3487 
3488 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3489   // What to do depends on the size of the integer and the size of the pointer.
3490   // We can either truncate, zero extend, or no-op, accordingly.
3491   SDValue N = getValue(I.getOperand(0));
3492   auto &TLI = DAG.getTargetLoweringInfo();
3493   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3494                                                         I.getType());
3495   EVT PtrMemVT =
3496       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3497   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3498   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3499   setValue(&I, N);
3500 }
3501 
3502 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3503   // What to do depends on the size of the integer and the size of the pointer.
3504   // We can either truncate, zero extend, or no-op, accordingly.
3505   SDValue N = getValue(I.getOperand(0));
3506   auto &TLI = DAG.getTargetLoweringInfo();
3507   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3508   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3509   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3510   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3511   setValue(&I, N);
3512 }
3513 
3514 void SelectionDAGBuilder::visitBitCast(const User &I) {
3515   SDValue N = getValue(I.getOperand(0));
3516   SDLoc dl = getCurSDLoc();
3517   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3518                                                         I.getType());
3519 
3520   // BitCast assures us that source and destination are the same size so this is
3521   // either a BITCAST or a no-op.
3522   if (DestVT != N.getValueType())
3523     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3524                              DestVT, N)); // convert types.
3525   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3526   // might fold any kind of constant expression to an integer constant and that
3527   // is not what we are looking for. Only recognize a bitcast of a genuine
3528   // constant integer as an opaque constant.
3529   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3530     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3531                                  /*isOpaque*/true));
3532   else
3533     setValue(&I, N);            // noop cast.
3534 }
3535 
3536 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3538   const Value *SV = I.getOperand(0);
3539   SDValue N = getValue(SV);
3540   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3541 
3542   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3543   unsigned DestAS = I.getType()->getPointerAddressSpace();
3544 
3545   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3546     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3547 
3548   setValue(&I, N);
3549 }
3550 
3551 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3553   SDValue InVec = getValue(I.getOperand(0));
3554   SDValue InVal = getValue(I.getOperand(1));
3555   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3556                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3557   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3558                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3559                            InVec, InVal, InIdx));
3560 }
3561 
3562 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3563   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3564   SDValue InVec = getValue(I.getOperand(0));
3565   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3566                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3567   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3568                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3569                            InVec, InIdx));
3570 }
3571 
3572 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3573   SDValue Src1 = getValue(I.getOperand(0));
3574   SDValue Src2 = getValue(I.getOperand(1));
3575   Constant *MaskV = cast<Constant>(I.getOperand(2));
3576   SDLoc DL = getCurSDLoc();
3577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3578   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3579   EVT SrcVT = Src1.getValueType();
3580   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3581 
3582   if (MaskV->isNullValue() && VT.isScalableVector()) {
3583     // Canonical splat form of first element of first input vector.
3584     SDValue FirstElt =
3585         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3586                     DAG.getVectorIdxConstant(0, DL));
3587     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3588     return;
3589   }
3590 
3591   // For now, we only handle splats for scalable vectors.
3592   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3593   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3594   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3595 
3596   SmallVector<int, 8> Mask;
3597   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3598   unsigned MaskNumElts = Mask.size();
3599 
3600   if (SrcNumElts == MaskNumElts) {
3601     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3602     return;
3603   }
3604 
3605   // Normalize the shuffle vector since mask and vector length don't match.
3606   if (SrcNumElts < MaskNumElts) {
3607     // Mask is longer than the source vectors. We can use concatenate vector to
3608     // make the mask and vectors lengths match.
3609 
3610     if (MaskNumElts % SrcNumElts == 0) {
3611       // Mask length is a multiple of the source vector length.
3612       // Check if the shuffle is some kind of concatenation of the input
3613       // vectors.
3614       unsigned NumConcat = MaskNumElts / SrcNumElts;
3615       bool IsConcat = true;
3616       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3617       for (unsigned i = 0; i != MaskNumElts; ++i) {
3618         int Idx = Mask[i];
3619         if (Idx < 0)
3620           continue;
3621         // Ensure the indices in each SrcVT sized piece are sequential and that
3622         // the same source is used for the whole piece.
3623         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3624             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3625              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3626           IsConcat = false;
3627           break;
3628         }
3629         // Remember which source this index came from.
3630         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3631       }
3632 
3633       // The shuffle is concatenating multiple vectors together. Just emit
3634       // a CONCAT_VECTORS operation.
3635       if (IsConcat) {
3636         SmallVector<SDValue, 8> ConcatOps;
3637         for (auto Src : ConcatSrcs) {
3638           if (Src < 0)
3639             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3640           else if (Src == 0)
3641             ConcatOps.push_back(Src1);
3642           else
3643             ConcatOps.push_back(Src2);
3644         }
3645         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3646         return;
3647       }
3648     }
3649 
3650     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3651     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3652     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3653                                     PaddedMaskNumElts);
3654 
3655     // Pad both vectors with undefs to make them the same length as the mask.
3656     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3657 
3658     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3659     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3660     MOps1[0] = Src1;
3661     MOps2[0] = Src2;
3662 
3663     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3664     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3665 
3666     // Readjust mask for new input vector length.
3667     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3668     for (unsigned i = 0; i != MaskNumElts; ++i) {
3669       int Idx = Mask[i];
3670       if (Idx >= (int)SrcNumElts)
3671         Idx -= SrcNumElts - PaddedMaskNumElts;
3672       MappedOps[i] = Idx;
3673     }
3674 
3675     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3676 
3677     // If the concatenated vector was padded, extract a subvector with the
3678     // correct number of elements.
3679     if (MaskNumElts != PaddedMaskNumElts)
3680       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3681                            DAG.getVectorIdxConstant(0, DL));
3682 
3683     setValue(&I, Result);
3684     return;
3685   }
3686 
3687   if (SrcNumElts > MaskNumElts) {
3688     // Analyze the access pattern of the vector to see if we can extract
3689     // two subvectors and do the shuffle.
3690     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3691     bool CanExtract = true;
3692     for (int Idx : Mask) {
3693       unsigned Input = 0;
3694       if (Idx < 0)
3695         continue;
3696 
3697       if (Idx >= (int)SrcNumElts) {
3698         Input = 1;
3699         Idx -= SrcNumElts;
3700       }
3701 
3702       // If all the indices come from the same MaskNumElts sized portion of
3703       // the sources we can use extract. Also make sure the extract wouldn't
3704       // extract past the end of the source.
3705       int NewStartIdx = alignDown(Idx, MaskNumElts);
3706       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3707           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3708         CanExtract = false;
3709       // Make sure we always update StartIdx as we use it to track if all
3710       // elements are undef.
3711       StartIdx[Input] = NewStartIdx;
3712     }
3713 
3714     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3715       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3716       return;
3717     }
3718     if (CanExtract) {
3719       // Extract appropriate subvector and generate a vector shuffle
3720       for (unsigned Input = 0; Input < 2; ++Input) {
3721         SDValue &Src = Input == 0 ? Src1 : Src2;
3722         if (StartIdx[Input] < 0)
3723           Src = DAG.getUNDEF(VT);
3724         else {
3725           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3726                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
3727         }
3728       }
3729 
3730       // Calculate new mask.
3731       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3732       for (int &Idx : MappedOps) {
3733         if (Idx >= (int)SrcNumElts)
3734           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3735         else if (Idx >= 0)
3736           Idx -= StartIdx[0];
3737       }
3738 
3739       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3740       return;
3741     }
3742   }
3743 
3744   // We can't use either concat vectors or extract subvectors so fall back to
3745   // replacing the shuffle with extract and build vector.
3746   // to insert and build vector.
3747   EVT EltVT = VT.getVectorElementType();
3748   SmallVector<SDValue,8> Ops;
3749   for (int Idx : Mask) {
3750     SDValue Res;
3751 
3752     if (Idx < 0) {
3753       Res = DAG.getUNDEF(EltVT);
3754     } else {
3755       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3756       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3757 
3758       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
3759                         DAG.getVectorIdxConstant(Idx, DL));
3760     }
3761 
3762     Ops.push_back(Res);
3763   }
3764 
3765   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3766 }
3767 
3768 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3769   ArrayRef<unsigned> Indices;
3770   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3771     Indices = IV->getIndices();
3772   else
3773     Indices = cast<ConstantExpr>(&I)->getIndices();
3774 
3775   const Value *Op0 = I.getOperand(0);
3776   const Value *Op1 = I.getOperand(1);
3777   Type *AggTy = I.getType();
3778   Type *ValTy = Op1->getType();
3779   bool IntoUndef = isa<UndefValue>(Op0);
3780   bool FromUndef = isa<UndefValue>(Op1);
3781 
3782   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3783 
3784   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3785   SmallVector<EVT, 4> AggValueVTs;
3786   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3787   SmallVector<EVT, 4> ValValueVTs;
3788   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3789 
3790   unsigned NumAggValues = AggValueVTs.size();
3791   unsigned NumValValues = ValValueVTs.size();
3792   SmallVector<SDValue, 4> Values(NumAggValues);
3793 
3794   // Ignore an insertvalue that produces an empty object
3795   if (!NumAggValues) {
3796     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3797     return;
3798   }
3799 
3800   SDValue Agg = getValue(Op0);
3801   unsigned i = 0;
3802   // Copy the beginning value(s) from the original aggregate.
3803   for (; i != LinearIndex; ++i)
3804     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3805                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3806   // Copy values from the inserted value(s).
3807   if (NumValValues) {
3808     SDValue Val = getValue(Op1);
3809     for (; i != LinearIndex + NumValValues; ++i)
3810       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3811                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3812   }
3813   // Copy remaining value(s) from the original aggregate.
3814   for (; i != NumAggValues; ++i)
3815     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3816                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3817 
3818   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3819                            DAG.getVTList(AggValueVTs), Values));
3820 }
3821 
3822 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3823   ArrayRef<unsigned> Indices;
3824   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3825     Indices = EV->getIndices();
3826   else
3827     Indices = cast<ConstantExpr>(&I)->getIndices();
3828 
3829   const Value *Op0 = I.getOperand(0);
3830   Type *AggTy = Op0->getType();
3831   Type *ValTy = I.getType();
3832   bool OutOfUndef = isa<UndefValue>(Op0);
3833 
3834   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3835 
3836   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3837   SmallVector<EVT, 4> ValValueVTs;
3838   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3839 
3840   unsigned NumValValues = ValValueVTs.size();
3841 
3842   // Ignore a extractvalue that produces an empty object
3843   if (!NumValValues) {
3844     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3845     return;
3846   }
3847 
3848   SmallVector<SDValue, 4> Values(NumValValues);
3849 
3850   SDValue Agg = getValue(Op0);
3851   // Copy out the selected value(s).
3852   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3853     Values[i - LinearIndex] =
3854       OutOfUndef ?
3855         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3856         SDValue(Agg.getNode(), Agg.getResNo() + i);
3857 
3858   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3859                            DAG.getVTList(ValValueVTs), Values));
3860 }
3861 
3862 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3863   Value *Op0 = I.getOperand(0);
3864   // Note that the pointer operand may be a vector of pointers. Take the scalar
3865   // element which holds a pointer.
3866   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3867   SDValue N = getValue(Op0);
3868   SDLoc dl = getCurSDLoc();
3869   auto &TLI = DAG.getTargetLoweringInfo();
3870   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3871   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3872 
3873   // Normalize Vector GEP - all scalar operands should be converted to the
3874   // splat vector.
3875   bool IsVectorGEP = I.getType()->isVectorTy();
3876   ElementCount VectorElementCount = IsVectorGEP ?
3877     I.getType()->getVectorElementCount() : ElementCount(0, false);
3878 
3879   if (IsVectorGEP && !N.getValueType().isVector()) {
3880     LLVMContext &Context = *DAG.getContext();
3881     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
3882     if (VectorElementCount.Scalable)
3883       N = DAG.getSplatVector(VT, dl, N);
3884     else
3885       N = DAG.getSplatBuildVector(VT, dl, N);
3886   }
3887 
3888   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3889        GTI != E; ++GTI) {
3890     const Value *Idx = GTI.getOperand();
3891     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3892       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3893       if (Field) {
3894         // N = N + Offset
3895         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3896 
3897         // In an inbounds GEP with an offset that is nonnegative even when
3898         // interpreted as signed, assume there is no unsigned overflow.
3899         SDNodeFlags Flags;
3900         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3901           Flags.setNoUnsignedWrap(true);
3902 
3903         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3904                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3905       }
3906     } else {
3907       // IdxSize is the width of the arithmetic according to IR semantics.
3908       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
3909       // (and fix up the result later).
3910       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3911       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3912       TypeSize ElementSize = DL->getTypeAllocSize(GTI.getIndexedType());
3913       // We intentionally mask away the high bits here; ElementSize may not
3914       // fit in IdxTy.
3915       APInt ElementMul(IdxSize, ElementSize.getKnownMinSize());
3916       bool ElementScalable = ElementSize.isScalable();
3917 
3918       // If this is a scalar constant or a splat vector of constants,
3919       // handle it quickly.
3920       const auto *C = dyn_cast<Constant>(Idx);
3921       if (C && isa<VectorType>(C->getType()))
3922         C = C->getSplatValue();
3923 
3924       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
3925       if (CI && CI->isZero())
3926         continue;
3927       if (CI && !ElementScalable) {
3928         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
3929         LLVMContext &Context = *DAG.getContext();
3930         SDValue OffsVal;
3931         if (IsVectorGEP)
3932           OffsVal = DAG.getConstant(
3933               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
3934         else
3935           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
3936 
3937         // In an inbounds GEP with an offset that is nonnegative even when
3938         // interpreted as signed, assume there is no unsigned overflow.
3939         SDNodeFlags Flags;
3940         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3941           Flags.setNoUnsignedWrap(true);
3942 
3943         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3944 
3945         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3946         continue;
3947       }
3948 
3949       // N = N + Idx * ElementMul;
3950       SDValue IdxN = getValue(Idx);
3951 
3952       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
3953         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
3954                                   VectorElementCount);
3955         if (VectorElementCount.Scalable)
3956           IdxN = DAG.getSplatVector(VT, dl, IdxN);
3957         else
3958           IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3959       }
3960 
3961       // If the index is smaller or larger than intptr_t, truncate or extend
3962       // it.
3963       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3964 
3965       if (ElementScalable) {
3966         EVT VScaleTy = N.getValueType().getScalarType();
3967         SDValue VScale = DAG.getNode(
3968             ISD::VSCALE, dl, VScaleTy,
3969             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
3970         if (IsVectorGEP)
3971           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
3972         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
3973       } else {
3974         // If this is a multiply by a power of two, turn it into a shl
3975         // immediately.  This is a very common case.
3976         if (ElementMul != 1) {
3977           if (ElementMul.isPowerOf2()) {
3978             unsigned Amt = ElementMul.logBase2();
3979             IdxN = DAG.getNode(ISD::SHL, dl,
3980                                N.getValueType(), IdxN,
3981                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
3982           } else {
3983             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
3984                                             IdxN.getValueType());
3985             IdxN = DAG.getNode(ISD::MUL, dl,
3986                                N.getValueType(), IdxN, Scale);
3987           }
3988         }
3989       }
3990 
3991       N = DAG.getNode(ISD::ADD, dl,
3992                       N.getValueType(), N, IdxN);
3993     }
3994   }
3995 
3996   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3997     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3998 
3999   setValue(&I, N);
4000 }
4001 
4002 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4003   // If this is a fixed sized alloca in the entry block of the function,
4004   // allocate it statically on the stack.
4005   if (FuncInfo.StaticAllocaMap.count(&I))
4006     return;   // getValue will auto-populate this.
4007 
4008   SDLoc dl = getCurSDLoc();
4009   Type *Ty = I.getAllocatedType();
4010   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4011   auto &DL = DAG.getDataLayout();
4012   uint64_t TySize = DL.getTypeAllocSize(Ty);
4013   unsigned Align =
4014       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
4015 
4016   SDValue AllocSize = getValue(I.getArraySize());
4017 
4018   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
4019   if (AllocSize.getValueType() != IntPtr)
4020     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4021 
4022   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
4023                           AllocSize,
4024                           DAG.getConstant(TySize, dl, IntPtr));
4025 
4026   // Handle alignment.  If the requested alignment is less than or equal to
4027   // the stack alignment, ignore it.  If the size is greater than or equal to
4028   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4029   unsigned StackAlign =
4030       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
4031   if (Align <= StackAlign)
4032     Align = 0;
4033 
4034   // Round the size of the allocation up to the stack alignment size
4035   // by add SA-1 to the size. This doesn't overflow because we're computing
4036   // an address inside an alloca.
4037   SDNodeFlags Flags;
4038   Flags.setNoUnsignedWrap(true);
4039   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4040                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
4041 
4042   // Mask out the low bits for alignment purposes.
4043   AllocSize =
4044       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4045                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
4046 
4047   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
4048   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4049   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4050   setValue(&I, DSA);
4051   DAG.setRoot(DSA.getValue(1));
4052 
4053   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4054 }
4055 
4056 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4057   if (I.isAtomic())
4058     return visitAtomicLoad(I);
4059 
4060   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4061   const Value *SV = I.getOperand(0);
4062   if (TLI.supportSwiftError()) {
4063     // Swifterror values can come from either a function parameter with
4064     // swifterror attribute or an alloca with swifterror attribute.
4065     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4066       if (Arg->hasSwiftErrorAttr())
4067         return visitLoadFromSwiftError(I);
4068     }
4069 
4070     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4071       if (Alloca->isSwiftError())
4072         return visitLoadFromSwiftError(I);
4073     }
4074   }
4075 
4076   SDValue Ptr = getValue(SV);
4077 
4078   Type *Ty = I.getType();
4079   unsigned Alignment = I.getAlignment();
4080 
4081   AAMDNodes AAInfo;
4082   I.getAAMetadata(AAInfo);
4083   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4084 
4085   SmallVector<EVT, 4> ValueVTs, MemVTs;
4086   SmallVector<uint64_t, 4> Offsets;
4087   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4088   unsigned NumValues = ValueVTs.size();
4089   if (NumValues == 0)
4090     return;
4091 
4092   bool isVolatile = I.isVolatile();
4093 
4094   SDValue Root;
4095   bool ConstantMemory = false;
4096   if (isVolatile)
4097     // Serialize volatile loads with other side effects.
4098     Root = getRoot();
4099   else if (NumValues > MaxParallelChains)
4100     Root = getMemoryRoot();
4101   else if (AA &&
4102            AA->pointsToConstantMemory(MemoryLocation(
4103                SV,
4104                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4105                AAInfo))) {
4106     // Do not serialize (non-volatile) loads of constant memory with anything.
4107     Root = DAG.getEntryNode();
4108     ConstantMemory = true;
4109   } else {
4110     // Do not serialize non-volatile loads against each other.
4111     Root = DAG.getRoot();
4112   }
4113 
4114   SDLoc dl = getCurSDLoc();
4115 
4116   if (isVolatile)
4117     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4118 
4119   // An aggregate load cannot wrap around the address space, so offsets to its
4120   // parts don't wrap either.
4121   SDNodeFlags Flags;
4122   Flags.setNoUnsignedWrap(true);
4123 
4124   SmallVector<SDValue, 4> Values(NumValues);
4125   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4126   EVT PtrVT = Ptr.getValueType();
4127 
4128   MachineMemOperand::Flags MMOFlags
4129     = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4130 
4131   unsigned ChainI = 0;
4132   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4133     // Serializing loads here may result in excessive register pressure, and
4134     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4135     // could recover a bit by hoisting nodes upward in the chain by recognizing
4136     // they are side-effect free or do not alias. The optimizer should really
4137     // avoid this case by converting large object/array copies to llvm.memcpy
4138     // (MaxParallelChains should always remain as failsafe).
4139     if (ChainI == MaxParallelChains) {
4140       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4141       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4142                                   makeArrayRef(Chains.data(), ChainI));
4143       Root = Chain;
4144       ChainI = 0;
4145     }
4146     SDValue A = DAG.getNode(ISD::ADD, dl,
4147                             PtrVT, Ptr,
4148                             DAG.getConstant(Offsets[i], dl, PtrVT),
4149                             Flags);
4150 
4151     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4152                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4153                             MMOFlags, AAInfo, Ranges);
4154     Chains[ChainI] = L.getValue(1);
4155 
4156     if (MemVTs[i] != ValueVTs[i])
4157       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4158 
4159     Values[i] = L;
4160   }
4161 
4162   if (!ConstantMemory) {
4163     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4164                                 makeArrayRef(Chains.data(), ChainI));
4165     if (isVolatile)
4166       DAG.setRoot(Chain);
4167     else
4168       PendingLoads.push_back(Chain);
4169   }
4170 
4171   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4172                            DAG.getVTList(ValueVTs), Values));
4173 }
4174 
4175 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4176   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4177          "call visitStoreToSwiftError when backend supports swifterror");
4178 
4179   SmallVector<EVT, 4> ValueVTs;
4180   SmallVector<uint64_t, 4> Offsets;
4181   const Value *SrcV = I.getOperand(0);
4182   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4183                   SrcV->getType(), ValueVTs, &Offsets);
4184   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4185          "expect a single EVT for swifterror");
4186 
4187   SDValue Src = getValue(SrcV);
4188   // Create a virtual register, then update the virtual register.
4189   Register VReg =
4190       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4191   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4192   // Chain can be getRoot or getControlRoot.
4193   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4194                                       SDValue(Src.getNode(), Src.getResNo()));
4195   DAG.setRoot(CopyNode);
4196 }
4197 
4198 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4199   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4200          "call visitLoadFromSwiftError when backend supports swifterror");
4201 
4202   assert(!I.isVolatile() &&
4203          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4204          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4205          "Support volatile, non temporal, invariant for load_from_swift_error");
4206 
4207   const Value *SV = I.getOperand(0);
4208   Type *Ty = I.getType();
4209   AAMDNodes AAInfo;
4210   I.getAAMetadata(AAInfo);
4211   assert(
4212       (!AA ||
4213        !AA->pointsToConstantMemory(MemoryLocation(
4214            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4215            AAInfo))) &&
4216       "load_from_swift_error should not be constant memory");
4217 
4218   SmallVector<EVT, 4> ValueVTs;
4219   SmallVector<uint64_t, 4> Offsets;
4220   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4221                   ValueVTs, &Offsets);
4222   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4223          "expect a single EVT for swifterror");
4224 
4225   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4226   SDValue L = DAG.getCopyFromReg(
4227       getRoot(), getCurSDLoc(),
4228       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4229 
4230   setValue(&I, L);
4231 }
4232 
4233 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4234   if (I.isAtomic())
4235     return visitAtomicStore(I);
4236 
4237   const Value *SrcV = I.getOperand(0);
4238   const Value *PtrV = I.getOperand(1);
4239 
4240   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4241   if (TLI.supportSwiftError()) {
4242     // Swifterror values can come from either a function parameter with
4243     // swifterror attribute or an alloca with swifterror attribute.
4244     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4245       if (Arg->hasSwiftErrorAttr())
4246         return visitStoreToSwiftError(I);
4247     }
4248 
4249     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4250       if (Alloca->isSwiftError())
4251         return visitStoreToSwiftError(I);
4252     }
4253   }
4254 
4255   SmallVector<EVT, 4> ValueVTs, MemVTs;
4256   SmallVector<uint64_t, 4> Offsets;
4257   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4258                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4259   unsigned NumValues = ValueVTs.size();
4260   if (NumValues == 0)
4261     return;
4262 
4263   // Get the lowered operands. Note that we do this after
4264   // checking if NumResults is zero, because with zero results
4265   // the operands won't have values in the map.
4266   SDValue Src = getValue(SrcV);
4267   SDValue Ptr = getValue(PtrV);
4268 
4269   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4270   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4271   SDLoc dl = getCurSDLoc();
4272   unsigned Alignment = I.getAlignment();
4273   AAMDNodes AAInfo;
4274   I.getAAMetadata(AAInfo);
4275 
4276   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4277 
4278   // An aggregate load cannot wrap around the address space, so offsets to its
4279   // parts don't wrap either.
4280   SDNodeFlags Flags;
4281   Flags.setNoUnsignedWrap(true);
4282 
4283   unsigned ChainI = 0;
4284   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4285     // See visitLoad comments.
4286     if (ChainI == MaxParallelChains) {
4287       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4288                                   makeArrayRef(Chains.data(), ChainI));
4289       Root = Chain;
4290       ChainI = 0;
4291     }
4292     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4293     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4294     if (MemVTs[i] != ValueVTs[i])
4295       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4296     SDValue St =
4297         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4298                      Alignment, MMOFlags, AAInfo);
4299     Chains[ChainI] = St;
4300   }
4301 
4302   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4303                                   makeArrayRef(Chains.data(), ChainI));
4304   DAG.setRoot(StoreNode);
4305 }
4306 
4307 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4308                                            bool IsCompressing) {
4309   SDLoc sdl = getCurSDLoc();
4310 
4311   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4312                            unsigned& Alignment) {
4313     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4314     Src0 = I.getArgOperand(0);
4315     Ptr = I.getArgOperand(1);
4316     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4317     Mask = I.getArgOperand(3);
4318   };
4319   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4320                            unsigned& Alignment) {
4321     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4322     Src0 = I.getArgOperand(0);
4323     Ptr = I.getArgOperand(1);
4324     Mask = I.getArgOperand(2);
4325     Alignment = 0;
4326   };
4327 
4328   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4329   unsigned Alignment;
4330   if (IsCompressing)
4331     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4332   else
4333     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4334 
4335   SDValue Ptr = getValue(PtrOperand);
4336   SDValue Src0 = getValue(Src0Operand);
4337   SDValue Mask = getValue(MaskOperand);
4338   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4339 
4340   EVT VT = Src0.getValueType();
4341   if (!Alignment)
4342     Alignment = DAG.getEVTAlignment(VT);
4343 
4344   AAMDNodes AAInfo;
4345   I.getAAMetadata(AAInfo);
4346 
4347   MachineMemOperand *MMO =
4348     DAG.getMachineFunction().
4349     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4350                           MachineMemOperand::MOStore,
4351                           // TODO: Make MachineMemOperands aware of scalable
4352                           // vectors.
4353                           VT.getStoreSize().getKnownMinSize(),
4354                           Alignment, AAInfo);
4355   SDValue StoreNode =
4356       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4357                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4358   DAG.setRoot(StoreNode);
4359   setValue(&I, StoreNode);
4360 }
4361 
4362 // Get a uniform base for the Gather/Scatter intrinsic.
4363 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4364 // We try to represent it as a base pointer + vector of indices.
4365 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4366 // The first operand of the GEP may be a single pointer or a vector of pointers
4367 // Example:
4368 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4369 //  or
4370 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4371 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4372 //
4373 // When the first GEP operand is a single pointer - it is the uniform base we
4374 // are looking for. If first operand of the GEP is a splat vector - we
4375 // extract the splat value and use it as a uniform base.
4376 // In all other cases the function returns 'false'.
4377 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4378                            ISD::MemIndexType &IndexType, SDValue &Scale,
4379                            SelectionDAGBuilder *SDB) {
4380   SelectionDAG& DAG = SDB->DAG;
4381   LLVMContext &Context = *DAG.getContext();
4382 
4383   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4384   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4385   if (!GEP)
4386     return false;
4387 
4388   const Value *GEPPtr = GEP->getPointerOperand();
4389   if (!GEPPtr->getType()->isVectorTy())
4390     Ptr = GEPPtr;
4391   else if (!(Ptr = getSplatValue(GEPPtr)))
4392     return false;
4393 
4394   unsigned FinalIndex = GEP->getNumOperands() - 1;
4395   Value *IndexVal = GEP->getOperand(FinalIndex);
4396   gep_type_iterator GTI = gep_type_begin(*GEP);
4397 
4398   // Ensure all the other indices are 0.
4399   for (unsigned i = 1; i < FinalIndex; ++i, ++GTI) {
4400     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4401     if (!C)
4402       return false;
4403     if (isa<VectorType>(C->getType()))
4404       C = C->getSplatValue();
4405     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4406     if (!CI || !CI->isZero())
4407       return false;
4408   }
4409 
4410   // The operands of the GEP may be defined in another basic block.
4411   // In this case we'll not find nodes for the operands.
4412   if (!SDB->findValue(Ptr))
4413     return false;
4414   Constant *C = dyn_cast<Constant>(IndexVal);
4415   if (!C && !SDB->findValue(IndexVal))
4416     return false;
4417 
4418   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4419   const DataLayout &DL = DAG.getDataLayout();
4420   StructType *STy = GTI.getStructTypeOrNull();
4421 
4422   if (STy) {
4423     const StructLayout *SL = DL.getStructLayout(STy);
4424     if (isa<VectorType>(C->getType())) {
4425       C = C->getSplatValue();
4426       // FIXME: If getSplatValue may return nullptr for a structure?
4427       // If not, the following check can be removed.
4428       if (!C)
4429         return false;
4430     }
4431     auto *CI = cast<ConstantInt>(C);
4432     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4433     Index = DAG.getConstant(SL->getElementOffset(CI->getZExtValue()),
4434                             SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4435   } else {
4436     Scale = DAG.getTargetConstant(
4437                 DL.getTypeAllocSize(GEP->getResultElementType()),
4438                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4439     Index = SDB->getValue(IndexVal);
4440   }
4441   Base = SDB->getValue(Ptr);
4442   IndexType = ISD::SIGNED_SCALED;
4443 
4444   if (STy || !Index.getValueType().isVector()) {
4445     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4446     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4447     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4448   }
4449   return true;
4450 }
4451 
4452 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4453   SDLoc sdl = getCurSDLoc();
4454 
4455   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4456   const Value *Ptr = I.getArgOperand(1);
4457   SDValue Src0 = getValue(I.getArgOperand(0));
4458   SDValue Mask = getValue(I.getArgOperand(3));
4459   EVT VT = Src0.getValueType();
4460   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4461   if (!Alignment)
4462     Alignment = DAG.getEVTAlignment(VT);
4463   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4464 
4465   AAMDNodes AAInfo;
4466   I.getAAMetadata(AAInfo);
4467 
4468   SDValue Base;
4469   SDValue Index;
4470   ISD::MemIndexType IndexType;
4471   SDValue Scale;
4472   const Value *BasePtr = Ptr;
4473   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4474                                     this);
4475 
4476   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4477   MachineMemOperand *MMO = DAG.getMachineFunction().
4478     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4479                          MachineMemOperand::MOStore,
4480                          // TODO: Make MachineMemOperands aware of scalable
4481                          // vectors.
4482                          VT.getStoreSize().getKnownMinSize(),
4483                          Alignment, AAInfo);
4484   if (!UniformBase) {
4485     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4486     Index = getValue(Ptr);
4487     IndexType = ISD::SIGNED_SCALED;
4488     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4489   }
4490   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4491   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4492                                          Ops, MMO, IndexType);
4493   DAG.setRoot(Scatter);
4494   setValue(&I, Scatter);
4495 }
4496 
4497 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4498   SDLoc sdl = getCurSDLoc();
4499 
4500   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4501                            unsigned& Alignment) {
4502     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4503     Ptr = I.getArgOperand(0);
4504     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4505     Mask = I.getArgOperand(2);
4506     Src0 = I.getArgOperand(3);
4507   };
4508   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4509                            unsigned& Alignment) {
4510     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4511     Ptr = I.getArgOperand(0);
4512     Alignment = 0;
4513     Mask = I.getArgOperand(1);
4514     Src0 = I.getArgOperand(2);
4515   };
4516 
4517   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4518   unsigned Alignment;
4519   if (IsExpanding)
4520     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4521   else
4522     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4523 
4524   SDValue Ptr = getValue(PtrOperand);
4525   SDValue Src0 = getValue(Src0Operand);
4526   SDValue Mask = getValue(MaskOperand);
4527   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4528 
4529   EVT VT = Src0.getValueType();
4530   if (!Alignment)
4531     Alignment = DAG.getEVTAlignment(VT);
4532 
4533   AAMDNodes AAInfo;
4534   I.getAAMetadata(AAInfo);
4535   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4536 
4537   // Do not serialize masked loads of constant memory with anything.
4538   MemoryLocation ML;
4539   if (VT.isScalableVector())
4540     ML = MemoryLocation(PtrOperand);
4541   else
4542     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4543                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4544                            AAInfo);
4545   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4546 
4547   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4548 
4549   MachineMemOperand *MMO =
4550     DAG.getMachineFunction().
4551     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4552                           MachineMemOperand::MOLoad,
4553                           // TODO: Make MachineMemOperands aware of scalable
4554                           // vectors.
4555                           VT.getStoreSize().getKnownMinSize(),
4556                           Alignment, AAInfo, Ranges);
4557 
4558   SDValue Load =
4559       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4560                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4561   if (AddToChain)
4562     PendingLoads.push_back(Load.getValue(1));
4563   setValue(&I, Load);
4564 }
4565 
4566 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4567   SDLoc sdl = getCurSDLoc();
4568 
4569   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4570   const Value *Ptr = I.getArgOperand(0);
4571   SDValue Src0 = getValue(I.getArgOperand(3));
4572   SDValue Mask = getValue(I.getArgOperand(2));
4573 
4574   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4575   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4576   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4577   if (!Alignment)
4578     Alignment = DAG.getEVTAlignment(VT);
4579 
4580   AAMDNodes AAInfo;
4581   I.getAAMetadata(AAInfo);
4582   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4583 
4584   SDValue Root = DAG.getRoot();
4585   SDValue Base;
4586   SDValue Index;
4587   ISD::MemIndexType IndexType;
4588   SDValue Scale;
4589   const Value *BasePtr = Ptr;
4590   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4591                                     this);
4592   bool ConstantMemory = false;
4593   if (UniformBase && AA &&
4594       AA->pointsToConstantMemory(
4595           MemoryLocation(BasePtr,
4596                          LocationSize::precise(
4597                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4598                          AAInfo))) {
4599     // Do not serialize (non-volatile) loads of constant memory with anything.
4600     Root = DAG.getEntryNode();
4601     ConstantMemory = true;
4602   }
4603 
4604   MachineMemOperand *MMO =
4605     DAG.getMachineFunction().
4606     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4607                          MachineMemOperand::MOLoad,
4608                          // TODO: Make MachineMemOperands aware of scalable
4609                          // vectors.
4610                          VT.getStoreSize().getKnownMinSize(),
4611                          Alignment, AAInfo, Ranges);
4612 
4613   if (!UniformBase) {
4614     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4615     Index = getValue(Ptr);
4616     IndexType = ISD::SIGNED_SCALED;
4617     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4618   }
4619   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4620   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4621                                        Ops, MMO, IndexType);
4622 
4623   SDValue OutChain = Gather.getValue(1);
4624   if (!ConstantMemory)
4625     PendingLoads.push_back(OutChain);
4626   setValue(&I, Gather);
4627 }
4628 
4629 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4630   SDLoc dl = getCurSDLoc();
4631   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4632   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4633   SyncScope::ID SSID = I.getSyncScopeID();
4634 
4635   SDValue InChain = getRoot();
4636 
4637   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4638   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4639 
4640   auto Alignment = DAG.getEVTAlignment(MemVT);
4641   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4642   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4643 
4644   MachineFunction &MF = DAG.getMachineFunction();
4645   MachineMemOperand *MMO =
4646     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4647                             Flags, MemVT.getStoreSize(), Alignment,
4648                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4649                             FailureOrdering);
4650 
4651   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4652                                    dl, MemVT, VTs, InChain,
4653                                    getValue(I.getPointerOperand()),
4654                                    getValue(I.getCompareOperand()),
4655                                    getValue(I.getNewValOperand()), MMO);
4656 
4657   SDValue OutChain = L.getValue(2);
4658 
4659   setValue(&I, L);
4660   DAG.setRoot(OutChain);
4661 }
4662 
4663 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4664   SDLoc dl = getCurSDLoc();
4665   ISD::NodeType NT;
4666   switch (I.getOperation()) {
4667   default: llvm_unreachable("Unknown atomicrmw operation");
4668   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4669   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4670   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4671   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4672   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4673   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4674   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4675   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4676   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4677   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4678   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4679   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4680   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4681   }
4682   AtomicOrdering Ordering = I.getOrdering();
4683   SyncScope::ID SSID = I.getSyncScopeID();
4684 
4685   SDValue InChain = getRoot();
4686 
4687   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4688   auto Alignment = DAG.getEVTAlignment(MemVT);
4689   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4690   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
4691 
4692   MachineFunction &MF = DAG.getMachineFunction();
4693   MachineMemOperand *MMO =
4694     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4695                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4696                             nullptr, SSID, Ordering);
4697 
4698   SDValue L =
4699     DAG.getAtomic(NT, dl, MemVT, InChain,
4700                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4701                   MMO);
4702 
4703   SDValue OutChain = L.getValue(1);
4704 
4705   setValue(&I, L);
4706   DAG.setRoot(OutChain);
4707 }
4708 
4709 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4710   SDLoc dl = getCurSDLoc();
4711   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4712   SDValue Ops[3];
4713   Ops[0] = getRoot();
4714   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
4715                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4716   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
4717                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
4718   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4719 }
4720 
4721 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4722   SDLoc dl = getCurSDLoc();
4723   AtomicOrdering Order = I.getOrdering();
4724   SyncScope::ID SSID = I.getSyncScopeID();
4725 
4726   SDValue InChain = getRoot();
4727 
4728   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4729   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4730   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4731 
4732   if (!TLI.supportsUnalignedAtomics() &&
4733       I.getAlignment() < MemVT.getSizeInBits() / 8)
4734     report_fatal_error("Cannot generate unaligned atomic load");
4735 
4736   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout());
4737 
4738   MachineMemOperand *MMO =
4739       DAG.getMachineFunction().
4740       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4741                            Flags, MemVT.getStoreSize(),
4742                            I.getAlignment() ? I.getAlignment() :
4743                                               DAG.getEVTAlignment(MemVT),
4744                            AAMDNodes(), nullptr, SSID, Order);
4745 
4746   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4747 
4748   SDValue Ptr = getValue(I.getPointerOperand());
4749 
4750   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4751     // TODO: Once this is better exercised by tests, it should be merged with
4752     // the normal path for loads to prevent future divergence.
4753     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4754     if (MemVT != VT)
4755       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4756 
4757     setValue(&I, L);
4758     SDValue OutChain = L.getValue(1);
4759     if (!I.isUnordered())
4760       DAG.setRoot(OutChain);
4761     else
4762       PendingLoads.push_back(OutChain);
4763     return;
4764   }
4765 
4766   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4767                             Ptr, MMO);
4768 
4769   SDValue OutChain = L.getValue(1);
4770   if (MemVT != VT)
4771     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4772 
4773   setValue(&I, L);
4774   DAG.setRoot(OutChain);
4775 }
4776 
4777 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4778   SDLoc dl = getCurSDLoc();
4779 
4780   AtomicOrdering Ordering = I.getOrdering();
4781   SyncScope::ID SSID = I.getSyncScopeID();
4782 
4783   SDValue InChain = getRoot();
4784 
4785   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4786   EVT MemVT =
4787       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4788 
4789   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4790     report_fatal_error("Cannot generate unaligned atomic store");
4791 
4792   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4793 
4794   MachineFunction &MF = DAG.getMachineFunction();
4795   MachineMemOperand *MMO =
4796     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4797                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4798                             nullptr, SSID, Ordering);
4799 
4800   SDValue Val = getValue(I.getValueOperand());
4801   if (Val.getValueType() != MemVT)
4802     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4803   SDValue Ptr = getValue(I.getPointerOperand());
4804 
4805   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4806     // TODO: Once this is better exercised by tests, it should be merged with
4807     // the normal path for stores to prevent future divergence.
4808     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4809     DAG.setRoot(S);
4810     return;
4811   }
4812   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4813                                    Ptr, Val, MMO);
4814 
4815 
4816   DAG.setRoot(OutChain);
4817 }
4818 
4819 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4820 /// node.
4821 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4822                                                unsigned Intrinsic) {
4823   // Ignore the callsite's attributes. A specific call site may be marked with
4824   // readnone, but the lowering code will expect the chain based on the
4825   // definition.
4826   const Function *F = I.getCalledFunction();
4827   bool HasChain = !F->doesNotAccessMemory();
4828   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4829 
4830   // Build the operand list.
4831   SmallVector<SDValue, 8> Ops;
4832   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4833     if (OnlyLoad) {
4834       // We don't need to serialize loads against other loads.
4835       Ops.push_back(DAG.getRoot());
4836     } else {
4837       Ops.push_back(getRoot());
4838     }
4839   }
4840 
4841   // Info is set by getTgtMemInstrinsic
4842   TargetLowering::IntrinsicInfo Info;
4843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4844   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4845                                                DAG.getMachineFunction(),
4846                                                Intrinsic);
4847 
4848   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4849   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4850       Info.opc == ISD::INTRINSIC_W_CHAIN)
4851     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4852                                         TLI.getPointerTy(DAG.getDataLayout())));
4853 
4854   // Add all operands of the call to the operand list.
4855   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4856     const Value *Arg = I.getArgOperand(i);
4857     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4858       Ops.push_back(getValue(Arg));
4859       continue;
4860     }
4861 
4862     // Use TargetConstant instead of a regular constant for immarg.
4863     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4864     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4865       assert(CI->getBitWidth() <= 64 &&
4866              "large intrinsic immediates not handled");
4867       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4868     } else {
4869       Ops.push_back(
4870           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4871     }
4872   }
4873 
4874   SmallVector<EVT, 4> ValueVTs;
4875   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4876 
4877   if (HasChain)
4878     ValueVTs.push_back(MVT::Other);
4879 
4880   SDVTList VTs = DAG.getVTList(ValueVTs);
4881 
4882   // Create the node.
4883   SDValue Result;
4884   if (IsTgtIntrinsic) {
4885     // This is target intrinsic that touches memory
4886     AAMDNodes AAInfo;
4887     I.getAAMetadata(AAInfo);
4888     Result = DAG.getMemIntrinsicNode(
4889         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4890         MachinePointerInfo(Info.ptrVal, Info.offset),
4891         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4892   } else if (!HasChain) {
4893     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4894   } else if (!I.getType()->isVoidTy()) {
4895     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4896   } else {
4897     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4898   }
4899 
4900   if (HasChain) {
4901     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4902     if (OnlyLoad)
4903       PendingLoads.push_back(Chain);
4904     else
4905       DAG.setRoot(Chain);
4906   }
4907 
4908   if (!I.getType()->isVoidTy()) {
4909     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4910       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4911       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4912     } else
4913       Result = lowerRangeToAssertZExt(DAG, I, Result);
4914 
4915     setValue(&I, Result);
4916   }
4917 }
4918 
4919 /// GetSignificand - Get the significand and build it into a floating-point
4920 /// number with exponent of 1:
4921 ///
4922 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4923 ///
4924 /// where Op is the hexadecimal representation of floating point value.
4925 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4926   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4927                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4928   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4929                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4930   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4931 }
4932 
4933 /// GetExponent - Get the exponent:
4934 ///
4935 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4936 ///
4937 /// where Op is the hexadecimal representation of floating point value.
4938 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4939                            const TargetLowering &TLI, const SDLoc &dl) {
4940   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4941                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4942   SDValue t1 = DAG.getNode(
4943       ISD::SRL, dl, MVT::i32, t0,
4944       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4945   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4946                            DAG.getConstant(127, dl, MVT::i32));
4947   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4948 }
4949 
4950 /// getF32Constant - Get 32-bit floating point constant.
4951 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4952                               const SDLoc &dl) {
4953   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4954                            MVT::f32);
4955 }
4956 
4957 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4958                                        SelectionDAG &DAG) {
4959   // TODO: What fast-math-flags should be set on the floating-point nodes?
4960 
4961   //   IntegerPartOfX = ((int32_t)(t0);
4962   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4963 
4964   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4965   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4966   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4967 
4968   //   IntegerPartOfX <<= 23;
4969   IntegerPartOfX = DAG.getNode(
4970       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4971       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4972                                   DAG.getDataLayout())));
4973 
4974   SDValue TwoToFractionalPartOfX;
4975   if (LimitFloatPrecision <= 6) {
4976     // For floating-point precision of 6:
4977     //
4978     //   TwoToFractionalPartOfX =
4979     //     0.997535578f +
4980     //       (0.735607626f + 0.252464424f * x) * x;
4981     //
4982     // error 0.0144103317, which is 6 bits
4983     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4984                              getF32Constant(DAG, 0x3e814304, dl));
4985     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4986                              getF32Constant(DAG, 0x3f3c50c8, dl));
4987     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4988     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4989                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4990   } else if (LimitFloatPrecision <= 12) {
4991     // For floating-point precision of 12:
4992     //
4993     //   TwoToFractionalPartOfX =
4994     //     0.999892986f +
4995     //       (0.696457318f +
4996     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4997     //
4998     // error 0.000107046256, which is 13 to 14 bits
4999     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5000                              getF32Constant(DAG, 0x3da235e3, dl));
5001     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5002                              getF32Constant(DAG, 0x3e65b8f3, dl));
5003     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5004     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5005                              getF32Constant(DAG, 0x3f324b07, dl));
5006     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5007     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5008                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5009   } else { // LimitFloatPrecision <= 18
5010     // For floating-point precision of 18:
5011     //
5012     //   TwoToFractionalPartOfX =
5013     //     0.999999982f +
5014     //       (0.693148872f +
5015     //         (0.240227044f +
5016     //           (0.554906021e-1f +
5017     //             (0.961591928e-2f +
5018     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5019     // error 2.47208000*10^(-7), which is better than 18 bits
5020     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5021                              getF32Constant(DAG, 0x3924b03e, dl));
5022     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5023                              getF32Constant(DAG, 0x3ab24b87, dl));
5024     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5025     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5026                              getF32Constant(DAG, 0x3c1d8c17, dl));
5027     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5028     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5029                              getF32Constant(DAG, 0x3d634a1d, dl));
5030     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5031     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5032                              getF32Constant(DAG, 0x3e75fe14, dl));
5033     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5034     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5035                               getF32Constant(DAG, 0x3f317234, dl));
5036     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5037     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5038                                          getF32Constant(DAG, 0x3f800000, dl));
5039   }
5040 
5041   // Add the exponent into the result in integer domain.
5042   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5043   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5044                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5045 }
5046 
5047 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5048 /// limited-precision mode.
5049 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5050                          const TargetLowering &TLI) {
5051   if (Op.getValueType() == MVT::f32 &&
5052       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5053 
5054     // Put the exponent in the right bit position for later addition to the
5055     // final result:
5056     //
5057     // t0 = Op * log2(e)
5058 
5059     // TODO: What fast-math-flags should be set here?
5060     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5061                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5062     return getLimitedPrecisionExp2(t0, dl, DAG);
5063   }
5064 
5065   // No special expansion.
5066   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5067 }
5068 
5069 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5070 /// limited-precision mode.
5071 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5072                          const TargetLowering &TLI) {
5073   // TODO: What fast-math-flags should be set on the floating-point nodes?
5074 
5075   if (Op.getValueType() == MVT::f32 &&
5076       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5077     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5078 
5079     // Scale the exponent by log(2).
5080     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5081     SDValue LogOfExponent =
5082         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5083                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5084 
5085     // Get the significand and build it into a floating-point number with
5086     // exponent of 1.
5087     SDValue X = GetSignificand(DAG, Op1, dl);
5088 
5089     SDValue LogOfMantissa;
5090     if (LimitFloatPrecision <= 6) {
5091       // For floating-point precision of 6:
5092       //
5093       //   LogofMantissa =
5094       //     -1.1609546f +
5095       //       (1.4034025f - 0.23903021f * x) * x;
5096       //
5097       // error 0.0034276066, which is better than 8 bits
5098       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5099                                getF32Constant(DAG, 0xbe74c456, dl));
5100       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5101                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5102       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5103       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5104                                   getF32Constant(DAG, 0x3f949a29, dl));
5105     } else if (LimitFloatPrecision <= 12) {
5106       // For floating-point precision of 12:
5107       //
5108       //   LogOfMantissa =
5109       //     -1.7417939f +
5110       //       (2.8212026f +
5111       //         (-1.4699568f +
5112       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5113       //
5114       // error 0.000061011436, which is 14 bits
5115       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5116                                getF32Constant(DAG, 0xbd67b6d6, dl));
5117       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5118                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5119       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5120       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5121                                getF32Constant(DAG, 0x3fbc278b, dl));
5122       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5123       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5124                                getF32Constant(DAG, 0x40348e95, dl));
5125       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5126       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5127                                   getF32Constant(DAG, 0x3fdef31a, dl));
5128     } else { // LimitFloatPrecision <= 18
5129       // For floating-point precision of 18:
5130       //
5131       //   LogOfMantissa =
5132       //     -2.1072184f +
5133       //       (4.2372794f +
5134       //         (-3.7029485f +
5135       //           (2.2781945f +
5136       //             (-0.87823314f +
5137       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5138       //
5139       // error 0.0000023660568, which is better than 18 bits
5140       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5141                                getF32Constant(DAG, 0xbc91e5ac, dl));
5142       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5143                                getF32Constant(DAG, 0x3e4350aa, dl));
5144       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5145       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5146                                getF32Constant(DAG, 0x3f60d3e3, dl));
5147       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5148       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5149                                getF32Constant(DAG, 0x4011cdf0, dl));
5150       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5151       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5152                                getF32Constant(DAG, 0x406cfd1c, dl));
5153       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5154       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5155                                getF32Constant(DAG, 0x408797cb, dl));
5156       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5157       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5158                                   getF32Constant(DAG, 0x4006dcab, dl));
5159     }
5160 
5161     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5162   }
5163 
5164   // No special expansion.
5165   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5166 }
5167 
5168 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5169 /// limited-precision mode.
5170 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5171                           const TargetLowering &TLI) {
5172   // TODO: What fast-math-flags should be set on the floating-point nodes?
5173 
5174   if (Op.getValueType() == MVT::f32 &&
5175       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5176     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5177 
5178     // Get the exponent.
5179     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5180 
5181     // Get the significand and build it into a floating-point number with
5182     // exponent of 1.
5183     SDValue X = GetSignificand(DAG, Op1, dl);
5184 
5185     // Different possible minimax approximations of significand in
5186     // floating-point for various degrees of accuracy over [1,2].
5187     SDValue Log2ofMantissa;
5188     if (LimitFloatPrecision <= 6) {
5189       // For floating-point precision of 6:
5190       //
5191       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5192       //
5193       // error 0.0049451742, which is more than 7 bits
5194       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5195                                getF32Constant(DAG, 0xbeb08fe0, dl));
5196       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5197                                getF32Constant(DAG, 0x40019463, dl));
5198       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5199       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5200                                    getF32Constant(DAG, 0x3fd6633d, dl));
5201     } else if (LimitFloatPrecision <= 12) {
5202       // For floating-point precision of 12:
5203       //
5204       //   Log2ofMantissa =
5205       //     -2.51285454f +
5206       //       (4.07009056f +
5207       //         (-2.12067489f +
5208       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5209       //
5210       // error 0.0000876136000, which is better than 13 bits
5211       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5212                                getF32Constant(DAG, 0xbda7262e, dl));
5213       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5214                                getF32Constant(DAG, 0x3f25280b, dl));
5215       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5216       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5217                                getF32Constant(DAG, 0x4007b923, dl));
5218       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5219       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5220                                getF32Constant(DAG, 0x40823e2f, dl));
5221       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5222       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5223                                    getF32Constant(DAG, 0x4020d29c, dl));
5224     } else { // LimitFloatPrecision <= 18
5225       // For floating-point precision of 18:
5226       //
5227       //   Log2ofMantissa =
5228       //     -3.0400495f +
5229       //       (6.1129976f +
5230       //         (-5.3420409f +
5231       //           (3.2865683f +
5232       //             (-1.2669343f +
5233       //               (0.27515199f -
5234       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5235       //
5236       // error 0.0000018516, which is better than 18 bits
5237       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5238                                getF32Constant(DAG, 0xbcd2769e, dl));
5239       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5240                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5241       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5242       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5243                                getF32Constant(DAG, 0x3fa22ae7, dl));
5244       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5245       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5246                                getF32Constant(DAG, 0x40525723, dl));
5247       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5248       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5249                                getF32Constant(DAG, 0x40aaf200, dl));
5250       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5251       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5252                                getF32Constant(DAG, 0x40c39dad, dl));
5253       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5254       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5255                                    getF32Constant(DAG, 0x4042902c, dl));
5256     }
5257 
5258     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5259   }
5260 
5261   // No special expansion.
5262   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5263 }
5264 
5265 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5266 /// limited-precision mode.
5267 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5268                            const TargetLowering &TLI) {
5269   // TODO: What fast-math-flags should be set on the floating-point nodes?
5270 
5271   if (Op.getValueType() == MVT::f32 &&
5272       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5273     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5274 
5275     // Scale the exponent by log10(2) [0.30102999f].
5276     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5277     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5278                                         getF32Constant(DAG, 0x3e9a209a, dl));
5279 
5280     // Get the significand and build it into a floating-point number with
5281     // exponent of 1.
5282     SDValue X = GetSignificand(DAG, Op1, dl);
5283 
5284     SDValue Log10ofMantissa;
5285     if (LimitFloatPrecision <= 6) {
5286       // For floating-point precision of 6:
5287       //
5288       //   Log10ofMantissa =
5289       //     -0.50419619f +
5290       //       (0.60948995f - 0.10380950f * x) * x;
5291       //
5292       // error 0.0014886165, which is 6 bits
5293       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5294                                getF32Constant(DAG, 0xbdd49a13, dl));
5295       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5296                                getF32Constant(DAG, 0x3f1c0789, dl));
5297       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5298       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5299                                     getF32Constant(DAG, 0x3f011300, dl));
5300     } else if (LimitFloatPrecision <= 12) {
5301       // For floating-point precision of 12:
5302       //
5303       //   Log10ofMantissa =
5304       //     -0.64831180f +
5305       //       (0.91751397f +
5306       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5307       //
5308       // error 0.00019228036, which is better than 12 bits
5309       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5310                                getF32Constant(DAG, 0x3d431f31, dl));
5311       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5312                                getF32Constant(DAG, 0x3ea21fb2, dl));
5313       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5314       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5315                                getF32Constant(DAG, 0x3f6ae232, dl));
5316       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5317       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5318                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5319     } else { // LimitFloatPrecision <= 18
5320       // For floating-point precision of 18:
5321       //
5322       //   Log10ofMantissa =
5323       //     -0.84299375f +
5324       //       (1.5327582f +
5325       //         (-1.0688956f +
5326       //           (0.49102474f +
5327       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5328       //
5329       // error 0.0000037995730, which is better than 18 bits
5330       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5331                                getF32Constant(DAG, 0x3c5d51ce, dl));
5332       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5333                                getF32Constant(DAG, 0x3e00685a, dl));
5334       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5335       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5336                                getF32Constant(DAG, 0x3efb6798, dl));
5337       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5338       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5339                                getF32Constant(DAG, 0x3f88d192, dl));
5340       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5341       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5342                                getF32Constant(DAG, 0x3fc4316c, dl));
5343       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5344       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5345                                     getF32Constant(DAG, 0x3f57ce70, dl));
5346     }
5347 
5348     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5349   }
5350 
5351   // No special expansion.
5352   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5353 }
5354 
5355 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5356 /// limited-precision mode.
5357 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5358                           const TargetLowering &TLI) {
5359   if (Op.getValueType() == MVT::f32 &&
5360       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5361     return getLimitedPrecisionExp2(Op, dl, DAG);
5362 
5363   // No special expansion.
5364   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5365 }
5366 
5367 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5368 /// limited-precision mode with x == 10.0f.
5369 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5370                          SelectionDAG &DAG, const TargetLowering &TLI) {
5371   bool IsExp10 = false;
5372   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5373       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5374     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5375       APFloat Ten(10.0f);
5376       IsExp10 = LHSC->isExactlyValue(Ten);
5377     }
5378   }
5379 
5380   // TODO: What fast-math-flags should be set on the FMUL node?
5381   if (IsExp10) {
5382     // Put the exponent in the right bit position for later addition to the
5383     // final result:
5384     //
5385     //   #define LOG2OF10 3.3219281f
5386     //   t0 = Op * LOG2OF10;
5387     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5388                              getF32Constant(DAG, 0x40549a78, dl));
5389     return getLimitedPrecisionExp2(t0, dl, DAG);
5390   }
5391 
5392   // No special expansion.
5393   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5394 }
5395 
5396 /// ExpandPowI - Expand a llvm.powi intrinsic.
5397 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5398                           SelectionDAG &DAG) {
5399   // If RHS is a constant, we can expand this out to a multiplication tree,
5400   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5401   // optimizing for size, we only want to do this if the expansion would produce
5402   // a small number of multiplies, otherwise we do the full expansion.
5403   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5404     // Get the exponent as a positive value.
5405     unsigned Val = RHSC->getSExtValue();
5406     if ((int)Val < 0) Val = -Val;
5407 
5408     // powi(x, 0) -> 1.0
5409     if (Val == 0)
5410       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5411 
5412     bool OptForSize = DAG.shouldOptForSize();
5413     if (!OptForSize ||
5414         // If optimizing for size, don't insert too many multiplies.
5415         // This inserts up to 5 multiplies.
5416         countPopulation(Val) + Log2_32(Val) < 7) {
5417       // We use the simple binary decomposition method to generate the multiply
5418       // sequence.  There are more optimal ways to do this (for example,
5419       // powi(x,15) generates one more multiply than it should), but this has
5420       // the benefit of being both really simple and much better than a libcall.
5421       SDValue Res;  // Logically starts equal to 1.0
5422       SDValue CurSquare = LHS;
5423       // TODO: Intrinsics should have fast-math-flags that propagate to these
5424       // nodes.
5425       while (Val) {
5426         if (Val & 1) {
5427           if (Res.getNode())
5428             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5429           else
5430             Res = CurSquare;  // 1.0*CurSquare.
5431         }
5432 
5433         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5434                                 CurSquare, CurSquare);
5435         Val >>= 1;
5436       }
5437 
5438       // If the original was negative, invert the result, producing 1/(x*x*x).
5439       if (RHSC->getSExtValue() < 0)
5440         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5441                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5442       return Res;
5443     }
5444   }
5445 
5446   // Otherwise, expand to a libcall.
5447   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5448 }
5449 
5450 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5451                             SDValue LHS, SDValue RHS, SDValue Scale,
5452                             SelectionDAG &DAG, const TargetLowering &TLI) {
5453   EVT VT = LHS.getValueType();
5454   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5455   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5456   LLVMContext &Ctx = *DAG.getContext();
5457 
5458   // If the type is legal but the operation isn't, this node might survive all
5459   // the way to operation legalization. If we end up there and we do not have
5460   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5461   // node.
5462 
5463   // Coax the legalizer into expanding the node during type legalization instead
5464   // by bumping the size by one bit. This will force it to Promote, enabling the
5465   // early expansion and avoiding the need to expand later.
5466 
5467   // We don't have to do this if Scale is 0; that can always be expanded, unless
5468   // it's a saturating signed operation. Those can experience true integer
5469   // division overflow, a case which we must avoid.
5470 
5471   // FIXME: We wouldn't have to do this (or any of the early
5472   // expansion/promotion) if it was possible to expand a libcall of an
5473   // illegal type during operation legalization. But it's not, so things
5474   // get a bit hacky.
5475   unsigned ScaleInt = cast<ConstantSDNode>(Scale)->getZExtValue();
5476   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5477       (TLI.isTypeLegal(VT) ||
5478        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5479     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5480         Opcode, VT, ScaleInt);
5481     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5482       EVT PromVT;
5483       if (VT.isScalarInteger())
5484         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5485       else if (VT.isVector()) {
5486         PromVT = VT.getVectorElementType();
5487         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5488         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5489       } else
5490         llvm_unreachable("Wrong VT for DIVFIX?");
5491       if (Signed) {
5492         LHS = DAG.getSExtOrTrunc(LHS, DL, PromVT);
5493         RHS = DAG.getSExtOrTrunc(RHS, DL, PromVT);
5494       } else {
5495         LHS = DAG.getZExtOrTrunc(LHS, DL, PromVT);
5496         RHS = DAG.getZExtOrTrunc(RHS, DL, PromVT);
5497       }
5498       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5499       // For saturating operations, we need to shift up the LHS to get the
5500       // proper saturation width, and then shift down again afterwards.
5501       if (Saturating)
5502         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5503                           DAG.getConstant(1, DL, ShiftTy));
5504       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5505       if (Saturating)
5506         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5507                           DAG.getConstant(1, DL, ShiftTy));
5508       return DAG.getZExtOrTrunc(Res, DL, VT);
5509     }
5510   }
5511 
5512   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5513 }
5514 
5515 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5516 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5517 static void
5518 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5519                      const SDValue &N) {
5520   switch (N.getOpcode()) {
5521   case ISD::CopyFromReg: {
5522     SDValue Op = N.getOperand(1);
5523     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5524                       Op.getValueType().getSizeInBits());
5525     return;
5526   }
5527   case ISD::BITCAST:
5528   case ISD::AssertZext:
5529   case ISD::AssertSext:
5530   case ISD::TRUNCATE:
5531     getUnderlyingArgRegs(Regs, N.getOperand(0));
5532     return;
5533   case ISD::BUILD_PAIR:
5534   case ISD::BUILD_VECTOR:
5535   case ISD::CONCAT_VECTORS:
5536     for (SDValue Op : N->op_values())
5537       getUnderlyingArgRegs(Regs, Op);
5538     return;
5539   default:
5540     return;
5541   }
5542 }
5543 
5544 /// If the DbgValueInst is a dbg_value of a function argument, create the
5545 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5546 /// instruction selection, they will be inserted to the entry BB.
5547 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5548     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5549     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5550   const Argument *Arg = dyn_cast<Argument>(V);
5551   if (!Arg)
5552     return false;
5553 
5554   if (!IsDbgDeclare) {
5555     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5556     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5557     // the entry block.
5558     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5559     if (!IsInEntryBlock)
5560       return false;
5561 
5562     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5563     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5564     // variable that also is a param.
5565     //
5566     // Although, if we are at the top of the entry block already, we can still
5567     // emit using ArgDbgValue. This might catch some situations when the
5568     // dbg.value refers to an argument that isn't used in the entry block, so
5569     // any CopyToReg node would be optimized out and the only way to express
5570     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5571     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5572     // we should only emit as ArgDbgValue if the Variable is an argument to the
5573     // current function, and the dbg.value intrinsic is found in the entry
5574     // block.
5575     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5576         !DL->getInlinedAt();
5577     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5578     if (!IsInPrologue && !VariableIsFunctionInputArg)
5579       return false;
5580 
5581     // Here we assume that a function argument on IR level only can be used to
5582     // describe one input parameter on source level. If we for example have
5583     // source code like this
5584     //
5585     //    struct A { long x, y; };
5586     //    void foo(struct A a, long b) {
5587     //      ...
5588     //      b = a.x;
5589     //      ...
5590     //    }
5591     //
5592     // and IR like this
5593     //
5594     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5595     //  entry:
5596     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5597     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5598     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5599     //    ...
5600     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5601     //    ...
5602     //
5603     // then the last dbg.value is describing a parameter "b" using a value that
5604     // is an argument. But since we already has used %a1 to describe a parameter
5605     // we should not handle that last dbg.value here (that would result in an
5606     // incorrect hoisting of the DBG_VALUE to the function entry).
5607     // Notice that we allow one dbg.value per IR level argument, to accommodate
5608     // for the situation with fragments above.
5609     if (VariableIsFunctionInputArg) {
5610       unsigned ArgNo = Arg->getArgNo();
5611       if (ArgNo >= FuncInfo.DescribedArgs.size())
5612         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5613       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5614         return false;
5615       FuncInfo.DescribedArgs.set(ArgNo);
5616     }
5617   }
5618 
5619   MachineFunction &MF = DAG.getMachineFunction();
5620   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5621 
5622   bool IsIndirect = false;
5623   Optional<MachineOperand> Op;
5624   // Some arguments' frame index is recorded during argument lowering.
5625   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5626   if (FI != std::numeric_limits<int>::max())
5627     Op = MachineOperand::CreateFI(FI);
5628 
5629   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5630   if (!Op && N.getNode()) {
5631     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5632     Register Reg;
5633     if (ArgRegsAndSizes.size() == 1)
5634       Reg = ArgRegsAndSizes.front().first;
5635 
5636     if (Reg && Reg.isVirtual()) {
5637       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5638       Register PR = RegInfo.getLiveInPhysReg(Reg);
5639       if (PR)
5640         Reg = PR;
5641     }
5642     if (Reg) {
5643       Op = MachineOperand::CreateReg(Reg, false);
5644       IsIndirect = IsDbgDeclare;
5645     }
5646   }
5647 
5648   if (!Op && N.getNode()) {
5649     // Check if frame index is available.
5650     SDValue LCandidate = peekThroughBitcasts(N);
5651     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5652       if (FrameIndexSDNode *FINode =
5653           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5654         Op = MachineOperand::CreateFI(FINode->getIndex());
5655   }
5656 
5657   if (!Op) {
5658     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5659     auto splitMultiRegDbgValue
5660       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5661       unsigned Offset = 0;
5662       for (auto RegAndSize : SplitRegs) {
5663         // If the expression is already a fragment, the current register
5664         // offset+size might extend beyond the fragment. In this case, only
5665         // the register bits that are inside the fragment are relevant.
5666         int RegFragmentSizeInBits = RegAndSize.second;
5667         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
5668           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
5669           // The register is entirely outside the expression fragment,
5670           // so is irrelevant for debug info.
5671           if (Offset >= ExprFragmentSizeInBits)
5672             break;
5673           // The register is partially outside the expression fragment, only
5674           // the low bits within the fragment are relevant for debug info.
5675           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
5676             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
5677           }
5678         }
5679 
5680         auto FragmentExpr = DIExpression::createFragmentExpression(
5681             Expr, Offset, RegFragmentSizeInBits);
5682         Offset += RegAndSize.second;
5683         // If a valid fragment expression cannot be created, the variable's
5684         // correct value cannot be determined and so it is set as Undef.
5685         if (!FragmentExpr) {
5686           SDDbgValue *SDV = DAG.getConstantDbgValue(
5687               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5688           DAG.AddDbgValue(SDV, nullptr, false);
5689           continue;
5690         }
5691         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5692         FuncInfo.ArgDbgValues.push_back(
5693           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5694                   RegAndSize.first, Variable, *FragmentExpr));
5695       }
5696     };
5697 
5698     // Check if ValueMap has reg number.
5699     DenseMap<const Value *, unsigned>::const_iterator
5700       VMI = FuncInfo.ValueMap.find(V);
5701     if (VMI != FuncInfo.ValueMap.end()) {
5702       const auto &TLI = DAG.getTargetLoweringInfo();
5703       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5704                        V->getType(), getABIRegCopyCC(V));
5705       if (RFV.occupiesMultipleRegs()) {
5706         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5707         return true;
5708       }
5709 
5710       Op = MachineOperand::CreateReg(VMI->second, false);
5711       IsIndirect = IsDbgDeclare;
5712     } else if (ArgRegsAndSizes.size() > 1) {
5713       // This was split due to the calling convention, and no virtual register
5714       // mapping exists for the value.
5715       splitMultiRegDbgValue(ArgRegsAndSizes);
5716       return true;
5717     }
5718   }
5719 
5720   if (!Op)
5721     return false;
5722 
5723   assert(Variable->isValidLocationForIntrinsic(DL) &&
5724          "Expected inlined-at fields to agree");
5725   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5726   FuncInfo.ArgDbgValues.push_back(
5727       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5728               *Op, Variable, Expr));
5729 
5730   return true;
5731 }
5732 
5733 /// Return the appropriate SDDbgValue based on N.
5734 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5735                                              DILocalVariable *Variable,
5736                                              DIExpression *Expr,
5737                                              const DebugLoc &dl,
5738                                              unsigned DbgSDNodeOrder) {
5739   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5740     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5741     // stack slot locations.
5742     //
5743     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5744     // debug values here after optimization:
5745     //
5746     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5747     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5748     //
5749     // Both describe the direct values of their associated variables.
5750     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5751                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5752   }
5753   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5754                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5755 }
5756 
5757 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5758   switch (Intrinsic) {
5759   case Intrinsic::smul_fix:
5760     return ISD::SMULFIX;
5761   case Intrinsic::umul_fix:
5762     return ISD::UMULFIX;
5763   case Intrinsic::smul_fix_sat:
5764     return ISD::SMULFIXSAT;
5765   case Intrinsic::umul_fix_sat:
5766     return ISD::UMULFIXSAT;
5767   case Intrinsic::sdiv_fix:
5768     return ISD::SDIVFIX;
5769   case Intrinsic::udiv_fix:
5770     return ISD::UDIVFIX;
5771   case Intrinsic::sdiv_fix_sat:
5772     return ISD::SDIVFIXSAT;
5773   case Intrinsic::udiv_fix_sat:
5774     return ISD::UDIVFIXSAT;
5775   default:
5776     llvm_unreachable("Unhandled fixed point intrinsic");
5777   }
5778 }
5779 
5780 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5781                                            const char *FunctionName) {
5782   assert(FunctionName && "FunctionName must not be nullptr");
5783   SDValue Callee = DAG.getExternalSymbol(
5784       FunctionName,
5785       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5786   LowerCallTo(&I, Callee, I.isTailCall());
5787 }
5788 
5789 /// Lower the call to the specified intrinsic function.
5790 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5791                                              unsigned Intrinsic) {
5792   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5793   SDLoc sdl = getCurSDLoc();
5794   DebugLoc dl = getCurDebugLoc();
5795   SDValue Res;
5796 
5797   switch (Intrinsic) {
5798   default:
5799     // By default, turn this into a target intrinsic node.
5800     visitTargetIntrinsic(I, Intrinsic);
5801     return;
5802   case Intrinsic::vscale: {
5803     match(&I, m_VScale(DAG.getDataLayout()));
5804     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5805     setValue(&I,
5806              DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1)));
5807     return;
5808   }
5809   case Intrinsic::vastart:  visitVAStart(I); return;
5810   case Intrinsic::vaend:    visitVAEnd(I); return;
5811   case Intrinsic::vacopy:   visitVACopy(I); return;
5812   case Intrinsic::returnaddress:
5813     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5814                              TLI.getPointerTy(DAG.getDataLayout()),
5815                              getValue(I.getArgOperand(0))));
5816     return;
5817   case Intrinsic::addressofreturnaddress:
5818     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5819                              TLI.getPointerTy(DAG.getDataLayout())));
5820     return;
5821   case Intrinsic::sponentry:
5822     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5823                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5824     return;
5825   case Intrinsic::frameaddress:
5826     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5827                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5828                              getValue(I.getArgOperand(0))));
5829     return;
5830   case Intrinsic::read_register: {
5831     Value *Reg = I.getArgOperand(0);
5832     SDValue Chain = getRoot();
5833     SDValue RegName =
5834         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5835     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5836     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5837       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5838     setValue(&I, Res);
5839     DAG.setRoot(Res.getValue(1));
5840     return;
5841   }
5842   case Intrinsic::write_register: {
5843     Value *Reg = I.getArgOperand(0);
5844     Value *RegValue = I.getArgOperand(1);
5845     SDValue Chain = getRoot();
5846     SDValue RegName =
5847         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5848     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5849                             RegName, getValue(RegValue)));
5850     return;
5851   }
5852   case Intrinsic::memcpy: {
5853     const auto &MCI = cast<MemCpyInst>(I);
5854     SDValue Op1 = getValue(I.getArgOperand(0));
5855     SDValue Op2 = getValue(I.getArgOperand(1));
5856     SDValue Op3 = getValue(I.getArgOperand(2));
5857     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5858     Align DstAlign = MCI.getDestAlign().valueOrOne();
5859     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5860     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5861     bool isVol = MCI.isVolatile();
5862     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5863     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5864     // node.
5865     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5866     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5867                                /* AlwaysInline */ false, isTC,
5868                                MachinePointerInfo(I.getArgOperand(0)),
5869                                MachinePointerInfo(I.getArgOperand(1)));
5870     updateDAGForMaybeTailCall(MC);
5871     return;
5872   }
5873   case Intrinsic::memcpy_inline: {
5874     const auto &MCI = cast<MemCpyInlineInst>(I);
5875     SDValue Dst = getValue(I.getArgOperand(0));
5876     SDValue Src = getValue(I.getArgOperand(1));
5877     SDValue Size = getValue(I.getArgOperand(2));
5878     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
5879     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
5880     Align DstAlign = MCI.getDestAlign().valueOrOne();
5881     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
5882     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5883     bool isVol = MCI.isVolatile();
5884     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5885     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5886     // node.
5887     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
5888                                /* AlwaysInline */ true, isTC,
5889                                MachinePointerInfo(I.getArgOperand(0)),
5890                                MachinePointerInfo(I.getArgOperand(1)));
5891     updateDAGForMaybeTailCall(MC);
5892     return;
5893   }
5894   case Intrinsic::memset: {
5895     const auto &MSI = cast<MemSetInst>(I);
5896     SDValue Op1 = getValue(I.getArgOperand(0));
5897     SDValue Op2 = getValue(I.getArgOperand(1));
5898     SDValue Op3 = getValue(I.getArgOperand(2));
5899     // @llvm.memset defines 0 and 1 to both mean no alignment.
5900     Align Alignment = MSI.getDestAlign().valueOrOne();
5901     bool isVol = MSI.isVolatile();
5902     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5903     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5904     SDValue MS = DAG.getMemset(Root, sdl, Op1, Op2, Op3, Alignment, isVol, isTC,
5905                                MachinePointerInfo(I.getArgOperand(0)));
5906     updateDAGForMaybeTailCall(MS);
5907     return;
5908   }
5909   case Intrinsic::memmove: {
5910     const auto &MMI = cast<MemMoveInst>(I);
5911     SDValue Op1 = getValue(I.getArgOperand(0));
5912     SDValue Op2 = getValue(I.getArgOperand(1));
5913     SDValue Op3 = getValue(I.getArgOperand(2));
5914     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5915     Align DstAlign = MMI.getDestAlign().valueOrOne();
5916     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
5917     Align Alignment = commonAlignment(DstAlign, SrcAlign);
5918     bool isVol = MMI.isVolatile();
5919     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5920     // FIXME: Support passing different dest/src alignments to the memmove DAG
5921     // node.
5922     SDValue Root = isVol ? getRoot() : getMemoryRoot();
5923     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
5924                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5925                                 MachinePointerInfo(I.getArgOperand(1)));
5926     updateDAGForMaybeTailCall(MM);
5927     return;
5928   }
5929   case Intrinsic::memcpy_element_unordered_atomic: {
5930     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5931     SDValue Dst = getValue(MI.getRawDest());
5932     SDValue Src = getValue(MI.getRawSource());
5933     SDValue Length = getValue(MI.getLength());
5934 
5935     unsigned DstAlign = MI.getDestAlignment();
5936     unsigned SrcAlign = MI.getSourceAlignment();
5937     Type *LengthTy = MI.getLength()->getType();
5938     unsigned ElemSz = MI.getElementSizeInBytes();
5939     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5940     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5941                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5942                                      MachinePointerInfo(MI.getRawDest()),
5943                                      MachinePointerInfo(MI.getRawSource()));
5944     updateDAGForMaybeTailCall(MC);
5945     return;
5946   }
5947   case Intrinsic::memmove_element_unordered_atomic: {
5948     auto &MI = cast<AtomicMemMoveInst>(I);
5949     SDValue Dst = getValue(MI.getRawDest());
5950     SDValue Src = getValue(MI.getRawSource());
5951     SDValue Length = getValue(MI.getLength());
5952 
5953     unsigned DstAlign = MI.getDestAlignment();
5954     unsigned SrcAlign = MI.getSourceAlignment();
5955     Type *LengthTy = MI.getLength()->getType();
5956     unsigned ElemSz = MI.getElementSizeInBytes();
5957     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5958     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5959                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5960                                       MachinePointerInfo(MI.getRawDest()),
5961                                       MachinePointerInfo(MI.getRawSource()));
5962     updateDAGForMaybeTailCall(MC);
5963     return;
5964   }
5965   case Intrinsic::memset_element_unordered_atomic: {
5966     auto &MI = cast<AtomicMemSetInst>(I);
5967     SDValue Dst = getValue(MI.getRawDest());
5968     SDValue Val = getValue(MI.getValue());
5969     SDValue Length = getValue(MI.getLength());
5970 
5971     unsigned DstAlign = MI.getDestAlignment();
5972     Type *LengthTy = MI.getLength()->getType();
5973     unsigned ElemSz = MI.getElementSizeInBytes();
5974     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5975     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5976                                      LengthTy, ElemSz, isTC,
5977                                      MachinePointerInfo(MI.getRawDest()));
5978     updateDAGForMaybeTailCall(MC);
5979     return;
5980   }
5981   case Intrinsic::dbg_addr:
5982   case Intrinsic::dbg_declare: {
5983     const auto &DI = cast<DbgVariableIntrinsic>(I);
5984     DILocalVariable *Variable = DI.getVariable();
5985     DIExpression *Expression = DI.getExpression();
5986     dropDanglingDebugInfo(Variable, Expression);
5987     assert(Variable && "Missing variable");
5988     LLVM_DEBUG(dbgs() << "SelectionDAG visiting debug intrinsic: " << DI
5989                       << "\n");
5990     // Check if address has undef value.
5991     const Value *Address = DI.getVariableLocation();
5992     if (!Address || isa<UndefValue>(Address) ||
5993         (Address->use_empty() && !isa<Argument>(Address))) {
5994       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
5995                         << " (bad/undef/unused-arg address)\n");
5996       return;
5997     }
5998 
5999     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
6000 
6001     // Check if this variable can be described by a frame index, typically
6002     // either as a static alloca or a byval parameter.
6003     int FI = std::numeric_limits<int>::max();
6004     if (const auto *AI =
6005             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
6006       if (AI->isStaticAlloca()) {
6007         auto I = FuncInfo.StaticAllocaMap.find(AI);
6008         if (I != FuncInfo.StaticAllocaMap.end())
6009           FI = I->second;
6010       }
6011     } else if (const auto *Arg = dyn_cast<Argument>(
6012                    Address->stripInBoundsConstantOffsets())) {
6013       FI = FuncInfo.getArgumentFrameIndex(Arg);
6014     }
6015 
6016     // llvm.dbg.addr is control dependent and always generates indirect
6017     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
6018     // the MachineFunction variable table.
6019     if (FI != std::numeric_limits<int>::max()) {
6020       if (Intrinsic == Intrinsic::dbg_addr) {
6021         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
6022             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
6023         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
6024       } else {
6025         LLVM_DEBUG(dbgs() << "Skipping " << DI
6026                           << " (variable info stashed in MF side table)\n");
6027       }
6028       return;
6029     }
6030 
6031     SDValue &N = NodeMap[Address];
6032     if (!N.getNode() && isa<Argument>(Address))
6033       // Check unused arguments map.
6034       N = UnusedArgNodeMap[Address];
6035     SDDbgValue *SDV;
6036     if (N.getNode()) {
6037       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
6038         Address = BCI->getOperand(0);
6039       // Parameters are handled specially.
6040       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
6041       if (isParameter && FINode) {
6042         // Byval parameter. We have a frame index at this point.
6043         SDV =
6044             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
6045                                       /*IsIndirect*/ true, dl, SDNodeOrder);
6046       } else if (isa<Argument>(Address)) {
6047         // Address is an argument, so try to emit its dbg value using
6048         // virtual register info from the FuncInfo.ValueMap.
6049         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
6050         return;
6051       } else {
6052         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
6053                               true, dl, SDNodeOrder);
6054       }
6055       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
6056     } else {
6057       // If Address is an argument then try to emit its dbg value using
6058       // virtual register info from the FuncInfo.ValueMap.
6059       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
6060                                     N)) {
6061         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI
6062                           << " (could not emit func-arg dbg_value)\n");
6063       }
6064     }
6065     return;
6066   }
6067   case Intrinsic::dbg_label: {
6068     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6069     DILabel *Label = DI.getLabel();
6070     assert(Label && "Missing label");
6071 
6072     SDDbgLabel *SDV;
6073     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6074     DAG.AddDbgLabel(SDV);
6075     return;
6076   }
6077   case Intrinsic::dbg_value: {
6078     const DbgValueInst &DI = cast<DbgValueInst>(I);
6079     assert(DI.getVariable() && "Missing variable");
6080 
6081     DILocalVariable *Variable = DI.getVariable();
6082     DIExpression *Expression = DI.getExpression();
6083     dropDanglingDebugInfo(Variable, Expression);
6084     const Value *V = DI.getValue();
6085     if (!V)
6086       return;
6087 
6088     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
6089         SDNodeOrder))
6090       return;
6091 
6092     // TODO: Dangling debug info will eventually either be resolved or produce
6093     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
6094     // between the original dbg.value location and its resolved DBG_VALUE, which
6095     // we should ideally fill with an extra Undef DBG_VALUE.
6096 
6097     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
6098     return;
6099   }
6100 
6101   case Intrinsic::eh_typeid_for: {
6102     // Find the type id for the given typeinfo.
6103     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6104     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6105     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6106     setValue(&I, Res);
6107     return;
6108   }
6109 
6110   case Intrinsic::eh_return_i32:
6111   case Intrinsic::eh_return_i64:
6112     DAG.getMachineFunction().setCallsEHReturn(true);
6113     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6114                             MVT::Other,
6115                             getControlRoot(),
6116                             getValue(I.getArgOperand(0)),
6117                             getValue(I.getArgOperand(1))));
6118     return;
6119   case Intrinsic::eh_unwind_init:
6120     DAG.getMachineFunction().setCallsUnwindInit(true);
6121     return;
6122   case Intrinsic::eh_dwarf_cfa:
6123     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6124                              TLI.getPointerTy(DAG.getDataLayout()),
6125                              getValue(I.getArgOperand(0))));
6126     return;
6127   case Intrinsic::eh_sjlj_callsite: {
6128     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6129     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
6130     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
6131     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6132 
6133     MMI.setCurrentCallSite(CI->getZExtValue());
6134     return;
6135   }
6136   case Intrinsic::eh_sjlj_functioncontext: {
6137     // Get and store the index of the function context.
6138     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6139     AllocaInst *FnCtx =
6140       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6141     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6142     MFI.setFunctionContextIndex(FI);
6143     return;
6144   }
6145   case Intrinsic::eh_sjlj_setjmp: {
6146     SDValue Ops[2];
6147     Ops[0] = getRoot();
6148     Ops[1] = getValue(I.getArgOperand(0));
6149     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6150                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6151     setValue(&I, Op.getValue(0));
6152     DAG.setRoot(Op.getValue(1));
6153     return;
6154   }
6155   case Intrinsic::eh_sjlj_longjmp:
6156     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6157                             getRoot(), getValue(I.getArgOperand(0))));
6158     return;
6159   case Intrinsic::eh_sjlj_setup_dispatch:
6160     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6161                             getRoot()));
6162     return;
6163   case Intrinsic::masked_gather:
6164     visitMaskedGather(I);
6165     return;
6166   case Intrinsic::masked_load:
6167     visitMaskedLoad(I);
6168     return;
6169   case Intrinsic::masked_scatter:
6170     visitMaskedScatter(I);
6171     return;
6172   case Intrinsic::masked_store:
6173     visitMaskedStore(I);
6174     return;
6175   case Intrinsic::masked_expandload:
6176     visitMaskedLoad(I, true /* IsExpanding */);
6177     return;
6178   case Intrinsic::masked_compressstore:
6179     visitMaskedStore(I, true /* IsCompressing */);
6180     return;
6181   case Intrinsic::powi:
6182     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6183                             getValue(I.getArgOperand(1)), DAG));
6184     return;
6185   case Intrinsic::log:
6186     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6187     return;
6188   case Intrinsic::log2:
6189     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6190     return;
6191   case Intrinsic::log10:
6192     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6193     return;
6194   case Intrinsic::exp:
6195     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6196     return;
6197   case Intrinsic::exp2:
6198     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6199     return;
6200   case Intrinsic::pow:
6201     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6202                            getValue(I.getArgOperand(1)), DAG, TLI));
6203     return;
6204   case Intrinsic::sqrt:
6205   case Intrinsic::fabs:
6206   case Intrinsic::sin:
6207   case Intrinsic::cos:
6208   case Intrinsic::floor:
6209   case Intrinsic::ceil:
6210   case Intrinsic::trunc:
6211   case Intrinsic::rint:
6212   case Intrinsic::nearbyint:
6213   case Intrinsic::round:
6214   case Intrinsic::canonicalize: {
6215     unsigned Opcode;
6216     switch (Intrinsic) {
6217     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6218     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6219     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6220     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6221     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6222     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6223     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6224     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6225     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6226     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6227     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6228     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6229     }
6230 
6231     setValue(&I, DAG.getNode(Opcode, sdl,
6232                              getValue(I.getArgOperand(0)).getValueType(),
6233                              getValue(I.getArgOperand(0))));
6234     return;
6235   }
6236   case Intrinsic::lround:
6237   case Intrinsic::llround:
6238   case Intrinsic::lrint:
6239   case Intrinsic::llrint: {
6240     unsigned Opcode;
6241     switch (Intrinsic) {
6242     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6243     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6244     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6245     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6246     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6247     }
6248 
6249     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6250     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6251                              getValue(I.getArgOperand(0))));
6252     return;
6253   }
6254   case Intrinsic::minnum:
6255     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6256                              getValue(I.getArgOperand(0)).getValueType(),
6257                              getValue(I.getArgOperand(0)),
6258                              getValue(I.getArgOperand(1))));
6259     return;
6260   case Intrinsic::maxnum:
6261     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6262                              getValue(I.getArgOperand(0)).getValueType(),
6263                              getValue(I.getArgOperand(0)),
6264                              getValue(I.getArgOperand(1))));
6265     return;
6266   case Intrinsic::minimum:
6267     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6268                              getValue(I.getArgOperand(0)).getValueType(),
6269                              getValue(I.getArgOperand(0)),
6270                              getValue(I.getArgOperand(1))));
6271     return;
6272   case Intrinsic::maximum:
6273     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6274                              getValue(I.getArgOperand(0)).getValueType(),
6275                              getValue(I.getArgOperand(0)),
6276                              getValue(I.getArgOperand(1))));
6277     return;
6278   case Intrinsic::copysign:
6279     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6280                              getValue(I.getArgOperand(0)).getValueType(),
6281                              getValue(I.getArgOperand(0)),
6282                              getValue(I.getArgOperand(1))));
6283     return;
6284   case Intrinsic::fma:
6285     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6286                              getValue(I.getArgOperand(0)).getValueType(),
6287                              getValue(I.getArgOperand(0)),
6288                              getValue(I.getArgOperand(1)),
6289                              getValue(I.getArgOperand(2))));
6290     return;
6291 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6292   case Intrinsic::INTRINSIC:
6293 #include "llvm/IR/ConstrainedOps.def"
6294     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6295     return;
6296   case Intrinsic::fmuladd: {
6297     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6298     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6299         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6300       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6301                                getValue(I.getArgOperand(0)).getValueType(),
6302                                getValue(I.getArgOperand(0)),
6303                                getValue(I.getArgOperand(1)),
6304                                getValue(I.getArgOperand(2))));
6305     } else {
6306       // TODO: Intrinsic calls should have fast-math-flags.
6307       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6308                                 getValue(I.getArgOperand(0)).getValueType(),
6309                                 getValue(I.getArgOperand(0)),
6310                                 getValue(I.getArgOperand(1)));
6311       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6312                                 getValue(I.getArgOperand(0)).getValueType(),
6313                                 Mul,
6314                                 getValue(I.getArgOperand(2)));
6315       setValue(&I, Add);
6316     }
6317     return;
6318   }
6319   case Intrinsic::convert_to_fp16:
6320     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6321                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6322                                          getValue(I.getArgOperand(0)),
6323                                          DAG.getTargetConstant(0, sdl,
6324                                                                MVT::i32))));
6325     return;
6326   case Intrinsic::convert_from_fp16:
6327     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6328                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6329                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6330                                          getValue(I.getArgOperand(0)))));
6331     return;
6332   case Intrinsic::pcmarker: {
6333     SDValue Tmp = getValue(I.getArgOperand(0));
6334     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6335     return;
6336   }
6337   case Intrinsic::readcyclecounter: {
6338     SDValue Op = getRoot();
6339     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6340                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6341     setValue(&I, Res);
6342     DAG.setRoot(Res.getValue(1));
6343     return;
6344   }
6345   case Intrinsic::bitreverse:
6346     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6347                              getValue(I.getArgOperand(0)).getValueType(),
6348                              getValue(I.getArgOperand(0))));
6349     return;
6350   case Intrinsic::bswap:
6351     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6352                              getValue(I.getArgOperand(0)).getValueType(),
6353                              getValue(I.getArgOperand(0))));
6354     return;
6355   case Intrinsic::cttz: {
6356     SDValue Arg = getValue(I.getArgOperand(0));
6357     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6358     EVT Ty = Arg.getValueType();
6359     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6360                              sdl, Ty, Arg));
6361     return;
6362   }
6363   case Intrinsic::ctlz: {
6364     SDValue Arg = getValue(I.getArgOperand(0));
6365     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6366     EVT Ty = Arg.getValueType();
6367     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6368                              sdl, Ty, Arg));
6369     return;
6370   }
6371   case Intrinsic::ctpop: {
6372     SDValue Arg = getValue(I.getArgOperand(0));
6373     EVT Ty = Arg.getValueType();
6374     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6375     return;
6376   }
6377   case Intrinsic::fshl:
6378   case Intrinsic::fshr: {
6379     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6380     SDValue X = getValue(I.getArgOperand(0));
6381     SDValue Y = getValue(I.getArgOperand(1));
6382     SDValue Z = getValue(I.getArgOperand(2));
6383     EVT VT = X.getValueType();
6384     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6385     SDValue Zero = DAG.getConstant(0, sdl, VT);
6386     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6387 
6388     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6389     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6390       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6391       return;
6392     }
6393 
6394     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6395     // avoid the select that is necessary in the general case to filter out
6396     // the 0-shift possibility that leads to UB.
6397     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6398       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6399       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6400         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6401         return;
6402       }
6403 
6404       // Some targets only rotate one way. Try the opposite direction.
6405       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6406       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6407         // Negate the shift amount because it is safe to ignore the high bits.
6408         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6409         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6410         return;
6411       }
6412 
6413       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6414       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6415       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6416       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6417       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6418       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6419       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6420       return;
6421     }
6422 
6423     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6424     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6425     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6426     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6427     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6428     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6429 
6430     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6431     // and that is undefined. We must compare and select to avoid UB.
6432     EVT CCVT = MVT::i1;
6433     if (VT.isVector())
6434       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6435 
6436     // For fshl, 0-shift returns the 1st arg (X).
6437     // For fshr, 0-shift returns the 2nd arg (Y).
6438     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6439     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6440     return;
6441   }
6442   case Intrinsic::sadd_sat: {
6443     SDValue Op1 = getValue(I.getArgOperand(0));
6444     SDValue Op2 = getValue(I.getArgOperand(1));
6445     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6446     return;
6447   }
6448   case Intrinsic::uadd_sat: {
6449     SDValue Op1 = getValue(I.getArgOperand(0));
6450     SDValue Op2 = getValue(I.getArgOperand(1));
6451     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6452     return;
6453   }
6454   case Intrinsic::ssub_sat: {
6455     SDValue Op1 = getValue(I.getArgOperand(0));
6456     SDValue Op2 = getValue(I.getArgOperand(1));
6457     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6458     return;
6459   }
6460   case Intrinsic::usub_sat: {
6461     SDValue Op1 = getValue(I.getArgOperand(0));
6462     SDValue Op2 = getValue(I.getArgOperand(1));
6463     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6464     return;
6465   }
6466   case Intrinsic::smul_fix:
6467   case Intrinsic::umul_fix:
6468   case Intrinsic::smul_fix_sat:
6469   case Intrinsic::umul_fix_sat: {
6470     SDValue Op1 = getValue(I.getArgOperand(0));
6471     SDValue Op2 = getValue(I.getArgOperand(1));
6472     SDValue Op3 = getValue(I.getArgOperand(2));
6473     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6474                              Op1.getValueType(), Op1, Op2, Op3));
6475     return;
6476   }
6477   case Intrinsic::sdiv_fix:
6478   case Intrinsic::udiv_fix:
6479   case Intrinsic::sdiv_fix_sat:
6480   case Intrinsic::udiv_fix_sat: {
6481     SDValue Op1 = getValue(I.getArgOperand(0));
6482     SDValue Op2 = getValue(I.getArgOperand(1));
6483     SDValue Op3 = getValue(I.getArgOperand(2));
6484     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6485                               Op1, Op2, Op3, DAG, TLI));
6486     return;
6487   }
6488   case Intrinsic::stacksave: {
6489     SDValue Op = getRoot();
6490     Res = DAG.getNode(
6491         ISD::STACKSAVE, sdl,
6492         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6493     setValue(&I, Res);
6494     DAG.setRoot(Res.getValue(1));
6495     return;
6496   }
6497   case Intrinsic::stackrestore:
6498     Res = getValue(I.getArgOperand(0));
6499     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6500     return;
6501   case Intrinsic::get_dynamic_area_offset: {
6502     SDValue Op = getRoot();
6503     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6504     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6505     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6506     // target.
6507     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6508       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6509                          " intrinsic!");
6510     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6511                       Op);
6512     DAG.setRoot(Op);
6513     setValue(&I, Res);
6514     return;
6515   }
6516   case Intrinsic::stackguard: {
6517     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6518     MachineFunction &MF = DAG.getMachineFunction();
6519     const Module &M = *MF.getFunction().getParent();
6520     SDValue Chain = getRoot();
6521     if (TLI.useLoadStackGuardNode()) {
6522       Res = getLoadStackGuard(DAG, sdl, Chain);
6523     } else {
6524       const Value *Global = TLI.getSDagStackGuard(M);
6525       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6526       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6527                         MachinePointerInfo(Global, 0), Align,
6528                         MachineMemOperand::MOVolatile);
6529     }
6530     if (TLI.useStackGuardXorFP())
6531       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6532     DAG.setRoot(Chain);
6533     setValue(&I, Res);
6534     return;
6535   }
6536   case Intrinsic::stackprotector: {
6537     // Emit code into the DAG to store the stack guard onto the stack.
6538     MachineFunction &MF = DAG.getMachineFunction();
6539     MachineFrameInfo &MFI = MF.getFrameInfo();
6540     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6541     SDValue Src, Chain = getRoot();
6542 
6543     if (TLI.useLoadStackGuardNode())
6544       Src = getLoadStackGuard(DAG, sdl, Chain);
6545     else
6546       Src = getValue(I.getArgOperand(0));   // The guard's value.
6547 
6548     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6549 
6550     int FI = FuncInfo.StaticAllocaMap[Slot];
6551     MFI.setStackProtectorIndex(FI);
6552 
6553     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6554 
6555     // Store the stack protector onto the stack.
6556     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6557                                                  DAG.getMachineFunction(), FI),
6558                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6559     setValue(&I, Res);
6560     DAG.setRoot(Res);
6561     return;
6562   }
6563   case Intrinsic::objectsize:
6564     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6565 
6566   case Intrinsic::is_constant:
6567     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6568 
6569   case Intrinsic::annotation:
6570   case Intrinsic::ptr_annotation:
6571   case Intrinsic::launder_invariant_group:
6572   case Intrinsic::strip_invariant_group:
6573     // Drop the intrinsic, but forward the value
6574     setValue(&I, getValue(I.getOperand(0)));
6575     return;
6576   case Intrinsic::assume:
6577   case Intrinsic::var_annotation:
6578   case Intrinsic::sideeffect:
6579     // Discard annotate attributes, assumptions, and artificial side-effects.
6580     return;
6581 
6582   case Intrinsic::codeview_annotation: {
6583     // Emit a label associated with this metadata.
6584     MachineFunction &MF = DAG.getMachineFunction();
6585     MCSymbol *Label =
6586         MF.getMMI().getContext().createTempSymbol("annotation", true);
6587     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6588     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6589     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6590     DAG.setRoot(Res);
6591     return;
6592   }
6593 
6594   case Intrinsic::init_trampoline: {
6595     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6596 
6597     SDValue Ops[6];
6598     Ops[0] = getRoot();
6599     Ops[1] = getValue(I.getArgOperand(0));
6600     Ops[2] = getValue(I.getArgOperand(1));
6601     Ops[3] = getValue(I.getArgOperand(2));
6602     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6603     Ops[5] = DAG.getSrcValue(F);
6604 
6605     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6606 
6607     DAG.setRoot(Res);
6608     return;
6609   }
6610   case Intrinsic::adjust_trampoline:
6611     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6612                              TLI.getPointerTy(DAG.getDataLayout()),
6613                              getValue(I.getArgOperand(0))));
6614     return;
6615   case Intrinsic::gcroot: {
6616     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6617            "only valid in functions with gc specified, enforced by Verifier");
6618     assert(GFI && "implied by previous");
6619     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6620     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6621 
6622     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6623     GFI->addStackRoot(FI->getIndex(), TypeMap);
6624     return;
6625   }
6626   case Intrinsic::gcread:
6627   case Intrinsic::gcwrite:
6628     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6629   case Intrinsic::flt_rounds:
6630     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6631     return;
6632 
6633   case Intrinsic::expect:
6634     // Just replace __builtin_expect(exp, c) with EXP.
6635     setValue(&I, getValue(I.getArgOperand(0)));
6636     return;
6637 
6638   case Intrinsic::debugtrap:
6639   case Intrinsic::trap: {
6640     StringRef TrapFuncName =
6641         I.getAttributes()
6642             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6643             .getValueAsString();
6644     if (TrapFuncName.empty()) {
6645       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6646         ISD::TRAP : ISD::DEBUGTRAP;
6647       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6648       return;
6649     }
6650     TargetLowering::ArgListTy Args;
6651 
6652     TargetLowering::CallLoweringInfo CLI(DAG);
6653     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6654         CallingConv::C, I.getType(),
6655         DAG.getExternalSymbol(TrapFuncName.data(),
6656                               TLI.getPointerTy(DAG.getDataLayout())),
6657         std::move(Args));
6658 
6659     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6660     DAG.setRoot(Result.second);
6661     return;
6662   }
6663 
6664   case Intrinsic::uadd_with_overflow:
6665   case Intrinsic::sadd_with_overflow:
6666   case Intrinsic::usub_with_overflow:
6667   case Intrinsic::ssub_with_overflow:
6668   case Intrinsic::umul_with_overflow:
6669   case Intrinsic::smul_with_overflow: {
6670     ISD::NodeType Op;
6671     switch (Intrinsic) {
6672     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6673     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6674     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6675     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6676     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6677     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6678     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6679     }
6680     SDValue Op1 = getValue(I.getArgOperand(0));
6681     SDValue Op2 = getValue(I.getArgOperand(1));
6682 
6683     EVT ResultVT = Op1.getValueType();
6684     EVT OverflowVT = MVT::i1;
6685     if (ResultVT.isVector())
6686       OverflowVT = EVT::getVectorVT(
6687           *Context, OverflowVT, ResultVT.getVectorNumElements());
6688 
6689     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6690     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6691     return;
6692   }
6693   case Intrinsic::prefetch: {
6694     SDValue Ops[5];
6695     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6696     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6697     Ops[0] = DAG.getRoot();
6698     Ops[1] = getValue(I.getArgOperand(0));
6699     Ops[2] = getValue(I.getArgOperand(1));
6700     Ops[3] = getValue(I.getArgOperand(2));
6701     Ops[4] = getValue(I.getArgOperand(3));
6702     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6703                                              DAG.getVTList(MVT::Other), Ops,
6704                                              EVT::getIntegerVT(*Context, 8),
6705                                              MachinePointerInfo(I.getArgOperand(0)),
6706                                              0, /* align */
6707                                              Flags);
6708 
6709     // Chain the prefetch in parallell with any pending loads, to stay out of
6710     // the way of later optimizations.
6711     PendingLoads.push_back(Result);
6712     Result = getRoot();
6713     DAG.setRoot(Result);
6714     return;
6715   }
6716   case Intrinsic::lifetime_start:
6717   case Intrinsic::lifetime_end: {
6718     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6719     // Stack coloring is not enabled in O0, discard region information.
6720     if (TM.getOptLevel() == CodeGenOpt::None)
6721       return;
6722 
6723     const int64_t ObjectSize =
6724         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6725     Value *const ObjectPtr = I.getArgOperand(1);
6726     SmallVector<const Value *, 4> Allocas;
6727     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6728 
6729     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6730            E = Allocas.end(); Object != E; ++Object) {
6731       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6732 
6733       // Could not find an Alloca.
6734       if (!LifetimeObject)
6735         continue;
6736 
6737       // First check that the Alloca is static, otherwise it won't have a
6738       // valid frame index.
6739       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6740       if (SI == FuncInfo.StaticAllocaMap.end())
6741         return;
6742 
6743       const int FrameIndex = SI->second;
6744       int64_t Offset;
6745       if (GetPointerBaseWithConstantOffset(
6746               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6747         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6748       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6749                                 Offset);
6750       DAG.setRoot(Res);
6751     }
6752     return;
6753   }
6754   case Intrinsic::invariant_start:
6755     // Discard region information.
6756     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6757     return;
6758   case Intrinsic::invariant_end:
6759     // Discard region information.
6760     return;
6761   case Intrinsic::clear_cache:
6762     /// FunctionName may be null.
6763     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6764       lowerCallToExternalSymbol(I, FunctionName);
6765     return;
6766   case Intrinsic::donothing:
6767     // ignore
6768     return;
6769   case Intrinsic::experimental_stackmap:
6770     visitStackmap(I);
6771     return;
6772   case Intrinsic::experimental_patchpoint_void:
6773   case Intrinsic::experimental_patchpoint_i64:
6774     visitPatchpoint(&I);
6775     return;
6776   case Intrinsic::experimental_gc_statepoint:
6777     LowerStatepoint(ImmutableStatepoint(&I));
6778     return;
6779   case Intrinsic::experimental_gc_result:
6780     visitGCResult(cast<GCResultInst>(I));
6781     return;
6782   case Intrinsic::experimental_gc_relocate:
6783     visitGCRelocate(cast<GCRelocateInst>(I));
6784     return;
6785   case Intrinsic::instrprof_increment:
6786     llvm_unreachable("instrprof failed to lower an increment");
6787   case Intrinsic::instrprof_value_profile:
6788     llvm_unreachable("instrprof failed to lower a value profiling call");
6789   case Intrinsic::localescape: {
6790     MachineFunction &MF = DAG.getMachineFunction();
6791     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6792 
6793     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6794     // is the same on all targets.
6795     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6796       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6797       if (isa<ConstantPointerNull>(Arg))
6798         continue; // Skip null pointers. They represent a hole in index space.
6799       AllocaInst *Slot = cast<AllocaInst>(Arg);
6800       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6801              "can only escape static allocas");
6802       int FI = FuncInfo.StaticAllocaMap[Slot];
6803       MCSymbol *FrameAllocSym =
6804           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6805               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6806       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6807               TII->get(TargetOpcode::LOCAL_ESCAPE))
6808           .addSym(FrameAllocSym)
6809           .addFrameIndex(FI);
6810     }
6811 
6812     return;
6813   }
6814 
6815   case Intrinsic::localrecover: {
6816     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6817     MachineFunction &MF = DAG.getMachineFunction();
6818     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6819 
6820     // Get the symbol that defines the frame offset.
6821     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6822     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6823     unsigned IdxVal =
6824         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6825     MCSymbol *FrameAllocSym =
6826         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6827             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6828 
6829     // Create a MCSymbol for the label to avoid any target lowering
6830     // that would make this PC relative.
6831     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6832     SDValue OffsetVal =
6833         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6834 
6835     // Add the offset to the FP.
6836     Value *FP = I.getArgOperand(1);
6837     SDValue FPVal = getValue(FP);
6838     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6839     setValue(&I, Add);
6840 
6841     return;
6842   }
6843 
6844   case Intrinsic::eh_exceptionpointer:
6845   case Intrinsic::eh_exceptioncode: {
6846     // Get the exception pointer vreg, copy from it, and resize it to fit.
6847     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6848     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6849     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6850     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6851     SDValue N =
6852         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6853     if (Intrinsic == Intrinsic::eh_exceptioncode)
6854       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6855     setValue(&I, N);
6856     return;
6857   }
6858   case Intrinsic::xray_customevent: {
6859     // Here we want to make sure that the intrinsic behaves as if it has a
6860     // specific calling convention, and only for x86_64.
6861     // FIXME: Support other platforms later.
6862     const auto &Triple = DAG.getTarget().getTargetTriple();
6863     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6864       return;
6865 
6866     SDLoc DL = getCurSDLoc();
6867     SmallVector<SDValue, 8> Ops;
6868 
6869     // We want to say that we always want the arguments in registers.
6870     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6871     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6872     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6873     SDValue Chain = getRoot();
6874     Ops.push_back(LogEntryVal);
6875     Ops.push_back(StrSizeVal);
6876     Ops.push_back(Chain);
6877 
6878     // We need to enforce the calling convention for the callsite, so that
6879     // argument ordering is enforced correctly, and that register allocation can
6880     // see that some registers may be assumed clobbered and have to preserve
6881     // them across calls to the intrinsic.
6882     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6883                                            DL, NodeTys, Ops);
6884     SDValue patchableNode = SDValue(MN, 0);
6885     DAG.setRoot(patchableNode);
6886     setValue(&I, patchableNode);
6887     return;
6888   }
6889   case Intrinsic::xray_typedevent: {
6890     // Here we want to make sure that the intrinsic behaves as if it has a
6891     // specific calling convention, and only for x86_64.
6892     // FIXME: Support other platforms later.
6893     const auto &Triple = DAG.getTarget().getTargetTriple();
6894     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6895       return;
6896 
6897     SDLoc DL = getCurSDLoc();
6898     SmallVector<SDValue, 8> Ops;
6899 
6900     // We want to say that we always want the arguments in registers.
6901     // It's unclear to me how manipulating the selection DAG here forces callers
6902     // to provide arguments in registers instead of on the stack.
6903     SDValue LogTypeId = getValue(I.getArgOperand(0));
6904     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6905     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6906     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6907     SDValue Chain = getRoot();
6908     Ops.push_back(LogTypeId);
6909     Ops.push_back(LogEntryVal);
6910     Ops.push_back(StrSizeVal);
6911     Ops.push_back(Chain);
6912 
6913     // We need to enforce the calling convention for the callsite, so that
6914     // argument ordering is enforced correctly, and that register allocation can
6915     // see that some registers may be assumed clobbered and have to preserve
6916     // them across calls to the intrinsic.
6917     MachineSDNode *MN = DAG.getMachineNode(
6918         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6919     SDValue patchableNode = SDValue(MN, 0);
6920     DAG.setRoot(patchableNode);
6921     setValue(&I, patchableNode);
6922     return;
6923   }
6924   case Intrinsic::experimental_deoptimize:
6925     LowerDeoptimizeCall(&I);
6926     return;
6927 
6928   case Intrinsic::experimental_vector_reduce_v2_fadd:
6929   case Intrinsic::experimental_vector_reduce_v2_fmul:
6930   case Intrinsic::experimental_vector_reduce_add:
6931   case Intrinsic::experimental_vector_reduce_mul:
6932   case Intrinsic::experimental_vector_reduce_and:
6933   case Intrinsic::experimental_vector_reduce_or:
6934   case Intrinsic::experimental_vector_reduce_xor:
6935   case Intrinsic::experimental_vector_reduce_smax:
6936   case Intrinsic::experimental_vector_reduce_smin:
6937   case Intrinsic::experimental_vector_reduce_umax:
6938   case Intrinsic::experimental_vector_reduce_umin:
6939   case Intrinsic::experimental_vector_reduce_fmax:
6940   case Intrinsic::experimental_vector_reduce_fmin:
6941     visitVectorReduce(I, Intrinsic);
6942     return;
6943 
6944   case Intrinsic::icall_branch_funnel: {
6945     SmallVector<SDValue, 16> Ops;
6946     Ops.push_back(getValue(I.getArgOperand(0)));
6947 
6948     int64_t Offset;
6949     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6950         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6951     if (!Base)
6952       report_fatal_error(
6953           "llvm.icall.branch.funnel operand must be a GlobalValue");
6954     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6955 
6956     struct BranchFunnelTarget {
6957       int64_t Offset;
6958       SDValue Target;
6959     };
6960     SmallVector<BranchFunnelTarget, 8> Targets;
6961 
6962     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6963       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6964           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6965       if (ElemBase != Base)
6966         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6967                            "to the same GlobalValue");
6968 
6969       SDValue Val = getValue(I.getArgOperand(Op + 1));
6970       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6971       if (!GA)
6972         report_fatal_error(
6973             "llvm.icall.branch.funnel operand must be a GlobalValue");
6974       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6975                                      GA->getGlobal(), getCurSDLoc(),
6976                                      Val.getValueType(), GA->getOffset())});
6977     }
6978     llvm::sort(Targets,
6979                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6980                  return T1.Offset < T2.Offset;
6981                });
6982 
6983     for (auto &T : Targets) {
6984       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6985       Ops.push_back(T.Target);
6986     }
6987 
6988     Ops.push_back(DAG.getRoot()); // Chain
6989     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6990                                  getCurSDLoc(), MVT::Other, Ops),
6991               0);
6992     DAG.setRoot(N);
6993     setValue(&I, N);
6994     HasTailCall = true;
6995     return;
6996   }
6997 
6998   case Intrinsic::wasm_landingpad_index:
6999     // Information this intrinsic contained has been transferred to
7000     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7001     // delete it now.
7002     return;
7003 
7004   case Intrinsic::aarch64_settag:
7005   case Intrinsic::aarch64_settag_zero: {
7006     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7007     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7008     SDValue Val = TSI.EmitTargetCodeForSetTag(
7009         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
7010         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7011         ZeroMemory);
7012     DAG.setRoot(Val);
7013     setValue(&I, Val);
7014     return;
7015   }
7016   case Intrinsic::ptrmask: {
7017     SDValue Ptr = getValue(I.getOperand(0));
7018     SDValue Const = getValue(I.getOperand(1));
7019 
7020     EVT DestVT =
7021         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7022 
7023     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
7024                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
7025     return;
7026   }
7027   }
7028 }
7029 
7030 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7031     const ConstrainedFPIntrinsic &FPI) {
7032   SDLoc sdl = getCurSDLoc();
7033 
7034   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7035   SmallVector<EVT, 4> ValueVTs;
7036   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
7037   ValueVTs.push_back(MVT::Other); // Out chain
7038 
7039   // We do not need to serialize constrained FP intrinsics against
7040   // each other or against (nonvolatile) loads, so they can be
7041   // chained like loads.
7042   SDValue Chain = DAG.getRoot();
7043   SmallVector<SDValue, 4> Opers;
7044   Opers.push_back(Chain);
7045   if (FPI.isUnaryOp()) {
7046     Opers.push_back(getValue(FPI.getArgOperand(0)));
7047   } else if (FPI.isTernaryOp()) {
7048     Opers.push_back(getValue(FPI.getArgOperand(0)));
7049     Opers.push_back(getValue(FPI.getArgOperand(1)));
7050     Opers.push_back(getValue(FPI.getArgOperand(2)));
7051   } else {
7052     Opers.push_back(getValue(FPI.getArgOperand(0)));
7053     Opers.push_back(getValue(FPI.getArgOperand(1)));
7054   }
7055 
7056   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7057     assert(Result.getNode()->getNumValues() == 2);
7058 
7059     // Push node to the appropriate list so that future instructions can be
7060     // chained up correctly.
7061     SDValue OutChain = Result.getValue(1);
7062     switch (EB) {
7063     case fp::ExceptionBehavior::ebIgnore:
7064       // The only reason why ebIgnore nodes still need to be chained is that
7065       // they might depend on the current rounding mode, and therefore must
7066       // not be moved across instruction that may change that mode.
7067       LLVM_FALLTHROUGH;
7068     case fp::ExceptionBehavior::ebMayTrap:
7069       // These must not be moved across calls or instructions that may change
7070       // floating-point exception masks.
7071       PendingConstrainedFP.push_back(OutChain);
7072       break;
7073     case fp::ExceptionBehavior::ebStrict:
7074       // These must not be moved across calls or instructions that may change
7075       // floating-point exception masks or read floating-point exception flags.
7076       // In addition, they cannot be optimized out even if unused.
7077       PendingConstrainedFPStrict.push_back(OutChain);
7078       break;
7079     }
7080   };
7081 
7082   SDVTList VTs = DAG.getVTList(ValueVTs);
7083   fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue();
7084 
7085   unsigned Opcode;
7086   switch (FPI.getIntrinsicID()) {
7087   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7088 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
7089   case Intrinsic::INTRINSIC:                                                   \
7090     Opcode = ISD::STRICT_##DAGN;                                               \
7091     break;
7092 #include "llvm/IR/ConstrainedOps.def"
7093   case Intrinsic::experimental_constrained_fmuladd: {
7094     Opcode = ISD::STRICT_FMA;
7095     // Break fmuladd into fmul and fadd.
7096     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
7097         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(),
7098                                         ValueVTs[0])) {
7099       Opers.pop_back();
7100       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers);
7101       pushOutChain(Mul, EB);
7102       Opcode = ISD::STRICT_FADD;
7103       Opers.clear();
7104       Opers.push_back(Mul.getValue(1));
7105       Opers.push_back(Mul.getValue(0));
7106       Opers.push_back(getValue(FPI.getArgOperand(2)));
7107     }
7108     break;
7109   }
7110   }
7111 
7112   // A few strict DAG nodes carry additional operands that are not
7113   // set up by the default code above.
7114   switch (Opcode) {
7115   default: break;
7116   case ISD::STRICT_FP_ROUND:
7117     Opers.push_back(
7118         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
7119     break;
7120   case ISD::STRICT_FSETCC:
7121   case ISD::STRICT_FSETCCS: {
7122     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
7123     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
7124     break;
7125   }
7126   }
7127 
7128   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
7129   pushOutChain(Result, EB);
7130 
7131   SDValue FPResult = Result.getValue(0);
7132   setValue(&FPI, FPResult);
7133 }
7134 
7135 std::pair<SDValue, SDValue>
7136 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
7137                                     const BasicBlock *EHPadBB) {
7138   MachineFunction &MF = DAG.getMachineFunction();
7139   MachineModuleInfo &MMI = MF.getMMI();
7140   MCSymbol *BeginLabel = nullptr;
7141 
7142   if (EHPadBB) {
7143     // Insert a label before the invoke call to mark the try range.  This can be
7144     // used to detect deletion of the invoke via the MachineModuleInfo.
7145     BeginLabel = MMI.getContext().createTempSymbol();
7146 
7147     // For SjLj, keep track of which landing pads go with which invokes
7148     // so as to maintain the ordering of pads in the LSDA.
7149     unsigned CallSiteIndex = MMI.getCurrentCallSite();
7150     if (CallSiteIndex) {
7151       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
7152       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
7153 
7154       // Now that the call site is handled, stop tracking it.
7155       MMI.setCurrentCallSite(0);
7156     }
7157 
7158     // Both PendingLoads and PendingExports must be flushed here;
7159     // this call might not return.
7160     (void)getRoot();
7161     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
7162 
7163     CLI.setChain(getRoot());
7164   }
7165   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7166   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7167 
7168   assert((CLI.IsTailCall || Result.second.getNode()) &&
7169          "Non-null chain expected with non-tail call!");
7170   assert((Result.second.getNode() || !Result.first.getNode()) &&
7171          "Null value expected with tail call!");
7172 
7173   if (!Result.second.getNode()) {
7174     // As a special case, a null chain means that a tail call has been emitted
7175     // and the DAG root is already updated.
7176     HasTailCall = true;
7177 
7178     // Since there's no actual continuation from this block, nothing can be
7179     // relying on us setting vregs for them.
7180     PendingExports.clear();
7181   } else {
7182     DAG.setRoot(Result.second);
7183   }
7184 
7185   if (EHPadBB) {
7186     // Insert a label at the end of the invoke call to mark the try range.  This
7187     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7188     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7189     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7190 
7191     // Inform MachineModuleInfo of range.
7192     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7193     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7194     // actually use outlined funclets and their LSDA info style.
7195     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7196       assert(CLI.CS);
7197       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7198       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7199                                 BeginLabel, EndLabel);
7200     } else if (!isScopedEHPersonality(Pers)) {
7201       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7202     }
7203   }
7204 
7205   return Result;
7206 }
7207 
7208 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7209                                       bool isTailCall,
7210                                       const BasicBlock *EHPadBB) {
7211   auto &DL = DAG.getDataLayout();
7212   FunctionType *FTy = CS.getFunctionType();
7213   Type *RetTy = CS.getType();
7214 
7215   TargetLowering::ArgListTy Args;
7216   Args.reserve(CS.arg_size());
7217 
7218   const Value *SwiftErrorVal = nullptr;
7219   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7220 
7221   if (isTailCall) {
7222     // Avoid emitting tail calls in functions with the disable-tail-calls
7223     // attribute.
7224     auto *Caller = CS.getInstruction()->getParent()->getParent();
7225     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
7226         "true")
7227       isTailCall = false;
7228 
7229     // We can't tail call inside a function with a swifterror argument. Lowering
7230     // does not support this yet. It would have to move into the swifterror
7231     // register before the call.
7232     if (TLI.supportSwiftError() &&
7233         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7234       isTailCall = false;
7235   }
7236 
7237   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7238        i != e; ++i) {
7239     TargetLowering::ArgListEntry Entry;
7240     const Value *V = *i;
7241 
7242     // Skip empty types
7243     if (V->getType()->isEmptyTy())
7244       continue;
7245 
7246     SDValue ArgNode = getValue(V);
7247     Entry.Node = ArgNode; Entry.Ty = V->getType();
7248 
7249     Entry.setAttributes(&CS, i - CS.arg_begin());
7250 
7251     // Use swifterror virtual register as input to the call.
7252     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7253       SwiftErrorVal = V;
7254       // We find the virtual register for the actual swifterror argument.
7255       // Instead of using the Value, we use the virtual register instead.
7256       Entry.Node = DAG.getRegister(
7257           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7258           EVT(TLI.getPointerTy(DL)));
7259     }
7260 
7261     Args.push_back(Entry);
7262 
7263     // If we have an explicit sret argument that is an Instruction, (i.e., it
7264     // might point to function-local memory), we can't meaningfully tail-call.
7265     if (Entry.IsSRet && isa<Instruction>(V))
7266       isTailCall = false;
7267   }
7268 
7269   // If call site has a cfguardtarget operand bundle, create and add an
7270   // additional ArgListEntry.
7271   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7272     TargetLowering::ArgListEntry Entry;
7273     Value *V = Bundle->Inputs[0];
7274     SDValue ArgNode = getValue(V);
7275     Entry.Node = ArgNode;
7276     Entry.Ty = V->getType();
7277     Entry.IsCFGuardTarget = true;
7278     Args.push_back(Entry);
7279   }
7280 
7281   // Check if target-independent constraints permit a tail call here.
7282   // Target-dependent constraints are checked within TLI->LowerCallTo.
7283   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7284     isTailCall = false;
7285 
7286   // Disable tail calls if there is an swifterror argument. Targets have not
7287   // been updated to support tail calls.
7288   if (TLI.supportSwiftError() && SwiftErrorVal)
7289     isTailCall = false;
7290 
7291   TargetLowering::CallLoweringInfo CLI(DAG);
7292   CLI.setDebugLoc(getCurSDLoc())
7293       .setChain(getRoot())
7294       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7295       .setTailCall(isTailCall)
7296       .setConvergent(CS.isConvergent());
7297   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7298 
7299   if (Result.first.getNode()) {
7300     const Instruction *Inst = CS.getInstruction();
7301     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7302     setValue(Inst, Result.first);
7303   }
7304 
7305   // The last element of CLI.InVals has the SDValue for swifterror return.
7306   // Here we copy it to a virtual register and update SwiftErrorMap for
7307   // book-keeping.
7308   if (SwiftErrorVal && TLI.supportSwiftError()) {
7309     // Get the last element of InVals.
7310     SDValue Src = CLI.InVals.back();
7311     Register VReg = SwiftError.getOrCreateVRegDefAt(
7312         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7313     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7314     DAG.setRoot(CopyNode);
7315   }
7316 }
7317 
7318 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7319                              SelectionDAGBuilder &Builder) {
7320   // Check to see if this load can be trivially constant folded, e.g. if the
7321   // input is from a string literal.
7322   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7323     // Cast pointer to the type we really want to load.
7324     Type *LoadTy =
7325         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7326     if (LoadVT.isVector())
7327       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7328 
7329     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7330                                          PointerType::getUnqual(LoadTy));
7331 
7332     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7333             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7334       return Builder.getValue(LoadCst);
7335   }
7336 
7337   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7338   // still constant memory, the input chain can be the entry node.
7339   SDValue Root;
7340   bool ConstantMemory = false;
7341 
7342   // Do not serialize (non-volatile) loads of constant memory with anything.
7343   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7344     Root = Builder.DAG.getEntryNode();
7345     ConstantMemory = true;
7346   } else {
7347     // Do not serialize non-volatile loads against each other.
7348     Root = Builder.DAG.getRoot();
7349   }
7350 
7351   SDValue Ptr = Builder.getValue(PtrVal);
7352   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7353                                         Ptr, MachinePointerInfo(PtrVal),
7354                                         /* Alignment = */ 1);
7355 
7356   if (!ConstantMemory)
7357     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7358   return LoadVal;
7359 }
7360 
7361 /// Record the value for an instruction that produces an integer result,
7362 /// converting the type where necessary.
7363 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7364                                                   SDValue Value,
7365                                                   bool IsSigned) {
7366   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7367                                                     I.getType(), true);
7368   if (IsSigned)
7369     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7370   else
7371     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7372   setValue(&I, Value);
7373 }
7374 
7375 /// See if we can lower a memcmp call into an optimized form. If so, return
7376 /// true and lower it. Otherwise return false, and it will be lowered like a
7377 /// normal call.
7378 /// The caller already checked that \p I calls the appropriate LibFunc with a
7379 /// correct prototype.
7380 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7381   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7382   const Value *Size = I.getArgOperand(2);
7383   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7384   if (CSize && CSize->getZExtValue() == 0) {
7385     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7386                                                           I.getType(), true);
7387     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7388     return true;
7389   }
7390 
7391   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7392   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7393       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7394       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7395   if (Res.first.getNode()) {
7396     processIntegerCallValue(I, Res.first, true);
7397     PendingLoads.push_back(Res.second);
7398     return true;
7399   }
7400 
7401   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7402   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7403   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7404     return false;
7405 
7406   // If the target has a fast compare for the given size, it will return a
7407   // preferred load type for that size. Require that the load VT is legal and
7408   // that the target supports unaligned loads of that type. Otherwise, return
7409   // INVALID.
7410   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7411     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7412     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7413     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7414       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7415       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7416       // TODO: Check alignment of src and dest ptrs.
7417       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7418       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7419       if (!TLI.isTypeLegal(LVT) ||
7420           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7421           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7422         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7423     }
7424 
7425     return LVT;
7426   };
7427 
7428   // This turns into unaligned loads. We only do this if the target natively
7429   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7430   // we'll only produce a small number of byte loads.
7431   MVT LoadVT;
7432   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7433   switch (NumBitsToCompare) {
7434   default:
7435     return false;
7436   case 16:
7437     LoadVT = MVT::i16;
7438     break;
7439   case 32:
7440     LoadVT = MVT::i32;
7441     break;
7442   case 64:
7443   case 128:
7444   case 256:
7445     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7446     break;
7447   }
7448 
7449   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7450     return false;
7451 
7452   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7453   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7454 
7455   // Bitcast to a wide integer type if the loads are vectors.
7456   if (LoadVT.isVector()) {
7457     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7458     LoadL = DAG.getBitcast(CmpVT, LoadL);
7459     LoadR = DAG.getBitcast(CmpVT, LoadR);
7460   }
7461 
7462   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7463   processIntegerCallValue(I, Cmp, false);
7464   return true;
7465 }
7466 
7467 /// See if we can lower a memchr call into an optimized form. If so, return
7468 /// true and lower it. Otherwise return false, and it will be lowered like a
7469 /// normal call.
7470 /// The caller already checked that \p I calls the appropriate LibFunc with a
7471 /// correct prototype.
7472 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7473   const Value *Src = I.getArgOperand(0);
7474   const Value *Char = I.getArgOperand(1);
7475   const Value *Length = I.getArgOperand(2);
7476 
7477   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7478   std::pair<SDValue, SDValue> Res =
7479     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7480                                 getValue(Src), getValue(Char), getValue(Length),
7481                                 MachinePointerInfo(Src));
7482   if (Res.first.getNode()) {
7483     setValue(&I, Res.first);
7484     PendingLoads.push_back(Res.second);
7485     return true;
7486   }
7487 
7488   return false;
7489 }
7490 
7491 /// See if we can lower a mempcpy call into an optimized form. If so, return
7492 /// true and lower it. Otherwise return false, and it will be lowered like a
7493 /// normal call.
7494 /// The caller already checked that \p I calls the appropriate LibFunc with a
7495 /// correct prototype.
7496 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7497   SDValue Dst = getValue(I.getArgOperand(0));
7498   SDValue Src = getValue(I.getArgOperand(1));
7499   SDValue Size = getValue(I.getArgOperand(2));
7500 
7501   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7502   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7503   // DAG::getMemcpy needs Alignment to be defined.
7504   Align Alignment = assumeAligned(std::min(DstAlign, SrcAlign));
7505 
7506   bool isVol = false;
7507   SDLoc sdl = getCurSDLoc();
7508 
7509   // In the mempcpy context we need to pass in a false value for isTailCall
7510   // because the return pointer needs to be adjusted by the size of
7511   // the copied memory.
7512   SDValue Root = isVol ? getRoot() : getMemoryRoot();
7513   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, isVol, false,
7514                              /*isTailCall=*/false,
7515                              MachinePointerInfo(I.getArgOperand(0)),
7516                              MachinePointerInfo(I.getArgOperand(1)));
7517   assert(MC.getNode() != nullptr &&
7518          "** memcpy should not be lowered as TailCall in mempcpy context **");
7519   DAG.setRoot(MC);
7520 
7521   // Check if Size needs to be truncated or extended.
7522   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7523 
7524   // Adjust return pointer to point just past the last dst byte.
7525   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7526                                     Dst, Size);
7527   setValue(&I, DstPlusSize);
7528   return true;
7529 }
7530 
7531 /// See if we can lower a strcpy call into an optimized form.  If so, return
7532 /// true and lower it, otherwise return false and it will be lowered like a
7533 /// normal call.
7534 /// The caller already checked that \p I calls the appropriate LibFunc with a
7535 /// correct prototype.
7536 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7537   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7538 
7539   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7540   std::pair<SDValue, SDValue> Res =
7541     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7542                                 getValue(Arg0), getValue(Arg1),
7543                                 MachinePointerInfo(Arg0),
7544                                 MachinePointerInfo(Arg1), isStpcpy);
7545   if (Res.first.getNode()) {
7546     setValue(&I, Res.first);
7547     DAG.setRoot(Res.second);
7548     return true;
7549   }
7550 
7551   return false;
7552 }
7553 
7554 /// See if we can lower a strcmp call into an optimized form.  If so, return
7555 /// true and lower it, otherwise return false and it will be lowered like a
7556 /// normal call.
7557 /// The caller already checked that \p I calls the appropriate LibFunc with a
7558 /// correct prototype.
7559 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7560   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7561 
7562   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7563   std::pair<SDValue, SDValue> Res =
7564     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7565                                 getValue(Arg0), getValue(Arg1),
7566                                 MachinePointerInfo(Arg0),
7567                                 MachinePointerInfo(Arg1));
7568   if (Res.first.getNode()) {
7569     processIntegerCallValue(I, Res.first, true);
7570     PendingLoads.push_back(Res.second);
7571     return true;
7572   }
7573 
7574   return false;
7575 }
7576 
7577 /// See if we can lower a strlen call into an optimized form.  If so, return
7578 /// true and lower it, otherwise return false and it will be lowered like a
7579 /// normal call.
7580 /// The caller already checked that \p I calls the appropriate LibFunc with a
7581 /// correct prototype.
7582 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7583   const Value *Arg0 = I.getArgOperand(0);
7584 
7585   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7586   std::pair<SDValue, SDValue> Res =
7587     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7588                                 getValue(Arg0), MachinePointerInfo(Arg0));
7589   if (Res.first.getNode()) {
7590     processIntegerCallValue(I, Res.first, false);
7591     PendingLoads.push_back(Res.second);
7592     return true;
7593   }
7594 
7595   return false;
7596 }
7597 
7598 /// See if we can lower a strnlen call into an optimized form.  If so, return
7599 /// true and lower it, otherwise return false and it will be lowered like a
7600 /// normal call.
7601 /// The caller already checked that \p I calls the appropriate LibFunc with a
7602 /// correct prototype.
7603 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7604   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7605 
7606   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7607   std::pair<SDValue, SDValue> Res =
7608     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7609                                  getValue(Arg0), getValue(Arg1),
7610                                  MachinePointerInfo(Arg0));
7611   if (Res.first.getNode()) {
7612     processIntegerCallValue(I, Res.first, false);
7613     PendingLoads.push_back(Res.second);
7614     return true;
7615   }
7616 
7617   return false;
7618 }
7619 
7620 /// See if we can lower a unary floating-point operation into an SDNode with
7621 /// the specified Opcode.  If so, return true and lower it, otherwise return
7622 /// false and it will be lowered like a normal call.
7623 /// The caller already checked that \p I calls the appropriate LibFunc with a
7624 /// correct prototype.
7625 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7626                                               unsigned Opcode) {
7627   // We already checked this call's prototype; verify it doesn't modify errno.
7628   if (!I.onlyReadsMemory())
7629     return false;
7630 
7631   SDValue Tmp = getValue(I.getArgOperand(0));
7632   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7633   return true;
7634 }
7635 
7636 /// See if we can lower a binary floating-point operation into an SDNode with
7637 /// the specified Opcode. If so, return true and lower it. Otherwise return
7638 /// false, and it will be lowered like a normal call.
7639 /// The caller already checked that \p I calls the appropriate LibFunc with a
7640 /// correct prototype.
7641 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7642                                                unsigned Opcode) {
7643   // We already checked this call's prototype; verify it doesn't modify errno.
7644   if (!I.onlyReadsMemory())
7645     return false;
7646 
7647   SDValue Tmp0 = getValue(I.getArgOperand(0));
7648   SDValue Tmp1 = getValue(I.getArgOperand(1));
7649   EVT VT = Tmp0.getValueType();
7650   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7651   return true;
7652 }
7653 
7654 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7655   // Handle inline assembly differently.
7656   if (isa<InlineAsm>(I.getCalledValue())) {
7657     visitInlineAsm(&I);
7658     return;
7659   }
7660 
7661   if (Function *F = I.getCalledFunction()) {
7662     if (F->isDeclaration()) {
7663       // Is this an LLVM intrinsic or a target-specific intrinsic?
7664       unsigned IID = F->getIntrinsicID();
7665       if (!IID)
7666         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7667           IID = II->getIntrinsicID(F);
7668 
7669       if (IID) {
7670         visitIntrinsicCall(I, IID);
7671         return;
7672       }
7673     }
7674 
7675     // Check for well-known libc/libm calls.  If the function is internal, it
7676     // can't be a library call.  Don't do the check if marked as nobuiltin for
7677     // some reason or the call site requires strict floating point semantics.
7678     LibFunc Func;
7679     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7680         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7681         LibInfo->hasOptimizedCodeGen(Func)) {
7682       switch (Func) {
7683       default: break;
7684       case LibFunc_copysign:
7685       case LibFunc_copysignf:
7686       case LibFunc_copysignl:
7687         // We already checked this call's prototype; verify it doesn't modify
7688         // errno.
7689         if (I.onlyReadsMemory()) {
7690           SDValue LHS = getValue(I.getArgOperand(0));
7691           SDValue RHS = getValue(I.getArgOperand(1));
7692           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7693                                    LHS.getValueType(), LHS, RHS));
7694           return;
7695         }
7696         break;
7697       case LibFunc_fabs:
7698       case LibFunc_fabsf:
7699       case LibFunc_fabsl:
7700         if (visitUnaryFloatCall(I, ISD::FABS))
7701           return;
7702         break;
7703       case LibFunc_fmin:
7704       case LibFunc_fminf:
7705       case LibFunc_fminl:
7706         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7707           return;
7708         break;
7709       case LibFunc_fmax:
7710       case LibFunc_fmaxf:
7711       case LibFunc_fmaxl:
7712         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7713           return;
7714         break;
7715       case LibFunc_sin:
7716       case LibFunc_sinf:
7717       case LibFunc_sinl:
7718         if (visitUnaryFloatCall(I, ISD::FSIN))
7719           return;
7720         break;
7721       case LibFunc_cos:
7722       case LibFunc_cosf:
7723       case LibFunc_cosl:
7724         if (visitUnaryFloatCall(I, ISD::FCOS))
7725           return;
7726         break;
7727       case LibFunc_sqrt:
7728       case LibFunc_sqrtf:
7729       case LibFunc_sqrtl:
7730       case LibFunc_sqrt_finite:
7731       case LibFunc_sqrtf_finite:
7732       case LibFunc_sqrtl_finite:
7733         if (visitUnaryFloatCall(I, ISD::FSQRT))
7734           return;
7735         break;
7736       case LibFunc_floor:
7737       case LibFunc_floorf:
7738       case LibFunc_floorl:
7739         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7740           return;
7741         break;
7742       case LibFunc_nearbyint:
7743       case LibFunc_nearbyintf:
7744       case LibFunc_nearbyintl:
7745         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7746           return;
7747         break;
7748       case LibFunc_ceil:
7749       case LibFunc_ceilf:
7750       case LibFunc_ceill:
7751         if (visitUnaryFloatCall(I, ISD::FCEIL))
7752           return;
7753         break;
7754       case LibFunc_rint:
7755       case LibFunc_rintf:
7756       case LibFunc_rintl:
7757         if (visitUnaryFloatCall(I, ISD::FRINT))
7758           return;
7759         break;
7760       case LibFunc_round:
7761       case LibFunc_roundf:
7762       case LibFunc_roundl:
7763         if (visitUnaryFloatCall(I, ISD::FROUND))
7764           return;
7765         break;
7766       case LibFunc_trunc:
7767       case LibFunc_truncf:
7768       case LibFunc_truncl:
7769         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7770           return;
7771         break;
7772       case LibFunc_log2:
7773       case LibFunc_log2f:
7774       case LibFunc_log2l:
7775         if (visitUnaryFloatCall(I, ISD::FLOG2))
7776           return;
7777         break;
7778       case LibFunc_exp2:
7779       case LibFunc_exp2f:
7780       case LibFunc_exp2l:
7781         if (visitUnaryFloatCall(I, ISD::FEXP2))
7782           return;
7783         break;
7784       case LibFunc_memcmp:
7785         if (visitMemCmpCall(I))
7786           return;
7787         break;
7788       case LibFunc_mempcpy:
7789         if (visitMemPCpyCall(I))
7790           return;
7791         break;
7792       case LibFunc_memchr:
7793         if (visitMemChrCall(I))
7794           return;
7795         break;
7796       case LibFunc_strcpy:
7797         if (visitStrCpyCall(I, false))
7798           return;
7799         break;
7800       case LibFunc_stpcpy:
7801         if (visitStrCpyCall(I, true))
7802           return;
7803         break;
7804       case LibFunc_strcmp:
7805         if (visitStrCmpCall(I))
7806           return;
7807         break;
7808       case LibFunc_strlen:
7809         if (visitStrLenCall(I))
7810           return;
7811         break;
7812       case LibFunc_strnlen:
7813         if (visitStrNLenCall(I))
7814           return;
7815         break;
7816       }
7817     }
7818   }
7819 
7820   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7821   // have to do anything here to lower funclet bundles.
7822   // CFGuardTarget bundles are lowered in LowerCallTo.
7823   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7824                                         LLVMContext::OB_funclet,
7825                                         LLVMContext::OB_cfguardtarget}) &&
7826          "Cannot lower calls with arbitrary operand bundles!");
7827 
7828   SDValue Callee = getValue(I.getCalledValue());
7829 
7830   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7831     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7832   else
7833     // Check if we can potentially perform a tail call. More detailed checking
7834     // is be done within LowerCallTo, after more information about the call is
7835     // known.
7836     LowerCallTo(&I, Callee, I.isTailCall());
7837 }
7838 
7839 namespace {
7840 
7841 /// AsmOperandInfo - This contains information for each constraint that we are
7842 /// lowering.
7843 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7844 public:
7845   /// CallOperand - If this is the result output operand or a clobber
7846   /// this is null, otherwise it is the incoming operand to the CallInst.
7847   /// This gets modified as the asm is processed.
7848   SDValue CallOperand;
7849 
7850   /// AssignedRegs - If this is a register or register class operand, this
7851   /// contains the set of register corresponding to the operand.
7852   RegsForValue AssignedRegs;
7853 
7854   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7855     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7856   }
7857 
7858   /// Whether or not this operand accesses memory
7859   bool hasMemory(const TargetLowering &TLI) const {
7860     // Indirect operand accesses access memory.
7861     if (isIndirect)
7862       return true;
7863 
7864     for (const auto &Code : Codes)
7865       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7866         return true;
7867 
7868     return false;
7869   }
7870 
7871   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7872   /// corresponds to.  If there is no Value* for this operand, it returns
7873   /// MVT::Other.
7874   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7875                            const DataLayout &DL) const {
7876     if (!CallOperandVal) return MVT::Other;
7877 
7878     if (isa<BasicBlock>(CallOperandVal))
7879       return TLI.getPointerTy(DL);
7880 
7881     llvm::Type *OpTy = CallOperandVal->getType();
7882 
7883     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7884     // If this is an indirect operand, the operand is a pointer to the
7885     // accessed type.
7886     if (isIndirect) {
7887       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7888       if (!PtrTy)
7889         report_fatal_error("Indirect operand for inline asm not a pointer!");
7890       OpTy = PtrTy->getElementType();
7891     }
7892 
7893     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7894     if (StructType *STy = dyn_cast<StructType>(OpTy))
7895       if (STy->getNumElements() == 1)
7896         OpTy = STy->getElementType(0);
7897 
7898     // If OpTy is not a single value, it may be a struct/union that we
7899     // can tile with integers.
7900     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7901       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7902       switch (BitSize) {
7903       default: break;
7904       case 1:
7905       case 8:
7906       case 16:
7907       case 32:
7908       case 64:
7909       case 128:
7910         OpTy = IntegerType::get(Context, BitSize);
7911         break;
7912       }
7913     }
7914 
7915     return TLI.getValueType(DL, OpTy, true);
7916   }
7917 };
7918 
7919 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7920 
7921 } // end anonymous namespace
7922 
7923 /// Make sure that the output operand \p OpInfo and its corresponding input
7924 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7925 /// out).
7926 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7927                                SDISelAsmOperandInfo &MatchingOpInfo,
7928                                SelectionDAG &DAG) {
7929   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7930     return;
7931 
7932   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7933   const auto &TLI = DAG.getTargetLoweringInfo();
7934 
7935   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7936       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7937                                        OpInfo.ConstraintVT);
7938   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7939       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7940                                        MatchingOpInfo.ConstraintVT);
7941   if ((OpInfo.ConstraintVT.isInteger() !=
7942        MatchingOpInfo.ConstraintVT.isInteger()) ||
7943       (MatchRC.second != InputRC.second)) {
7944     // FIXME: error out in a more elegant fashion
7945     report_fatal_error("Unsupported asm: input constraint"
7946                        " with a matching output constraint of"
7947                        " incompatible type!");
7948   }
7949   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7950 }
7951 
7952 /// Get a direct memory input to behave well as an indirect operand.
7953 /// This may introduce stores, hence the need for a \p Chain.
7954 /// \return The (possibly updated) chain.
7955 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7956                                         SDISelAsmOperandInfo &OpInfo,
7957                                         SelectionDAG &DAG) {
7958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7959 
7960   // If we don't have an indirect input, put it in the constpool if we can,
7961   // otherwise spill it to a stack slot.
7962   // TODO: This isn't quite right. We need to handle these according to
7963   // the addressing mode that the constraint wants. Also, this may take
7964   // an additional register for the computation and we don't want that
7965   // either.
7966 
7967   // If the operand is a float, integer, or vector constant, spill to a
7968   // constant pool entry to get its address.
7969   const Value *OpVal = OpInfo.CallOperandVal;
7970   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7971       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7972     OpInfo.CallOperand = DAG.getConstantPool(
7973         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7974     return Chain;
7975   }
7976 
7977   // Otherwise, create a stack slot and emit a store to it before the asm.
7978   Type *Ty = OpVal->getType();
7979   auto &DL = DAG.getDataLayout();
7980   uint64_t TySize = DL.getTypeAllocSize(Ty);
7981   unsigned Align = DL.getPrefTypeAlignment(Ty);
7982   MachineFunction &MF = DAG.getMachineFunction();
7983   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7984   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7985   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7986                             MachinePointerInfo::getFixedStack(MF, SSFI),
7987                             TLI.getMemValueType(DL, Ty));
7988   OpInfo.CallOperand = StackSlot;
7989 
7990   return Chain;
7991 }
7992 
7993 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7994 /// specified operand.  We prefer to assign virtual registers, to allow the
7995 /// register allocator to handle the assignment process.  However, if the asm
7996 /// uses features that we can't model on machineinstrs, we have SDISel do the
7997 /// allocation.  This produces generally horrible, but correct, code.
7998 ///
7999 ///   OpInfo describes the operand
8000 ///   RefOpInfo describes the matching operand if any, the operand otherwise
8001 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
8002                                  SDISelAsmOperandInfo &OpInfo,
8003                                  SDISelAsmOperandInfo &RefOpInfo) {
8004   LLVMContext &Context = *DAG.getContext();
8005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8006 
8007   MachineFunction &MF = DAG.getMachineFunction();
8008   SmallVector<unsigned, 4> Regs;
8009   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
8010 
8011   // No work to do for memory operations.
8012   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
8013     return;
8014 
8015   // If this is a constraint for a single physreg, or a constraint for a
8016   // register class, find it.
8017   unsigned AssignedReg;
8018   const TargetRegisterClass *RC;
8019   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
8020       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
8021   // RC is unset only on failure. Return immediately.
8022   if (!RC)
8023     return;
8024 
8025   // Get the actual register value type.  This is important, because the user
8026   // may have asked for (e.g.) the AX register in i32 type.  We need to
8027   // remember that AX is actually i16 to get the right extension.
8028   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
8029 
8030   if (OpInfo.ConstraintVT != MVT::Other) {
8031     // If this is an FP operand in an integer register (or visa versa), or more
8032     // generally if the operand value disagrees with the register class we plan
8033     // to stick it in, fix the operand type.
8034     //
8035     // If this is an input value, the bitcast to the new type is done now.
8036     // Bitcast for output value is done at the end of visitInlineAsm().
8037     if ((OpInfo.Type == InlineAsm::isOutput ||
8038          OpInfo.Type == InlineAsm::isInput) &&
8039         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
8040       // Try to convert to the first EVT that the reg class contains.  If the
8041       // types are identical size, use a bitcast to convert (e.g. two differing
8042       // vector types).  Note: output bitcast is done at the end of
8043       // visitInlineAsm().
8044       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
8045         // Exclude indirect inputs while they are unsupported because the code
8046         // to perform the load is missing and thus OpInfo.CallOperand still
8047         // refers to the input address rather than the pointed-to value.
8048         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
8049           OpInfo.CallOperand =
8050               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
8051         OpInfo.ConstraintVT = RegVT;
8052         // If the operand is an FP value and we want it in integer registers,
8053         // use the corresponding integer type. This turns an f64 value into
8054         // i64, which can be passed with two i32 values on a 32-bit machine.
8055       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
8056         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
8057         if (OpInfo.Type == InlineAsm::isInput)
8058           OpInfo.CallOperand =
8059               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
8060         OpInfo.ConstraintVT = VT;
8061       }
8062     }
8063   }
8064 
8065   // No need to allocate a matching input constraint since the constraint it's
8066   // matching to has already been allocated.
8067   if (OpInfo.isMatchingInputConstraint())
8068     return;
8069 
8070   EVT ValueVT = OpInfo.ConstraintVT;
8071   if (OpInfo.ConstraintVT == MVT::Other)
8072     ValueVT = RegVT;
8073 
8074   // Initialize NumRegs.
8075   unsigned NumRegs = 1;
8076   if (OpInfo.ConstraintVT != MVT::Other)
8077     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
8078 
8079   // If this is a constraint for a specific physical register, like {r17},
8080   // assign it now.
8081 
8082   // If this associated to a specific register, initialize iterator to correct
8083   // place. If virtual, make sure we have enough registers
8084 
8085   // Initialize iterator if necessary
8086   TargetRegisterClass::iterator I = RC->begin();
8087   MachineRegisterInfo &RegInfo = MF.getRegInfo();
8088 
8089   // Do not check for single registers.
8090   if (AssignedReg) {
8091       for (; *I != AssignedReg; ++I)
8092         assert(I != RC->end() && "AssignedReg should be member of RC");
8093   }
8094 
8095   for (; NumRegs; --NumRegs, ++I) {
8096     assert(I != RC->end() && "Ran out of registers to allocate!");
8097     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
8098     Regs.push_back(R);
8099   }
8100 
8101   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
8102 }
8103 
8104 static unsigned
8105 findMatchingInlineAsmOperand(unsigned OperandNo,
8106                              const std::vector<SDValue> &AsmNodeOperands) {
8107   // Scan until we find the definition we already emitted of this operand.
8108   unsigned CurOp = InlineAsm::Op_FirstOperand;
8109   for (; OperandNo; --OperandNo) {
8110     // Advance to the next operand.
8111     unsigned OpFlag =
8112         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8113     assert((InlineAsm::isRegDefKind(OpFlag) ||
8114             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
8115             InlineAsm::isMemKind(OpFlag)) &&
8116            "Skipped past definitions?");
8117     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
8118   }
8119   return CurOp;
8120 }
8121 
8122 namespace {
8123 
8124 class ExtraFlags {
8125   unsigned Flags = 0;
8126 
8127 public:
8128   explicit ExtraFlags(ImmutableCallSite CS) {
8129     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8130     if (IA->hasSideEffects())
8131       Flags |= InlineAsm::Extra_HasSideEffects;
8132     if (IA->isAlignStack())
8133       Flags |= InlineAsm::Extra_IsAlignStack;
8134     if (CS.isConvergent())
8135       Flags |= InlineAsm::Extra_IsConvergent;
8136     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
8137   }
8138 
8139   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
8140     // Ideally, we would only check against memory constraints.  However, the
8141     // meaning of an Other constraint can be target-specific and we can't easily
8142     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
8143     // for Other constraints as well.
8144     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8145         OpInfo.ConstraintType == TargetLowering::C_Other) {
8146       if (OpInfo.Type == InlineAsm::isInput)
8147         Flags |= InlineAsm::Extra_MayLoad;
8148       else if (OpInfo.Type == InlineAsm::isOutput)
8149         Flags |= InlineAsm::Extra_MayStore;
8150       else if (OpInfo.Type == InlineAsm::isClobber)
8151         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
8152     }
8153   }
8154 
8155   unsigned get() const { return Flags; }
8156 };
8157 
8158 } // end anonymous namespace
8159 
8160 /// visitInlineAsm - Handle a call to an InlineAsm object.
8161 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
8162   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
8163 
8164   /// ConstraintOperands - Information about all of the constraints.
8165   SDISelAsmOperandInfoVector ConstraintOperands;
8166 
8167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8168   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
8169       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
8170 
8171   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
8172   // AsmDialect, MayLoad, MayStore).
8173   bool HasSideEffect = IA->hasSideEffects();
8174   ExtraFlags ExtraInfo(CS);
8175 
8176   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
8177   unsigned ResNo = 0;   // ResNo - The result number of the next output.
8178   for (auto &T : TargetConstraints) {
8179     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
8180     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
8181 
8182     // Compute the value type for each operand.
8183     if (OpInfo.Type == InlineAsm::isInput ||
8184         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
8185       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8186 
8187       // Process the call argument. BasicBlocks are labels, currently appearing
8188       // only in asm's.
8189       const Instruction *I = CS.getInstruction();
8190       if (isa<CallBrInst>(I) &&
8191           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8192                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8193         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8194         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8195         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8196       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8197         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8198       } else {
8199         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8200       }
8201 
8202       OpInfo.ConstraintVT =
8203           OpInfo
8204               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8205               .getSimpleVT();
8206     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8207       // The return value of the call is this value.  As such, there is no
8208       // corresponding argument.
8209       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8210       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8211         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8212             DAG.getDataLayout(), STy->getElementType(ResNo));
8213       } else {
8214         assert(ResNo == 0 && "Asm only has one result!");
8215         OpInfo.ConstraintVT =
8216             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8217       }
8218       ++ResNo;
8219     } else {
8220       OpInfo.ConstraintVT = MVT::Other;
8221     }
8222 
8223     if (!HasSideEffect)
8224       HasSideEffect = OpInfo.hasMemory(TLI);
8225 
8226     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8227     // FIXME: Could we compute this on OpInfo rather than T?
8228 
8229     // Compute the constraint code and ConstraintType to use.
8230     TLI.ComputeConstraintToUse(T, SDValue());
8231 
8232     if (T.ConstraintType == TargetLowering::C_Immediate &&
8233         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8234       // We've delayed emitting a diagnostic like the "n" constraint because
8235       // inlining could cause an integer showing up.
8236       return emitInlineAsmError(
8237           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8238                   "integer constant expression");
8239 
8240     ExtraInfo.update(T);
8241   }
8242 
8243 
8244   // We won't need to flush pending loads if this asm doesn't touch
8245   // memory and is nonvolatile.
8246   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8247 
8248   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8249   if (IsCallBr) {
8250     // If this is a callbr we need to flush pending exports since inlineasm_br
8251     // is a terminator. We need to do this before nodes are glued to
8252     // the inlineasm_br node.
8253     Chain = getControlRoot();
8254   }
8255 
8256   // Second pass over the constraints: compute which constraint option to use.
8257   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8258     // If this is an output operand with a matching input operand, look up the
8259     // matching input. If their types mismatch, e.g. one is an integer, the
8260     // other is floating point, or their sizes are different, flag it as an
8261     // error.
8262     if (OpInfo.hasMatchingInput()) {
8263       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8264       patchMatchingInput(OpInfo, Input, DAG);
8265     }
8266 
8267     // Compute the constraint code and ConstraintType to use.
8268     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8269 
8270     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8271         OpInfo.Type == InlineAsm::isClobber)
8272       continue;
8273 
8274     // If this is a memory input, and if the operand is not indirect, do what we
8275     // need to provide an address for the memory input.
8276     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8277         !OpInfo.isIndirect) {
8278       assert((OpInfo.isMultipleAlternative ||
8279               (OpInfo.Type == InlineAsm::isInput)) &&
8280              "Can only indirectify direct input operands!");
8281 
8282       // Memory operands really want the address of the value.
8283       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8284 
8285       // There is no longer a Value* corresponding to this operand.
8286       OpInfo.CallOperandVal = nullptr;
8287 
8288       // It is now an indirect operand.
8289       OpInfo.isIndirect = true;
8290     }
8291 
8292   }
8293 
8294   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8295   std::vector<SDValue> AsmNodeOperands;
8296   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8297   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8298       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8299 
8300   // If we have a !srcloc metadata node associated with it, we want to attach
8301   // this to the ultimately generated inline asm machineinstr.  To do this, we
8302   // pass in the third operand as this (potentially null) inline asm MDNode.
8303   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8304   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8305 
8306   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8307   // bits as operand 3.
8308   AsmNodeOperands.push_back(DAG.getTargetConstant(
8309       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8310 
8311   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8312   // this, assign virtual and physical registers for inputs and otput.
8313   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8314     // Assign Registers.
8315     SDISelAsmOperandInfo &RefOpInfo =
8316         OpInfo.isMatchingInputConstraint()
8317             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8318             : OpInfo;
8319     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8320 
8321     switch (OpInfo.Type) {
8322     case InlineAsm::isOutput:
8323       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8324         unsigned ConstraintID =
8325             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8326         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8327                "Failed to convert memory constraint code to constraint id.");
8328 
8329         // Add information to the INLINEASM node to know about this output.
8330         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8331         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8332         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8333                                                         MVT::i32));
8334         AsmNodeOperands.push_back(OpInfo.CallOperand);
8335       } else {
8336         // Otherwise, this outputs to a register (directly for C_Register /
8337         // C_RegisterClass, and a target-defined fashion for
8338         // C_Immediate/C_Other). Find a register that we can use.
8339         if (OpInfo.AssignedRegs.Regs.empty()) {
8340           emitInlineAsmError(
8341               CS, "couldn't allocate output register for constraint '" +
8342                       Twine(OpInfo.ConstraintCode) + "'");
8343           return;
8344         }
8345 
8346         // Add information to the INLINEASM node to know that this register is
8347         // set.
8348         OpInfo.AssignedRegs.AddInlineAsmOperands(
8349             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8350                                   : InlineAsm::Kind_RegDef,
8351             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8352       }
8353       break;
8354 
8355     case InlineAsm::isInput: {
8356       SDValue InOperandVal = OpInfo.CallOperand;
8357 
8358       if (OpInfo.isMatchingInputConstraint()) {
8359         // If this is required to match an output register we have already set,
8360         // just use its register.
8361         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8362                                                   AsmNodeOperands);
8363         unsigned OpFlag =
8364           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8365         if (InlineAsm::isRegDefKind(OpFlag) ||
8366             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8367           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8368           if (OpInfo.isIndirect) {
8369             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8370             emitInlineAsmError(CS, "inline asm not supported yet:"
8371                                    " don't know how to handle tied "
8372                                    "indirect register inputs");
8373             return;
8374           }
8375 
8376           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8377           SmallVector<unsigned, 4> Regs;
8378 
8379           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8380             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8381             MachineRegisterInfo &RegInfo =
8382                 DAG.getMachineFunction().getRegInfo();
8383             for (unsigned i = 0; i != NumRegs; ++i)
8384               Regs.push_back(RegInfo.createVirtualRegister(RC));
8385           } else {
8386             emitInlineAsmError(CS, "inline asm error: This value type register "
8387                                    "class is not natively supported!");
8388             return;
8389           }
8390 
8391           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8392 
8393           SDLoc dl = getCurSDLoc();
8394           // Use the produced MatchedRegs object to
8395           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8396                                     CS.getInstruction());
8397           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8398                                            true, OpInfo.getMatchedOperand(), dl,
8399                                            DAG, AsmNodeOperands);
8400           break;
8401         }
8402 
8403         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8404         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8405                "Unexpected number of operands");
8406         // Add information to the INLINEASM node to know about this input.
8407         // See InlineAsm.h isUseOperandTiedToDef.
8408         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8409         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8410                                                     OpInfo.getMatchedOperand());
8411         AsmNodeOperands.push_back(DAG.getTargetConstant(
8412             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8413         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8414         break;
8415       }
8416 
8417       // Treat indirect 'X' constraint as memory.
8418       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8419           OpInfo.isIndirect)
8420         OpInfo.ConstraintType = TargetLowering::C_Memory;
8421 
8422       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8423           OpInfo.ConstraintType == TargetLowering::C_Other) {
8424         std::vector<SDValue> Ops;
8425         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8426                                           Ops, DAG);
8427         if (Ops.empty()) {
8428           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8429             if (isa<ConstantSDNode>(InOperandVal)) {
8430               emitInlineAsmError(CS, "value out of range for constraint '" +
8431                                  Twine(OpInfo.ConstraintCode) + "'");
8432               return;
8433             }
8434 
8435           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8436                                      Twine(OpInfo.ConstraintCode) + "'");
8437           return;
8438         }
8439 
8440         // Add information to the INLINEASM node to know about this input.
8441         unsigned ResOpType =
8442           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8443         AsmNodeOperands.push_back(DAG.getTargetConstant(
8444             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8445         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8446         break;
8447       }
8448 
8449       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8450         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8451         assert(InOperandVal.getValueType() ==
8452                    TLI.getPointerTy(DAG.getDataLayout()) &&
8453                "Memory operands expect pointer values");
8454 
8455         unsigned ConstraintID =
8456             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8457         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8458                "Failed to convert memory constraint code to constraint id.");
8459 
8460         // Add information to the INLINEASM node to know about this input.
8461         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8462         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8463         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8464                                                         getCurSDLoc(),
8465                                                         MVT::i32));
8466         AsmNodeOperands.push_back(InOperandVal);
8467         break;
8468       }
8469 
8470       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8471               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8472              "Unknown constraint type!");
8473 
8474       // TODO: Support this.
8475       if (OpInfo.isIndirect) {
8476         emitInlineAsmError(
8477             CS, "Don't know how to handle indirect register inputs yet "
8478                 "for constraint '" +
8479                     Twine(OpInfo.ConstraintCode) + "'");
8480         return;
8481       }
8482 
8483       // Copy the input into the appropriate registers.
8484       if (OpInfo.AssignedRegs.Regs.empty()) {
8485         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8486                                    Twine(OpInfo.ConstraintCode) + "'");
8487         return;
8488       }
8489 
8490       SDLoc dl = getCurSDLoc();
8491 
8492       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8493                                         Chain, &Flag, CS.getInstruction());
8494 
8495       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8496                                                dl, DAG, AsmNodeOperands);
8497       break;
8498     }
8499     case InlineAsm::isClobber:
8500       // Add the clobbered value to the operand list, so that the register
8501       // allocator is aware that the physreg got clobbered.
8502       if (!OpInfo.AssignedRegs.Regs.empty())
8503         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8504                                                  false, 0, getCurSDLoc(), DAG,
8505                                                  AsmNodeOperands);
8506       break;
8507     }
8508   }
8509 
8510   // Finish up input operands.  Set the input chain and add the flag last.
8511   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8512   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8513 
8514   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8515   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8516                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8517   Flag = Chain.getValue(1);
8518 
8519   // Do additional work to generate outputs.
8520 
8521   SmallVector<EVT, 1> ResultVTs;
8522   SmallVector<SDValue, 1> ResultValues;
8523   SmallVector<SDValue, 8> OutChains;
8524 
8525   llvm::Type *CSResultType = CS.getType();
8526   ArrayRef<Type *> ResultTypes;
8527   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8528     ResultTypes = StructResult->elements();
8529   else if (!CSResultType->isVoidTy())
8530     ResultTypes = makeArrayRef(CSResultType);
8531 
8532   auto CurResultType = ResultTypes.begin();
8533   auto handleRegAssign = [&](SDValue V) {
8534     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8535     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8536     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8537     ++CurResultType;
8538     // If the type of the inline asm call site return value is different but has
8539     // same size as the type of the asm output bitcast it.  One example of this
8540     // is for vectors with different width / number of elements.  This can
8541     // happen for register classes that can contain multiple different value
8542     // types.  The preg or vreg allocated may not have the same VT as was
8543     // expected.
8544     //
8545     // This can also happen for a return value that disagrees with the register
8546     // class it is put in, eg. a double in a general-purpose register on a
8547     // 32-bit machine.
8548     if (ResultVT != V.getValueType() &&
8549         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8550       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8551     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8552              V.getValueType().isInteger()) {
8553       // If a result value was tied to an input value, the computed result
8554       // may have a wider width than the expected result.  Extract the
8555       // relevant portion.
8556       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8557     }
8558     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8559     ResultVTs.push_back(ResultVT);
8560     ResultValues.push_back(V);
8561   };
8562 
8563   // Deal with output operands.
8564   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8565     if (OpInfo.Type == InlineAsm::isOutput) {
8566       SDValue Val;
8567       // Skip trivial output operands.
8568       if (OpInfo.AssignedRegs.Regs.empty())
8569         continue;
8570 
8571       switch (OpInfo.ConstraintType) {
8572       case TargetLowering::C_Register:
8573       case TargetLowering::C_RegisterClass:
8574         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8575             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8576         break;
8577       case TargetLowering::C_Immediate:
8578       case TargetLowering::C_Other:
8579         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8580                                               OpInfo, DAG);
8581         break;
8582       case TargetLowering::C_Memory:
8583         break; // Already handled.
8584       case TargetLowering::C_Unknown:
8585         assert(false && "Unexpected unknown constraint");
8586       }
8587 
8588       // Indirect output manifest as stores. Record output chains.
8589       if (OpInfo.isIndirect) {
8590         const Value *Ptr = OpInfo.CallOperandVal;
8591         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8592         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8593                                      MachinePointerInfo(Ptr));
8594         OutChains.push_back(Store);
8595       } else {
8596         // generate CopyFromRegs to associated registers.
8597         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8598         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8599           for (const SDValue &V : Val->op_values())
8600             handleRegAssign(V);
8601         } else
8602           handleRegAssign(Val);
8603       }
8604     }
8605   }
8606 
8607   // Set results.
8608   if (!ResultValues.empty()) {
8609     assert(CurResultType == ResultTypes.end() &&
8610            "Mismatch in number of ResultTypes");
8611     assert(ResultValues.size() == ResultTypes.size() &&
8612            "Mismatch in number of output operands in asm result");
8613 
8614     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8615                             DAG.getVTList(ResultVTs), ResultValues);
8616     setValue(CS.getInstruction(), V);
8617   }
8618 
8619   // Collect store chains.
8620   if (!OutChains.empty())
8621     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8622 
8623   // Only Update Root if inline assembly has a memory effect.
8624   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8625     DAG.setRoot(Chain);
8626 }
8627 
8628 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8629                                              const Twine &Message) {
8630   LLVMContext &Ctx = *DAG.getContext();
8631   Ctx.emitError(CS.getInstruction(), Message);
8632 
8633   // Make sure we leave the DAG in a valid state
8634   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8635   SmallVector<EVT, 1> ValueVTs;
8636   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8637 
8638   if (ValueVTs.empty())
8639     return;
8640 
8641   SmallVector<SDValue, 1> Ops;
8642   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8643     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8644 
8645   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8646 }
8647 
8648 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8649   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8650                           MVT::Other, getRoot(),
8651                           getValue(I.getArgOperand(0)),
8652                           DAG.getSrcValue(I.getArgOperand(0))));
8653 }
8654 
8655 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8657   const DataLayout &DL = DAG.getDataLayout();
8658   SDValue V = DAG.getVAArg(
8659       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8660       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8661       DL.getABITypeAlignment(I.getType()));
8662   DAG.setRoot(V.getValue(1));
8663 
8664   if (I.getType()->isPointerTy())
8665     V = DAG.getPtrExtOrTrunc(
8666         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8667   setValue(&I, V);
8668 }
8669 
8670 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8671   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8672                           MVT::Other, getRoot(),
8673                           getValue(I.getArgOperand(0)),
8674                           DAG.getSrcValue(I.getArgOperand(0))));
8675 }
8676 
8677 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8678   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8679                           MVT::Other, getRoot(),
8680                           getValue(I.getArgOperand(0)),
8681                           getValue(I.getArgOperand(1)),
8682                           DAG.getSrcValue(I.getArgOperand(0)),
8683                           DAG.getSrcValue(I.getArgOperand(1))));
8684 }
8685 
8686 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8687                                                     const Instruction &I,
8688                                                     SDValue Op) {
8689   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8690   if (!Range)
8691     return Op;
8692 
8693   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8694   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8695     return Op;
8696 
8697   APInt Lo = CR.getUnsignedMin();
8698   if (!Lo.isMinValue())
8699     return Op;
8700 
8701   APInt Hi = CR.getUnsignedMax();
8702   unsigned Bits = std::max(Hi.getActiveBits(),
8703                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8704 
8705   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8706 
8707   SDLoc SL = getCurSDLoc();
8708 
8709   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8710                              DAG.getValueType(SmallVT));
8711   unsigned NumVals = Op.getNode()->getNumValues();
8712   if (NumVals == 1)
8713     return ZExt;
8714 
8715   SmallVector<SDValue, 4> Ops;
8716 
8717   Ops.push_back(ZExt);
8718   for (unsigned I = 1; I != NumVals; ++I)
8719     Ops.push_back(Op.getValue(I));
8720 
8721   return DAG.getMergeValues(Ops, SL);
8722 }
8723 
8724 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8725 /// the call being lowered.
8726 ///
8727 /// This is a helper for lowering intrinsics that follow a target calling
8728 /// convention or require stack pointer adjustment. Only a subset of the
8729 /// intrinsic's operands need to participate in the calling convention.
8730 void SelectionDAGBuilder::populateCallLoweringInfo(
8731     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8732     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8733     bool IsPatchPoint) {
8734   TargetLowering::ArgListTy Args;
8735   Args.reserve(NumArgs);
8736 
8737   // Populate the argument list.
8738   // Attributes for args start at offset 1, after the return attribute.
8739   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8740        ArgI != ArgE; ++ArgI) {
8741     const Value *V = Call->getOperand(ArgI);
8742 
8743     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8744 
8745     TargetLowering::ArgListEntry Entry;
8746     Entry.Node = getValue(V);
8747     Entry.Ty = V->getType();
8748     Entry.setAttributes(Call, ArgI);
8749     Args.push_back(Entry);
8750   }
8751 
8752   CLI.setDebugLoc(getCurSDLoc())
8753       .setChain(getRoot())
8754       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8755       .setDiscardResult(Call->use_empty())
8756       .setIsPatchPoint(IsPatchPoint);
8757 }
8758 
8759 /// Add a stack map intrinsic call's live variable operands to a stackmap
8760 /// or patchpoint target node's operand list.
8761 ///
8762 /// Constants are converted to TargetConstants purely as an optimization to
8763 /// avoid constant materialization and register allocation.
8764 ///
8765 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8766 /// generate addess computation nodes, and so FinalizeISel can convert the
8767 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8768 /// address materialization and register allocation, but may also be required
8769 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8770 /// alloca in the entry block, then the runtime may assume that the alloca's
8771 /// StackMap location can be read immediately after compilation and that the
8772 /// location is valid at any point during execution (this is similar to the
8773 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8774 /// only available in a register, then the runtime would need to trap when
8775 /// execution reaches the StackMap in order to read the alloca's location.
8776 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8777                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8778                                 SelectionDAGBuilder &Builder) {
8779   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8780     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8781     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8782       Ops.push_back(
8783         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8784       Ops.push_back(
8785         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8786     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8787       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8788       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8789           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8790     } else
8791       Ops.push_back(OpVal);
8792   }
8793 }
8794 
8795 /// Lower llvm.experimental.stackmap directly to its target opcode.
8796 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8797   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8798   //                                  [live variables...])
8799 
8800   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8801 
8802   SDValue Chain, InFlag, Callee, NullPtr;
8803   SmallVector<SDValue, 32> Ops;
8804 
8805   SDLoc DL = getCurSDLoc();
8806   Callee = getValue(CI.getCalledValue());
8807   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8808 
8809   // The stackmap intrinsic only records the live variables (the arguments
8810   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8811   // intrinsic, this won't be lowered to a function call. This means we don't
8812   // have to worry about calling conventions and target specific lowering code.
8813   // Instead we perform the call lowering right here.
8814   //
8815   // chain, flag = CALLSEQ_START(chain, 0, 0)
8816   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8817   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8818   //
8819   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8820   InFlag = Chain.getValue(1);
8821 
8822   // Add the <id> and <numBytes> constants.
8823   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8824   Ops.push_back(DAG.getTargetConstant(
8825                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8826   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8827   Ops.push_back(DAG.getTargetConstant(
8828                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8829                   MVT::i32));
8830 
8831   // Push live variables for the stack map.
8832   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8833 
8834   // We are not pushing any register mask info here on the operands list,
8835   // because the stackmap doesn't clobber anything.
8836 
8837   // Push the chain and the glue flag.
8838   Ops.push_back(Chain);
8839   Ops.push_back(InFlag);
8840 
8841   // Create the STACKMAP node.
8842   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8843   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8844   Chain = SDValue(SM, 0);
8845   InFlag = Chain.getValue(1);
8846 
8847   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8848 
8849   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8850 
8851   // Set the root to the target-lowered call chain.
8852   DAG.setRoot(Chain);
8853 
8854   // Inform the Frame Information that we have a stackmap in this function.
8855   FuncInfo.MF->getFrameInfo().setHasStackMap();
8856 }
8857 
8858 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8859 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8860                                           const BasicBlock *EHPadBB) {
8861   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8862   //                                                 i32 <numBytes>,
8863   //                                                 i8* <target>,
8864   //                                                 i32 <numArgs>,
8865   //                                                 [Args...],
8866   //                                                 [live variables...])
8867 
8868   CallingConv::ID CC = CS.getCallingConv();
8869   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8870   bool HasDef = !CS->getType()->isVoidTy();
8871   SDLoc dl = getCurSDLoc();
8872   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8873 
8874   // Handle immediate and symbolic callees.
8875   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8876     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8877                                    /*isTarget=*/true);
8878   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8879     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8880                                          SDLoc(SymbolicCallee),
8881                                          SymbolicCallee->getValueType(0));
8882 
8883   // Get the real number of arguments participating in the call <numArgs>
8884   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8885   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8886 
8887   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8888   // Intrinsics include all meta-operands up to but not including CC.
8889   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8890   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8891          "Not enough arguments provided to the patchpoint intrinsic");
8892 
8893   // For AnyRegCC the arguments are lowered later on manually.
8894   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8895   Type *ReturnTy =
8896     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8897 
8898   TargetLowering::CallLoweringInfo CLI(DAG);
8899   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8900                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8901   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8902 
8903   SDNode *CallEnd = Result.second.getNode();
8904   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8905     CallEnd = CallEnd->getOperand(0).getNode();
8906 
8907   /// Get a call instruction from the call sequence chain.
8908   /// Tail calls are not allowed.
8909   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8910          "Expected a callseq node.");
8911   SDNode *Call = CallEnd->getOperand(0).getNode();
8912   bool HasGlue = Call->getGluedNode();
8913 
8914   // Replace the target specific call node with the patchable intrinsic.
8915   SmallVector<SDValue, 8> Ops;
8916 
8917   // Add the <id> and <numBytes> constants.
8918   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8919   Ops.push_back(DAG.getTargetConstant(
8920                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8921   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8922   Ops.push_back(DAG.getTargetConstant(
8923                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8924                   MVT::i32));
8925 
8926   // Add the callee.
8927   Ops.push_back(Callee);
8928 
8929   // Adjust <numArgs> to account for any arguments that have been passed on the
8930   // stack instead.
8931   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8932   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8933   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8934   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8935 
8936   // Add the calling convention
8937   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8938 
8939   // Add the arguments we omitted previously. The register allocator should
8940   // place these in any free register.
8941   if (IsAnyRegCC)
8942     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8943       Ops.push_back(getValue(CS.getArgument(i)));
8944 
8945   // Push the arguments from the call instruction up to the register mask.
8946   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8947   Ops.append(Call->op_begin() + 2, e);
8948 
8949   // Push live variables for the stack map.
8950   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8951 
8952   // Push the register mask info.
8953   if (HasGlue)
8954     Ops.push_back(*(Call->op_end()-2));
8955   else
8956     Ops.push_back(*(Call->op_end()-1));
8957 
8958   // Push the chain (this is originally the first operand of the call, but
8959   // becomes now the last or second to last operand).
8960   Ops.push_back(*(Call->op_begin()));
8961 
8962   // Push the glue flag (last operand).
8963   if (HasGlue)
8964     Ops.push_back(*(Call->op_end()-1));
8965 
8966   SDVTList NodeTys;
8967   if (IsAnyRegCC && HasDef) {
8968     // Create the return types based on the intrinsic definition
8969     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8970     SmallVector<EVT, 3> ValueVTs;
8971     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8972     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8973 
8974     // There is always a chain and a glue type at the end
8975     ValueVTs.push_back(MVT::Other);
8976     ValueVTs.push_back(MVT::Glue);
8977     NodeTys = DAG.getVTList(ValueVTs);
8978   } else
8979     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8980 
8981   // Replace the target specific call node with a PATCHPOINT node.
8982   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8983                                          dl, NodeTys, Ops);
8984 
8985   // Update the NodeMap.
8986   if (HasDef) {
8987     if (IsAnyRegCC)
8988       setValue(CS.getInstruction(), SDValue(MN, 0));
8989     else
8990       setValue(CS.getInstruction(), Result.first);
8991   }
8992 
8993   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8994   // call sequence. Furthermore the location of the chain and glue can change
8995   // when the AnyReg calling convention is used and the intrinsic returns a
8996   // value.
8997   if (IsAnyRegCC && HasDef) {
8998     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8999     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
9000     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9001   } else
9002     DAG.ReplaceAllUsesWith(Call, MN);
9003   DAG.DeleteNode(Call);
9004 
9005   // Inform the Frame Information that we have a patchpoint in this function.
9006   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
9007 }
9008 
9009 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
9010                                             unsigned Intrinsic) {
9011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9012   SDValue Op1 = getValue(I.getArgOperand(0));
9013   SDValue Op2;
9014   if (I.getNumArgOperands() > 1)
9015     Op2 = getValue(I.getArgOperand(1));
9016   SDLoc dl = getCurSDLoc();
9017   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
9018   SDValue Res;
9019   FastMathFlags FMF;
9020   if (isa<FPMathOperator>(I))
9021     FMF = I.getFastMathFlags();
9022 
9023   switch (Intrinsic) {
9024   case Intrinsic::experimental_vector_reduce_v2_fadd:
9025     if (FMF.allowReassoc())
9026       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
9027                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
9028     else
9029       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
9030     break;
9031   case Intrinsic::experimental_vector_reduce_v2_fmul:
9032     if (FMF.allowReassoc())
9033       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
9034                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
9035     else
9036       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
9037     break;
9038   case Intrinsic::experimental_vector_reduce_add:
9039     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
9040     break;
9041   case Intrinsic::experimental_vector_reduce_mul:
9042     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
9043     break;
9044   case Intrinsic::experimental_vector_reduce_and:
9045     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
9046     break;
9047   case Intrinsic::experimental_vector_reduce_or:
9048     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
9049     break;
9050   case Intrinsic::experimental_vector_reduce_xor:
9051     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
9052     break;
9053   case Intrinsic::experimental_vector_reduce_smax:
9054     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
9055     break;
9056   case Intrinsic::experimental_vector_reduce_smin:
9057     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
9058     break;
9059   case Intrinsic::experimental_vector_reduce_umax:
9060     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
9061     break;
9062   case Intrinsic::experimental_vector_reduce_umin:
9063     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
9064     break;
9065   case Intrinsic::experimental_vector_reduce_fmax:
9066     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
9067     break;
9068   case Intrinsic::experimental_vector_reduce_fmin:
9069     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
9070     break;
9071   default:
9072     llvm_unreachable("Unhandled vector reduce intrinsic");
9073   }
9074   setValue(&I, Res);
9075 }
9076 
9077 /// Returns an AttributeList representing the attributes applied to the return
9078 /// value of the given call.
9079 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
9080   SmallVector<Attribute::AttrKind, 2> Attrs;
9081   if (CLI.RetSExt)
9082     Attrs.push_back(Attribute::SExt);
9083   if (CLI.RetZExt)
9084     Attrs.push_back(Attribute::ZExt);
9085   if (CLI.IsInReg)
9086     Attrs.push_back(Attribute::InReg);
9087 
9088   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
9089                             Attrs);
9090 }
9091 
9092 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
9093 /// implementation, which just calls LowerCall.
9094 /// FIXME: When all targets are
9095 /// migrated to using LowerCall, this hook should be integrated into SDISel.
9096 std::pair<SDValue, SDValue>
9097 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
9098   // Handle the incoming return values from the call.
9099   CLI.Ins.clear();
9100   Type *OrigRetTy = CLI.RetTy;
9101   SmallVector<EVT, 4> RetTys;
9102   SmallVector<uint64_t, 4> Offsets;
9103   auto &DL = CLI.DAG.getDataLayout();
9104   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
9105 
9106   if (CLI.IsPostTypeLegalization) {
9107     // If we are lowering a libcall after legalization, split the return type.
9108     SmallVector<EVT, 4> OldRetTys;
9109     SmallVector<uint64_t, 4> OldOffsets;
9110     RetTys.swap(OldRetTys);
9111     Offsets.swap(OldOffsets);
9112 
9113     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
9114       EVT RetVT = OldRetTys[i];
9115       uint64_t Offset = OldOffsets[i];
9116       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
9117       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
9118       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
9119       RetTys.append(NumRegs, RegisterVT);
9120       for (unsigned j = 0; j != NumRegs; ++j)
9121         Offsets.push_back(Offset + j * RegisterVTByteSZ);
9122     }
9123   }
9124 
9125   SmallVector<ISD::OutputArg, 4> Outs;
9126   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
9127 
9128   bool CanLowerReturn =
9129       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
9130                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
9131 
9132   SDValue DemoteStackSlot;
9133   int DemoteStackIdx = -100;
9134   if (!CanLowerReturn) {
9135     // FIXME: equivalent assert?
9136     // assert(!CS.hasInAllocaArgument() &&
9137     //        "sret demotion is incompatible with inalloca");
9138     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
9139     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
9140     MachineFunction &MF = CLI.DAG.getMachineFunction();
9141     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
9142     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
9143                                               DL.getAllocaAddrSpace());
9144 
9145     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
9146     ArgListEntry Entry;
9147     Entry.Node = DemoteStackSlot;
9148     Entry.Ty = StackSlotPtrType;
9149     Entry.IsSExt = false;
9150     Entry.IsZExt = false;
9151     Entry.IsInReg = false;
9152     Entry.IsSRet = true;
9153     Entry.IsNest = false;
9154     Entry.IsByVal = false;
9155     Entry.IsReturned = false;
9156     Entry.IsSwiftSelf = false;
9157     Entry.IsSwiftError = false;
9158     Entry.IsCFGuardTarget = false;
9159     Entry.Alignment = Align;
9160     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
9161     CLI.NumFixedArgs += 1;
9162     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
9163 
9164     // sret demotion isn't compatible with tail-calls, since the sret argument
9165     // points into the callers stack frame.
9166     CLI.IsTailCall = false;
9167   } else {
9168     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9169         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
9170     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9171       ISD::ArgFlagsTy Flags;
9172       if (NeedsRegBlock) {
9173         Flags.setInConsecutiveRegs();
9174         if (I == RetTys.size() - 1)
9175           Flags.setInConsecutiveRegsLast();
9176       }
9177       EVT VT = RetTys[I];
9178       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9179                                                      CLI.CallConv, VT);
9180       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9181                                                        CLI.CallConv, VT);
9182       for (unsigned i = 0; i != NumRegs; ++i) {
9183         ISD::InputArg MyFlags;
9184         MyFlags.Flags = Flags;
9185         MyFlags.VT = RegisterVT;
9186         MyFlags.ArgVT = VT;
9187         MyFlags.Used = CLI.IsReturnValueUsed;
9188         if (CLI.RetTy->isPointerTy()) {
9189           MyFlags.Flags.setPointer();
9190           MyFlags.Flags.setPointerAddrSpace(
9191               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9192         }
9193         if (CLI.RetSExt)
9194           MyFlags.Flags.setSExt();
9195         if (CLI.RetZExt)
9196           MyFlags.Flags.setZExt();
9197         if (CLI.IsInReg)
9198           MyFlags.Flags.setInReg();
9199         CLI.Ins.push_back(MyFlags);
9200       }
9201     }
9202   }
9203 
9204   // We push in swifterror return as the last element of CLI.Ins.
9205   ArgListTy &Args = CLI.getArgs();
9206   if (supportSwiftError()) {
9207     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9208       if (Args[i].IsSwiftError) {
9209         ISD::InputArg MyFlags;
9210         MyFlags.VT = getPointerTy(DL);
9211         MyFlags.ArgVT = EVT(getPointerTy(DL));
9212         MyFlags.Flags.setSwiftError();
9213         CLI.Ins.push_back(MyFlags);
9214       }
9215     }
9216   }
9217 
9218   // Handle all of the outgoing arguments.
9219   CLI.Outs.clear();
9220   CLI.OutVals.clear();
9221   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9222     SmallVector<EVT, 4> ValueVTs;
9223     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9224     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9225     Type *FinalType = Args[i].Ty;
9226     if (Args[i].IsByVal)
9227       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9228     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9229         FinalType, CLI.CallConv, CLI.IsVarArg);
9230     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9231          ++Value) {
9232       EVT VT = ValueVTs[Value];
9233       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9234       SDValue Op = SDValue(Args[i].Node.getNode(),
9235                            Args[i].Node.getResNo() + Value);
9236       ISD::ArgFlagsTy Flags;
9237 
9238       // Certain targets (such as MIPS), may have a different ABI alignment
9239       // for a type depending on the context. Give the target a chance to
9240       // specify the alignment it wants.
9241       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9242 
9243       if (Args[i].Ty->isPointerTy()) {
9244         Flags.setPointer();
9245         Flags.setPointerAddrSpace(
9246             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9247       }
9248       if (Args[i].IsZExt)
9249         Flags.setZExt();
9250       if (Args[i].IsSExt)
9251         Flags.setSExt();
9252       if (Args[i].IsInReg) {
9253         // If we are using vectorcall calling convention, a structure that is
9254         // passed InReg - is surely an HVA
9255         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9256             isa<StructType>(FinalType)) {
9257           // The first value of a structure is marked
9258           if (0 == Value)
9259             Flags.setHvaStart();
9260           Flags.setHva();
9261         }
9262         // Set InReg Flag
9263         Flags.setInReg();
9264       }
9265       if (Args[i].IsSRet)
9266         Flags.setSRet();
9267       if (Args[i].IsSwiftSelf)
9268         Flags.setSwiftSelf();
9269       if (Args[i].IsSwiftError)
9270         Flags.setSwiftError();
9271       if (Args[i].IsCFGuardTarget)
9272         Flags.setCFGuardTarget();
9273       if (Args[i].IsByVal)
9274         Flags.setByVal();
9275       if (Args[i].IsInAlloca) {
9276         Flags.setInAlloca();
9277         // Set the byval flag for CCAssignFn callbacks that don't know about
9278         // inalloca.  This way we can know how many bytes we should've allocated
9279         // and how many bytes a callee cleanup function will pop.  If we port
9280         // inalloca to more targets, we'll have to add custom inalloca handling
9281         // in the various CC lowering callbacks.
9282         Flags.setByVal();
9283       }
9284       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9285         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9286         Type *ElementTy = Ty->getElementType();
9287 
9288         unsigned FrameSize = DL.getTypeAllocSize(
9289             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9290         Flags.setByValSize(FrameSize);
9291 
9292         // info is not there but there are cases it cannot get right.
9293         unsigned FrameAlign;
9294         if (Args[i].Alignment)
9295           FrameAlign = Args[i].Alignment;
9296         else
9297           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9298         Flags.setByValAlign(Align(FrameAlign));
9299       }
9300       if (Args[i].IsNest)
9301         Flags.setNest();
9302       if (NeedsRegBlock)
9303         Flags.setInConsecutiveRegs();
9304       Flags.setOrigAlign(OriginalAlignment);
9305 
9306       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9307                                                  CLI.CallConv, VT);
9308       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9309                                                         CLI.CallConv, VT);
9310       SmallVector<SDValue, 4> Parts(NumParts);
9311       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9312 
9313       if (Args[i].IsSExt)
9314         ExtendKind = ISD::SIGN_EXTEND;
9315       else if (Args[i].IsZExt)
9316         ExtendKind = ISD::ZERO_EXTEND;
9317 
9318       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9319       // for now.
9320       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9321           CanLowerReturn) {
9322         assert((CLI.RetTy == Args[i].Ty ||
9323                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9324                  CLI.RetTy->getPointerAddressSpace() ==
9325                      Args[i].Ty->getPointerAddressSpace())) &&
9326                RetTys.size() == NumValues && "unexpected use of 'returned'");
9327         // Before passing 'returned' to the target lowering code, ensure that
9328         // either the register MVT and the actual EVT are the same size or that
9329         // the return value and argument are extended in the same way; in these
9330         // cases it's safe to pass the argument register value unchanged as the
9331         // return register value (although it's at the target's option whether
9332         // to do so)
9333         // TODO: allow code generation to take advantage of partially preserved
9334         // registers rather than clobbering the entire register when the
9335         // parameter extension method is not compatible with the return
9336         // extension method
9337         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9338             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9339              CLI.RetZExt == Args[i].IsZExt))
9340           Flags.setReturned();
9341       }
9342 
9343       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9344                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9345 
9346       for (unsigned j = 0; j != NumParts; ++j) {
9347         // if it isn't first piece, alignment must be 1
9348         // For scalable vectors the scalable part is currently handled
9349         // by individual targets, so we just use the known minimum size here.
9350         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9351                     i < CLI.NumFixedArgs, i,
9352                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9353         if (NumParts > 1 && j == 0)
9354           MyFlags.Flags.setSplit();
9355         else if (j != 0) {
9356           MyFlags.Flags.setOrigAlign(Align(1));
9357           if (j == NumParts - 1)
9358             MyFlags.Flags.setSplitEnd();
9359         }
9360 
9361         CLI.Outs.push_back(MyFlags);
9362         CLI.OutVals.push_back(Parts[j]);
9363       }
9364 
9365       if (NeedsRegBlock && Value == NumValues - 1)
9366         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9367     }
9368   }
9369 
9370   SmallVector<SDValue, 4> InVals;
9371   CLI.Chain = LowerCall(CLI, InVals);
9372 
9373   // Update CLI.InVals to use outside of this function.
9374   CLI.InVals = InVals;
9375 
9376   // Verify that the target's LowerCall behaved as expected.
9377   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9378          "LowerCall didn't return a valid chain!");
9379   assert((!CLI.IsTailCall || InVals.empty()) &&
9380          "LowerCall emitted a return value for a tail call!");
9381   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9382          "LowerCall didn't emit the correct number of values!");
9383 
9384   // For a tail call, the return value is merely live-out and there aren't
9385   // any nodes in the DAG representing it. Return a special value to
9386   // indicate that a tail call has been emitted and no more Instructions
9387   // should be processed in the current block.
9388   if (CLI.IsTailCall) {
9389     CLI.DAG.setRoot(CLI.Chain);
9390     return std::make_pair(SDValue(), SDValue());
9391   }
9392 
9393 #ifndef NDEBUG
9394   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9395     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9396     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9397            "LowerCall emitted a value with the wrong type!");
9398   }
9399 #endif
9400 
9401   SmallVector<SDValue, 4> ReturnValues;
9402   if (!CanLowerReturn) {
9403     // The instruction result is the result of loading from the
9404     // hidden sret parameter.
9405     SmallVector<EVT, 1> PVTs;
9406     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9407 
9408     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9409     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9410     EVT PtrVT = PVTs[0];
9411 
9412     unsigned NumValues = RetTys.size();
9413     ReturnValues.resize(NumValues);
9414     SmallVector<SDValue, 4> Chains(NumValues);
9415 
9416     // An aggregate return value cannot wrap around the address space, so
9417     // offsets to its parts don't wrap either.
9418     SDNodeFlags Flags;
9419     Flags.setNoUnsignedWrap(true);
9420 
9421     for (unsigned i = 0; i < NumValues; ++i) {
9422       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9423                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9424                                                         PtrVT), Flags);
9425       SDValue L = CLI.DAG.getLoad(
9426           RetTys[i], CLI.DL, CLI.Chain, Add,
9427           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9428                                             DemoteStackIdx, Offsets[i]),
9429           /* Alignment = */ 1);
9430       ReturnValues[i] = L;
9431       Chains[i] = L.getValue(1);
9432     }
9433 
9434     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9435   } else {
9436     // Collect the legal value parts into potentially illegal values
9437     // that correspond to the original function's return values.
9438     Optional<ISD::NodeType> AssertOp;
9439     if (CLI.RetSExt)
9440       AssertOp = ISD::AssertSext;
9441     else if (CLI.RetZExt)
9442       AssertOp = ISD::AssertZext;
9443     unsigned CurReg = 0;
9444     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9445       EVT VT = RetTys[I];
9446       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9447                                                      CLI.CallConv, VT);
9448       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9449                                                        CLI.CallConv, VT);
9450 
9451       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9452                                               NumRegs, RegisterVT, VT, nullptr,
9453                                               CLI.CallConv, AssertOp));
9454       CurReg += NumRegs;
9455     }
9456 
9457     // For a function returning void, there is no return value. We can't create
9458     // such a node, so we just return a null return value in that case. In
9459     // that case, nothing will actually look at the value.
9460     if (ReturnValues.empty())
9461       return std::make_pair(SDValue(), CLI.Chain);
9462   }
9463 
9464   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9465                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9466   return std::make_pair(Res, CLI.Chain);
9467 }
9468 
9469 void TargetLowering::LowerOperationWrapper(SDNode *N,
9470                                            SmallVectorImpl<SDValue> &Results,
9471                                            SelectionDAG &DAG) const {
9472   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9473     Results.push_back(Res);
9474 }
9475 
9476 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9477   llvm_unreachable("LowerOperation not implemented for this target!");
9478 }
9479 
9480 void
9481 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9482   SDValue Op = getNonRegisterValue(V);
9483   assert((Op.getOpcode() != ISD::CopyFromReg ||
9484           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9485          "Copy from a reg to the same reg!");
9486   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9487 
9488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9489   // If this is an InlineAsm we have to match the registers required, not the
9490   // notional registers required by the type.
9491 
9492   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9493                    None); // This is not an ABI copy.
9494   SDValue Chain = DAG.getEntryNode();
9495 
9496   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9497                               FuncInfo.PreferredExtendType.end())
9498                                  ? ISD::ANY_EXTEND
9499                                  : FuncInfo.PreferredExtendType[V];
9500   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9501   PendingExports.push_back(Chain);
9502 }
9503 
9504 #include "llvm/CodeGen/SelectionDAGISel.h"
9505 
9506 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9507 /// entry block, return true.  This includes arguments used by switches, since
9508 /// the switch may expand into multiple basic blocks.
9509 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9510   // With FastISel active, we may be splitting blocks, so force creation
9511   // of virtual registers for all non-dead arguments.
9512   if (FastISel)
9513     return A->use_empty();
9514 
9515   const BasicBlock &Entry = A->getParent()->front();
9516   for (const User *U : A->users())
9517     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9518       return false;  // Use not in entry block.
9519 
9520   return true;
9521 }
9522 
9523 using ArgCopyElisionMapTy =
9524     DenseMap<const Argument *,
9525              std::pair<const AllocaInst *, const StoreInst *>>;
9526 
9527 /// Scan the entry block of the function in FuncInfo for arguments that look
9528 /// like copies into a local alloca. Record any copied arguments in
9529 /// ArgCopyElisionCandidates.
9530 static void
9531 findArgumentCopyElisionCandidates(const DataLayout &DL,
9532                                   FunctionLoweringInfo *FuncInfo,
9533                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9534   // Record the state of every static alloca used in the entry block. Argument
9535   // allocas are all used in the entry block, so we need approximately as many
9536   // entries as we have arguments.
9537   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9538   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9539   unsigned NumArgs = FuncInfo->Fn->arg_size();
9540   StaticAllocas.reserve(NumArgs * 2);
9541 
9542   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9543     if (!V)
9544       return nullptr;
9545     V = V->stripPointerCasts();
9546     const auto *AI = dyn_cast<AllocaInst>(V);
9547     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9548       return nullptr;
9549     auto Iter = StaticAllocas.insert({AI, Unknown});
9550     return &Iter.first->second;
9551   };
9552 
9553   // Look for stores of arguments to static allocas. Look through bitcasts and
9554   // GEPs to handle type coercions, as long as the alloca is fully initialized
9555   // by the store. Any non-store use of an alloca escapes it and any subsequent
9556   // unanalyzed store might write it.
9557   // FIXME: Handle structs initialized with multiple stores.
9558   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9559     // Look for stores, and handle non-store uses conservatively.
9560     const auto *SI = dyn_cast<StoreInst>(&I);
9561     if (!SI) {
9562       // We will look through cast uses, so ignore them completely.
9563       if (I.isCast())
9564         continue;
9565       // Ignore debug info intrinsics, they don't escape or store to allocas.
9566       if (isa<DbgInfoIntrinsic>(I))
9567         continue;
9568       // This is an unknown instruction. Assume it escapes or writes to all
9569       // static alloca operands.
9570       for (const Use &U : I.operands()) {
9571         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9572           *Info = StaticAllocaInfo::Clobbered;
9573       }
9574       continue;
9575     }
9576 
9577     // If the stored value is a static alloca, mark it as escaped.
9578     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9579       *Info = StaticAllocaInfo::Clobbered;
9580 
9581     // Check if the destination is a static alloca.
9582     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9583     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9584     if (!Info)
9585       continue;
9586     const AllocaInst *AI = cast<AllocaInst>(Dst);
9587 
9588     // Skip allocas that have been initialized or clobbered.
9589     if (*Info != StaticAllocaInfo::Unknown)
9590       continue;
9591 
9592     // Check if the stored value is an argument, and that this store fully
9593     // initializes the alloca. Don't elide copies from the same argument twice.
9594     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9595     const auto *Arg = dyn_cast<Argument>(Val);
9596     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9597         Arg->getType()->isEmptyTy() ||
9598         DL.getTypeStoreSize(Arg->getType()) !=
9599             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9600         ArgCopyElisionCandidates.count(Arg)) {
9601       *Info = StaticAllocaInfo::Clobbered;
9602       continue;
9603     }
9604 
9605     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9606                       << '\n');
9607 
9608     // Mark this alloca and store for argument copy elision.
9609     *Info = StaticAllocaInfo::Elidable;
9610     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9611 
9612     // Stop scanning if we've seen all arguments. This will happen early in -O0
9613     // builds, which is useful, because -O0 builds have large entry blocks and
9614     // many allocas.
9615     if (ArgCopyElisionCandidates.size() == NumArgs)
9616       break;
9617   }
9618 }
9619 
9620 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9621 /// ArgVal is a load from a suitable fixed stack object.
9622 static void tryToElideArgumentCopy(
9623     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
9624     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9625     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9626     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9627     SDValue ArgVal, bool &ArgHasUses) {
9628   // Check if this is a load from a fixed stack object.
9629   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9630   if (!LNode)
9631     return;
9632   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9633   if (!FINode)
9634     return;
9635 
9636   // Check that the fixed stack object is the right size and alignment.
9637   // Look at the alignment that the user wrote on the alloca instead of looking
9638   // at the stack object.
9639   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9640   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9641   const AllocaInst *AI = ArgCopyIter->second.first;
9642   int FixedIndex = FINode->getIndex();
9643   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
9644   int OldIndex = AllocaIndex;
9645   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
9646   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9647     LLVM_DEBUG(
9648         dbgs() << "  argument copy elision failed due to bad fixed stack "
9649                   "object size\n");
9650     return;
9651   }
9652   unsigned RequiredAlignment = AI->getAlignment();
9653   if (!RequiredAlignment) {
9654     RequiredAlignment = FuncInfo.MF->getDataLayout().getABITypeAlignment(
9655         AI->getAllocatedType());
9656   }
9657   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9658     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9659                          "greater than stack argument alignment ("
9660                       << RequiredAlignment << " vs "
9661                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9662     return;
9663   }
9664 
9665   // Perform the elision. Delete the old stack object and replace its only use
9666   // in the variable info map. Mark the stack object as mutable.
9667   LLVM_DEBUG({
9668     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9669            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9670            << '\n';
9671   });
9672   MFI.RemoveStackObject(OldIndex);
9673   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9674   AllocaIndex = FixedIndex;
9675   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9676   Chains.push_back(ArgVal.getValue(1));
9677 
9678   // Avoid emitting code for the store implementing the copy.
9679   const StoreInst *SI = ArgCopyIter->second.second;
9680   ElidedArgCopyInstrs.insert(SI);
9681 
9682   // Check for uses of the argument again so that we can avoid exporting ArgVal
9683   // if it is't used by anything other than the store.
9684   for (const Value *U : Arg.users()) {
9685     if (U != SI) {
9686       ArgHasUses = true;
9687       break;
9688     }
9689   }
9690 }
9691 
9692 void SelectionDAGISel::LowerArguments(const Function &F) {
9693   SelectionDAG &DAG = SDB->DAG;
9694   SDLoc dl = SDB->getCurSDLoc();
9695   const DataLayout &DL = DAG.getDataLayout();
9696   SmallVector<ISD::InputArg, 16> Ins;
9697 
9698   if (!FuncInfo->CanLowerReturn) {
9699     // Put in an sret pointer parameter before all the other parameters.
9700     SmallVector<EVT, 1> ValueVTs;
9701     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9702                     F.getReturnType()->getPointerTo(
9703                         DAG.getDataLayout().getAllocaAddrSpace()),
9704                     ValueVTs);
9705 
9706     // NOTE: Assuming that a pointer will never break down to more than one VT
9707     // or one register.
9708     ISD::ArgFlagsTy Flags;
9709     Flags.setSRet();
9710     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9711     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9712                          ISD::InputArg::NoArgIndex, 0);
9713     Ins.push_back(RetArg);
9714   }
9715 
9716   // Look for stores of arguments to static allocas. Mark such arguments with a
9717   // flag to ask the target to give us the memory location of that argument if
9718   // available.
9719   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9720   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
9721                                     ArgCopyElisionCandidates);
9722 
9723   // Set up the incoming argument description vector.
9724   for (const Argument &Arg : F.args()) {
9725     unsigned ArgNo = Arg.getArgNo();
9726     SmallVector<EVT, 4> ValueVTs;
9727     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9728     bool isArgValueUsed = !Arg.use_empty();
9729     unsigned PartBase = 0;
9730     Type *FinalType = Arg.getType();
9731     if (Arg.hasAttribute(Attribute::ByVal))
9732       FinalType = Arg.getParamByValType();
9733     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9734         FinalType, F.getCallingConv(), F.isVarArg());
9735     for (unsigned Value = 0, NumValues = ValueVTs.size();
9736          Value != NumValues; ++Value) {
9737       EVT VT = ValueVTs[Value];
9738       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9739       ISD::ArgFlagsTy Flags;
9740 
9741       // Certain targets (such as MIPS), may have a different ABI alignment
9742       // for a type depending on the context. Give the target a chance to
9743       // specify the alignment it wants.
9744       const Align OriginalAlignment(
9745           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9746 
9747       if (Arg.getType()->isPointerTy()) {
9748         Flags.setPointer();
9749         Flags.setPointerAddrSpace(
9750             cast<PointerType>(Arg.getType())->getAddressSpace());
9751       }
9752       if (Arg.hasAttribute(Attribute::ZExt))
9753         Flags.setZExt();
9754       if (Arg.hasAttribute(Attribute::SExt))
9755         Flags.setSExt();
9756       if (Arg.hasAttribute(Attribute::InReg)) {
9757         // If we are using vectorcall calling convention, a structure that is
9758         // passed InReg - is surely an HVA
9759         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9760             isa<StructType>(Arg.getType())) {
9761           // The first value of a structure is marked
9762           if (0 == Value)
9763             Flags.setHvaStart();
9764           Flags.setHva();
9765         }
9766         // Set InReg Flag
9767         Flags.setInReg();
9768       }
9769       if (Arg.hasAttribute(Attribute::StructRet))
9770         Flags.setSRet();
9771       if (Arg.hasAttribute(Attribute::SwiftSelf))
9772         Flags.setSwiftSelf();
9773       if (Arg.hasAttribute(Attribute::SwiftError))
9774         Flags.setSwiftError();
9775       if (Arg.hasAttribute(Attribute::ByVal))
9776         Flags.setByVal();
9777       if (Arg.hasAttribute(Attribute::InAlloca)) {
9778         Flags.setInAlloca();
9779         // Set the byval flag for CCAssignFn callbacks that don't know about
9780         // inalloca.  This way we can know how many bytes we should've allocated
9781         // and how many bytes a callee cleanup function will pop.  If we port
9782         // inalloca to more targets, we'll have to add custom inalloca handling
9783         // in the various CC lowering callbacks.
9784         Flags.setByVal();
9785       }
9786       if (F.getCallingConv() == CallingConv::X86_INTR) {
9787         // IA Interrupt passes frame (1st parameter) by value in the stack.
9788         if (ArgNo == 0)
9789           Flags.setByVal();
9790       }
9791       if (Flags.isByVal() || Flags.isInAlloca()) {
9792         Type *ElementTy = Arg.getParamByValType();
9793 
9794         // For ByVal, size and alignment should be passed from FE.  BE will
9795         // guess if this info is not there but there are cases it cannot get
9796         // right.
9797         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9798         Flags.setByValSize(FrameSize);
9799 
9800         unsigned FrameAlign;
9801         if (Arg.getParamAlignment())
9802           FrameAlign = Arg.getParamAlignment();
9803         else
9804           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9805         Flags.setByValAlign(Align(FrameAlign));
9806       }
9807       if (Arg.hasAttribute(Attribute::Nest))
9808         Flags.setNest();
9809       if (NeedsRegBlock)
9810         Flags.setInConsecutiveRegs();
9811       Flags.setOrigAlign(OriginalAlignment);
9812       if (ArgCopyElisionCandidates.count(&Arg))
9813         Flags.setCopyElisionCandidate();
9814       if (Arg.hasAttribute(Attribute::Returned))
9815         Flags.setReturned();
9816 
9817       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9818           *CurDAG->getContext(), F.getCallingConv(), VT);
9819       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9820           *CurDAG->getContext(), F.getCallingConv(), VT);
9821       for (unsigned i = 0; i != NumRegs; ++i) {
9822         // For scalable vectors, use the minimum size; individual targets
9823         // are responsible for handling scalable vector arguments and
9824         // return values.
9825         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9826                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9827         if (NumRegs > 1 && i == 0)
9828           MyFlags.Flags.setSplit();
9829         // if it isn't first piece, alignment must be 1
9830         else if (i > 0) {
9831           MyFlags.Flags.setOrigAlign(Align(1));
9832           if (i == NumRegs - 1)
9833             MyFlags.Flags.setSplitEnd();
9834         }
9835         Ins.push_back(MyFlags);
9836       }
9837       if (NeedsRegBlock && Value == NumValues - 1)
9838         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9839       PartBase += VT.getStoreSize().getKnownMinSize();
9840     }
9841   }
9842 
9843   // Call the target to set up the argument values.
9844   SmallVector<SDValue, 8> InVals;
9845   SDValue NewRoot = TLI->LowerFormalArguments(
9846       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9847 
9848   // Verify that the target's LowerFormalArguments behaved as expected.
9849   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9850          "LowerFormalArguments didn't return a valid chain!");
9851   assert(InVals.size() == Ins.size() &&
9852          "LowerFormalArguments didn't emit the correct number of values!");
9853   LLVM_DEBUG({
9854     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9855       assert(InVals[i].getNode() &&
9856              "LowerFormalArguments emitted a null value!");
9857       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9858              "LowerFormalArguments emitted a value with the wrong type!");
9859     }
9860   });
9861 
9862   // Update the DAG with the new chain value resulting from argument lowering.
9863   DAG.setRoot(NewRoot);
9864 
9865   // Set up the argument values.
9866   unsigned i = 0;
9867   if (!FuncInfo->CanLowerReturn) {
9868     // Create a virtual register for the sret pointer, and put in a copy
9869     // from the sret argument into it.
9870     SmallVector<EVT, 1> ValueVTs;
9871     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9872                     F.getReturnType()->getPointerTo(
9873                         DAG.getDataLayout().getAllocaAddrSpace()),
9874                     ValueVTs);
9875     MVT VT = ValueVTs[0].getSimpleVT();
9876     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9877     Optional<ISD::NodeType> AssertOp = None;
9878     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9879                                         nullptr, F.getCallingConv(), AssertOp);
9880 
9881     MachineFunction& MF = SDB->DAG.getMachineFunction();
9882     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9883     Register SRetReg =
9884         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9885     FuncInfo->DemoteRegister = SRetReg;
9886     NewRoot =
9887         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9888     DAG.setRoot(NewRoot);
9889 
9890     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9891     ++i;
9892   }
9893 
9894   SmallVector<SDValue, 4> Chains;
9895   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9896   for (const Argument &Arg : F.args()) {
9897     SmallVector<SDValue, 4> ArgValues;
9898     SmallVector<EVT, 4> ValueVTs;
9899     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9900     unsigned NumValues = ValueVTs.size();
9901     if (NumValues == 0)
9902       continue;
9903 
9904     bool ArgHasUses = !Arg.use_empty();
9905 
9906     // Elide the copying store if the target loaded this argument from a
9907     // suitable fixed stack object.
9908     if (Ins[i].Flags.isCopyElisionCandidate()) {
9909       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9910                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9911                              InVals[i], ArgHasUses);
9912     }
9913 
9914     // If this argument is unused then remember its value. It is used to generate
9915     // debugging information.
9916     bool isSwiftErrorArg =
9917         TLI->supportSwiftError() &&
9918         Arg.hasAttribute(Attribute::SwiftError);
9919     if (!ArgHasUses && !isSwiftErrorArg) {
9920       SDB->setUnusedArgValue(&Arg, InVals[i]);
9921 
9922       // Also remember any frame index for use in FastISel.
9923       if (FrameIndexSDNode *FI =
9924           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9925         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9926     }
9927 
9928     for (unsigned Val = 0; Val != NumValues; ++Val) {
9929       EVT VT = ValueVTs[Val];
9930       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9931                                                       F.getCallingConv(), VT);
9932       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9933           *CurDAG->getContext(), F.getCallingConv(), VT);
9934 
9935       // Even an apparent 'unused' swifterror argument needs to be returned. So
9936       // we do generate a copy for it that can be used on return from the
9937       // function.
9938       if (ArgHasUses || isSwiftErrorArg) {
9939         Optional<ISD::NodeType> AssertOp;
9940         if (Arg.hasAttribute(Attribute::SExt))
9941           AssertOp = ISD::AssertSext;
9942         else if (Arg.hasAttribute(Attribute::ZExt))
9943           AssertOp = ISD::AssertZext;
9944 
9945         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9946                                              PartVT, VT, nullptr,
9947                                              F.getCallingConv(), AssertOp));
9948       }
9949 
9950       i += NumParts;
9951     }
9952 
9953     // We don't need to do anything else for unused arguments.
9954     if (ArgValues.empty())
9955       continue;
9956 
9957     // Note down frame index.
9958     if (FrameIndexSDNode *FI =
9959         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9960       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9961 
9962     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9963                                      SDB->getCurSDLoc());
9964 
9965     SDB->setValue(&Arg, Res);
9966     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9967       // We want to associate the argument with the frame index, among
9968       // involved operands, that correspond to the lowest address. The
9969       // getCopyFromParts function, called earlier, is swapping the order of
9970       // the operands to BUILD_PAIR depending on endianness. The result of
9971       // that swapping is that the least significant bits of the argument will
9972       // be in the first operand of the BUILD_PAIR node, and the most
9973       // significant bits will be in the second operand.
9974       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9975       if (LoadSDNode *LNode =
9976           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9977         if (FrameIndexSDNode *FI =
9978             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9979           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9980     }
9981 
9982     // Analyses past this point are naive and don't expect an assertion.
9983     if (Res.getOpcode() == ISD::AssertZext)
9984       Res = Res.getOperand(0);
9985 
9986     // Update the SwiftErrorVRegDefMap.
9987     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9988       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9989       if (Register::isVirtualRegister(Reg))
9990         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9991                                    Reg);
9992     }
9993 
9994     // If this argument is live outside of the entry block, insert a copy from
9995     // wherever we got it to the vreg that other BB's will reference it as.
9996     if (Res.getOpcode() == ISD::CopyFromReg) {
9997       // If we can, though, try to skip creating an unnecessary vreg.
9998       // FIXME: This isn't very clean... it would be nice to make this more
9999       // general.
10000       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
10001       if (Register::isVirtualRegister(Reg)) {
10002         FuncInfo->ValueMap[&Arg] = Reg;
10003         continue;
10004       }
10005     }
10006     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
10007       FuncInfo->InitializeRegForValue(&Arg);
10008       SDB->CopyToExportRegsIfNeeded(&Arg);
10009     }
10010   }
10011 
10012   if (!Chains.empty()) {
10013     Chains.push_back(NewRoot);
10014     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
10015   }
10016 
10017   DAG.setRoot(NewRoot);
10018 
10019   assert(i == InVals.size() && "Argument register count mismatch!");
10020 
10021   // If any argument copy elisions occurred and we have debug info, update the
10022   // stale frame indices used in the dbg.declare variable info table.
10023   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
10024   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
10025     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
10026       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
10027       if (I != ArgCopyElisionFrameIndexMap.end())
10028         VI.Slot = I->second;
10029     }
10030   }
10031 
10032   // Finally, if the target has anything special to do, allow it to do so.
10033   emitFunctionEntryCode();
10034 }
10035 
10036 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
10037 /// ensure constants are generated when needed.  Remember the virtual registers
10038 /// that need to be added to the Machine PHI nodes as input.  We cannot just
10039 /// directly add them, because expansion might result in multiple MBB's for one
10040 /// BB.  As such, the start of the BB might correspond to a different MBB than
10041 /// the end.
10042 void
10043 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
10044   const Instruction *TI = LLVMBB->getTerminator();
10045 
10046   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
10047 
10048   // Check PHI nodes in successors that expect a value to be available from this
10049   // block.
10050   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
10051     const BasicBlock *SuccBB = TI->getSuccessor(succ);
10052     if (!isa<PHINode>(SuccBB->begin())) continue;
10053     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
10054 
10055     // If this terminator has multiple identical successors (common for
10056     // switches), only handle each succ once.
10057     if (!SuccsHandled.insert(SuccMBB).second)
10058       continue;
10059 
10060     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
10061 
10062     // At this point we know that there is a 1-1 correspondence between LLVM PHI
10063     // nodes and Machine PHI nodes, but the incoming operands have not been
10064     // emitted yet.
10065     for (const PHINode &PN : SuccBB->phis()) {
10066       // Ignore dead phi's.
10067       if (PN.use_empty())
10068         continue;
10069 
10070       // Skip empty types
10071       if (PN.getType()->isEmptyTy())
10072         continue;
10073 
10074       unsigned Reg;
10075       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
10076 
10077       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
10078         unsigned &RegOut = ConstantsOut[C];
10079         if (RegOut == 0) {
10080           RegOut = FuncInfo.CreateRegs(C);
10081           CopyValueToVirtualRegister(C, RegOut);
10082         }
10083         Reg = RegOut;
10084       } else {
10085         DenseMap<const Value *, unsigned>::iterator I =
10086           FuncInfo.ValueMap.find(PHIOp);
10087         if (I != FuncInfo.ValueMap.end())
10088           Reg = I->second;
10089         else {
10090           assert(isa<AllocaInst>(PHIOp) &&
10091                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
10092                  "Didn't codegen value into a register!??");
10093           Reg = FuncInfo.CreateRegs(PHIOp);
10094           CopyValueToVirtualRegister(PHIOp, Reg);
10095         }
10096       }
10097 
10098       // Remember that this register needs to added to the machine PHI node as
10099       // the input for this MBB.
10100       SmallVector<EVT, 4> ValueVTs;
10101       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10102       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
10103       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
10104         EVT VT = ValueVTs[vti];
10105         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
10106         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
10107           FuncInfo.PHINodesToUpdate.push_back(
10108               std::make_pair(&*MBBI++, Reg + i));
10109         Reg += NumRegisters;
10110       }
10111     }
10112   }
10113 
10114   ConstantsOut.clear();
10115 }
10116 
10117 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
10118 /// is 0.
10119 MachineBasicBlock *
10120 SelectionDAGBuilder::StackProtectorDescriptor::
10121 AddSuccessorMBB(const BasicBlock *BB,
10122                 MachineBasicBlock *ParentMBB,
10123                 bool IsLikely,
10124                 MachineBasicBlock *SuccMBB) {
10125   // If SuccBB has not been created yet, create it.
10126   if (!SuccMBB) {
10127     MachineFunction *MF = ParentMBB->getParent();
10128     MachineFunction::iterator BBI(ParentMBB);
10129     SuccMBB = MF->CreateMachineBasicBlock(BB);
10130     MF->insert(++BBI, SuccMBB);
10131   }
10132   // Add it as a successor of ParentMBB.
10133   ParentMBB->addSuccessor(
10134       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
10135   return SuccMBB;
10136 }
10137 
10138 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
10139   MachineFunction::iterator I(MBB);
10140   if (++I == FuncInfo.MF->end())
10141     return nullptr;
10142   return &*I;
10143 }
10144 
10145 /// During lowering new call nodes can be created (such as memset, etc.).
10146 /// Those will become new roots of the current DAG, but complications arise
10147 /// when they are tail calls. In such cases, the call lowering will update
10148 /// the root, but the builder still needs to know that a tail call has been
10149 /// lowered in order to avoid generating an additional return.
10150 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
10151   // If the node is null, we do have a tail call.
10152   if (MaybeTC.getNode() != nullptr)
10153     DAG.setRoot(MaybeTC);
10154   else
10155     HasTailCall = true;
10156 }
10157 
10158 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10159                                         MachineBasicBlock *SwitchMBB,
10160                                         MachineBasicBlock *DefaultMBB) {
10161   MachineFunction *CurMF = FuncInfo.MF;
10162   MachineBasicBlock *NextMBB = nullptr;
10163   MachineFunction::iterator BBI(W.MBB);
10164   if (++BBI != FuncInfo.MF->end())
10165     NextMBB = &*BBI;
10166 
10167   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10168 
10169   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10170 
10171   if (Size == 2 && W.MBB == SwitchMBB) {
10172     // If any two of the cases has the same destination, and if one value
10173     // is the same as the other, but has one bit unset that the other has set,
10174     // use bit manipulation to do two compares at once.  For example:
10175     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10176     // TODO: This could be extended to merge any 2 cases in switches with 3
10177     // cases.
10178     // TODO: Handle cases where W.CaseBB != SwitchBB.
10179     CaseCluster &Small = *W.FirstCluster;
10180     CaseCluster &Big = *W.LastCluster;
10181 
10182     if (Small.Low == Small.High && Big.Low == Big.High &&
10183         Small.MBB == Big.MBB) {
10184       const APInt &SmallValue = Small.Low->getValue();
10185       const APInt &BigValue = Big.Low->getValue();
10186 
10187       // Check that there is only one bit different.
10188       APInt CommonBit = BigValue ^ SmallValue;
10189       if (CommonBit.isPowerOf2()) {
10190         SDValue CondLHS = getValue(Cond);
10191         EVT VT = CondLHS.getValueType();
10192         SDLoc DL = getCurSDLoc();
10193 
10194         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10195                                  DAG.getConstant(CommonBit, DL, VT));
10196         SDValue Cond = DAG.getSetCC(
10197             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10198             ISD::SETEQ);
10199 
10200         // Update successor info.
10201         // Both Small and Big will jump to Small.BB, so we sum up the
10202         // probabilities.
10203         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10204         if (BPI)
10205           addSuccessorWithProb(
10206               SwitchMBB, DefaultMBB,
10207               // The default destination is the first successor in IR.
10208               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10209         else
10210           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10211 
10212         // Insert the true branch.
10213         SDValue BrCond =
10214             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10215                         DAG.getBasicBlock(Small.MBB));
10216         // Insert the false branch.
10217         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10218                              DAG.getBasicBlock(DefaultMBB));
10219 
10220         DAG.setRoot(BrCond);
10221         return;
10222       }
10223     }
10224   }
10225 
10226   if (TM.getOptLevel() != CodeGenOpt::None) {
10227     // Here, we order cases by probability so the most likely case will be
10228     // checked first. However, two clusters can have the same probability in
10229     // which case their relative ordering is non-deterministic. So we use Low
10230     // as a tie-breaker as clusters are guaranteed to never overlap.
10231     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10232                [](const CaseCluster &a, const CaseCluster &b) {
10233       return a.Prob != b.Prob ?
10234              a.Prob > b.Prob :
10235              a.Low->getValue().slt(b.Low->getValue());
10236     });
10237 
10238     // Rearrange the case blocks so that the last one falls through if possible
10239     // without changing the order of probabilities.
10240     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10241       --I;
10242       if (I->Prob > W.LastCluster->Prob)
10243         break;
10244       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10245         std::swap(*I, *W.LastCluster);
10246         break;
10247       }
10248     }
10249   }
10250 
10251   // Compute total probability.
10252   BranchProbability DefaultProb = W.DefaultProb;
10253   BranchProbability UnhandledProbs = DefaultProb;
10254   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10255     UnhandledProbs += I->Prob;
10256 
10257   MachineBasicBlock *CurMBB = W.MBB;
10258   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10259     bool FallthroughUnreachable = false;
10260     MachineBasicBlock *Fallthrough;
10261     if (I == W.LastCluster) {
10262       // For the last cluster, fall through to the default destination.
10263       Fallthrough = DefaultMBB;
10264       FallthroughUnreachable = isa<UnreachableInst>(
10265           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10266     } else {
10267       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10268       CurMF->insert(BBI, Fallthrough);
10269       // Put Cond in a virtual register to make it available from the new blocks.
10270       ExportFromCurrentBlock(Cond);
10271     }
10272     UnhandledProbs -= I->Prob;
10273 
10274     switch (I->Kind) {
10275       case CC_JumpTable: {
10276         // FIXME: Optimize away range check based on pivot comparisons.
10277         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10278         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10279 
10280         // The jump block hasn't been inserted yet; insert it here.
10281         MachineBasicBlock *JumpMBB = JT->MBB;
10282         CurMF->insert(BBI, JumpMBB);
10283 
10284         auto JumpProb = I->Prob;
10285         auto FallthroughProb = UnhandledProbs;
10286 
10287         // If the default statement is a target of the jump table, we evenly
10288         // distribute the default probability to successors of CurMBB. Also
10289         // update the probability on the edge from JumpMBB to Fallthrough.
10290         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10291                                               SE = JumpMBB->succ_end();
10292              SI != SE; ++SI) {
10293           if (*SI == DefaultMBB) {
10294             JumpProb += DefaultProb / 2;
10295             FallthroughProb -= DefaultProb / 2;
10296             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10297             JumpMBB->normalizeSuccProbs();
10298             break;
10299           }
10300         }
10301 
10302         if (FallthroughUnreachable) {
10303           // Skip the range check if the fallthrough block is unreachable.
10304           JTH->OmitRangeCheck = true;
10305         }
10306 
10307         if (!JTH->OmitRangeCheck)
10308           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10309         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10310         CurMBB->normalizeSuccProbs();
10311 
10312         // The jump table header will be inserted in our current block, do the
10313         // range check, and fall through to our fallthrough block.
10314         JTH->HeaderBB = CurMBB;
10315         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10316 
10317         // If we're in the right place, emit the jump table header right now.
10318         if (CurMBB == SwitchMBB) {
10319           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10320           JTH->Emitted = true;
10321         }
10322         break;
10323       }
10324       case CC_BitTests: {
10325         // FIXME: Optimize away range check based on pivot comparisons.
10326         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10327 
10328         // The bit test blocks haven't been inserted yet; insert them here.
10329         for (BitTestCase &BTC : BTB->Cases)
10330           CurMF->insert(BBI, BTC.ThisBB);
10331 
10332         // Fill in fields of the BitTestBlock.
10333         BTB->Parent = CurMBB;
10334         BTB->Default = Fallthrough;
10335 
10336         BTB->DefaultProb = UnhandledProbs;
10337         // If the cases in bit test don't form a contiguous range, we evenly
10338         // distribute the probability on the edge to Fallthrough to two
10339         // successors of CurMBB.
10340         if (!BTB->ContiguousRange) {
10341           BTB->Prob += DefaultProb / 2;
10342           BTB->DefaultProb -= DefaultProb / 2;
10343         }
10344 
10345         if (FallthroughUnreachable) {
10346           // Skip the range check if the fallthrough block is unreachable.
10347           BTB->OmitRangeCheck = true;
10348         }
10349 
10350         // If we're in the right place, emit the bit test header right now.
10351         if (CurMBB == SwitchMBB) {
10352           visitBitTestHeader(*BTB, SwitchMBB);
10353           BTB->Emitted = true;
10354         }
10355         break;
10356       }
10357       case CC_Range: {
10358         const Value *RHS, *LHS, *MHS;
10359         ISD::CondCode CC;
10360         if (I->Low == I->High) {
10361           // Check Cond == I->Low.
10362           CC = ISD::SETEQ;
10363           LHS = Cond;
10364           RHS=I->Low;
10365           MHS = nullptr;
10366         } else {
10367           // Check I->Low <= Cond <= I->High.
10368           CC = ISD::SETLE;
10369           LHS = I->Low;
10370           MHS = Cond;
10371           RHS = I->High;
10372         }
10373 
10374         // If Fallthrough is unreachable, fold away the comparison.
10375         if (FallthroughUnreachable)
10376           CC = ISD::SETTRUE;
10377 
10378         // The false probability is the sum of all unhandled cases.
10379         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10380                      getCurSDLoc(), I->Prob, UnhandledProbs);
10381 
10382         if (CurMBB == SwitchMBB)
10383           visitSwitchCase(CB, SwitchMBB);
10384         else
10385           SL->SwitchCases.push_back(CB);
10386 
10387         break;
10388       }
10389     }
10390     CurMBB = Fallthrough;
10391   }
10392 }
10393 
10394 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10395                                               CaseClusterIt First,
10396                                               CaseClusterIt Last) {
10397   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10398     if (X.Prob != CC.Prob)
10399       return X.Prob > CC.Prob;
10400 
10401     // Ties are broken by comparing the case value.
10402     return X.Low->getValue().slt(CC.Low->getValue());
10403   });
10404 }
10405 
10406 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10407                                         const SwitchWorkListItem &W,
10408                                         Value *Cond,
10409                                         MachineBasicBlock *SwitchMBB) {
10410   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10411          "Clusters not sorted?");
10412 
10413   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10414 
10415   // Balance the tree based on branch probabilities to create a near-optimal (in
10416   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10417   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10418   CaseClusterIt LastLeft = W.FirstCluster;
10419   CaseClusterIt FirstRight = W.LastCluster;
10420   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10421   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10422 
10423   // Move LastLeft and FirstRight towards each other from opposite directions to
10424   // find a partitioning of the clusters which balances the probability on both
10425   // sides. If LeftProb and RightProb are equal, alternate which side is
10426   // taken to ensure 0-probability nodes are distributed evenly.
10427   unsigned I = 0;
10428   while (LastLeft + 1 < FirstRight) {
10429     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10430       LeftProb += (++LastLeft)->Prob;
10431     else
10432       RightProb += (--FirstRight)->Prob;
10433     I++;
10434   }
10435 
10436   while (true) {
10437     // Our binary search tree differs from a typical BST in that ours can have up
10438     // to three values in each leaf. The pivot selection above doesn't take that
10439     // into account, which means the tree might require more nodes and be less
10440     // efficient. We compensate for this here.
10441 
10442     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10443     unsigned NumRight = W.LastCluster - FirstRight + 1;
10444 
10445     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10446       // If one side has less than 3 clusters, and the other has more than 3,
10447       // consider taking a cluster from the other side.
10448 
10449       if (NumLeft < NumRight) {
10450         // Consider moving the first cluster on the right to the left side.
10451         CaseCluster &CC = *FirstRight;
10452         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10453         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10454         if (LeftSideRank <= RightSideRank) {
10455           // Moving the cluster to the left does not demote it.
10456           ++LastLeft;
10457           ++FirstRight;
10458           continue;
10459         }
10460       } else {
10461         assert(NumRight < NumLeft);
10462         // Consider moving the last element on the left to the right side.
10463         CaseCluster &CC = *LastLeft;
10464         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10465         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10466         if (RightSideRank <= LeftSideRank) {
10467           // Moving the cluster to the right does not demot it.
10468           --LastLeft;
10469           --FirstRight;
10470           continue;
10471         }
10472       }
10473     }
10474     break;
10475   }
10476 
10477   assert(LastLeft + 1 == FirstRight);
10478   assert(LastLeft >= W.FirstCluster);
10479   assert(FirstRight <= W.LastCluster);
10480 
10481   // Use the first element on the right as pivot since we will make less-than
10482   // comparisons against it.
10483   CaseClusterIt PivotCluster = FirstRight;
10484   assert(PivotCluster > W.FirstCluster);
10485   assert(PivotCluster <= W.LastCluster);
10486 
10487   CaseClusterIt FirstLeft = W.FirstCluster;
10488   CaseClusterIt LastRight = W.LastCluster;
10489 
10490   const ConstantInt *Pivot = PivotCluster->Low;
10491 
10492   // New blocks will be inserted immediately after the current one.
10493   MachineFunction::iterator BBI(W.MBB);
10494   ++BBI;
10495 
10496   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10497   // we can branch to its destination directly if it's squeezed exactly in
10498   // between the known lower bound and Pivot - 1.
10499   MachineBasicBlock *LeftMBB;
10500   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10501       FirstLeft->Low == W.GE &&
10502       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10503     LeftMBB = FirstLeft->MBB;
10504   } else {
10505     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10506     FuncInfo.MF->insert(BBI, LeftMBB);
10507     WorkList.push_back(
10508         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10509     // Put Cond in a virtual register to make it available from the new blocks.
10510     ExportFromCurrentBlock(Cond);
10511   }
10512 
10513   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10514   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10515   // directly if RHS.High equals the current upper bound.
10516   MachineBasicBlock *RightMBB;
10517   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10518       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10519     RightMBB = FirstRight->MBB;
10520   } else {
10521     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10522     FuncInfo.MF->insert(BBI, RightMBB);
10523     WorkList.push_back(
10524         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10525     // Put Cond in a virtual register to make it available from the new blocks.
10526     ExportFromCurrentBlock(Cond);
10527   }
10528 
10529   // Create the CaseBlock record that will be used to lower the branch.
10530   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10531                getCurSDLoc(), LeftProb, RightProb);
10532 
10533   if (W.MBB == SwitchMBB)
10534     visitSwitchCase(CB, SwitchMBB);
10535   else
10536     SL->SwitchCases.push_back(CB);
10537 }
10538 
10539 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10540 // from the swith statement.
10541 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10542                                             BranchProbability PeeledCaseProb) {
10543   if (PeeledCaseProb == BranchProbability::getOne())
10544     return BranchProbability::getZero();
10545   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10546 
10547   uint32_t Numerator = CaseProb.getNumerator();
10548   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10549   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10550 }
10551 
10552 // Try to peel the top probability case if it exceeds the threshold.
10553 // Return current MachineBasicBlock for the switch statement if the peeling
10554 // does not occur.
10555 // If the peeling is performed, return the newly created MachineBasicBlock
10556 // for the peeled switch statement. Also update Clusters to remove the peeled
10557 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10558 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10559     const SwitchInst &SI, CaseClusterVector &Clusters,
10560     BranchProbability &PeeledCaseProb) {
10561   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10562   // Don't perform if there is only one cluster or optimizing for size.
10563   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10564       TM.getOptLevel() == CodeGenOpt::None ||
10565       SwitchMBB->getParent()->getFunction().hasMinSize())
10566     return SwitchMBB;
10567 
10568   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10569   unsigned PeeledCaseIndex = 0;
10570   bool SwitchPeeled = false;
10571   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10572     CaseCluster &CC = Clusters[Index];
10573     if (CC.Prob < TopCaseProb)
10574       continue;
10575     TopCaseProb = CC.Prob;
10576     PeeledCaseIndex = Index;
10577     SwitchPeeled = true;
10578   }
10579   if (!SwitchPeeled)
10580     return SwitchMBB;
10581 
10582   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10583                     << TopCaseProb << "\n");
10584 
10585   // Record the MBB for the peeled switch statement.
10586   MachineFunction::iterator BBI(SwitchMBB);
10587   ++BBI;
10588   MachineBasicBlock *PeeledSwitchMBB =
10589       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10590   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10591 
10592   ExportFromCurrentBlock(SI.getCondition());
10593   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10594   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10595                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10596   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10597 
10598   Clusters.erase(PeeledCaseIt);
10599   for (CaseCluster &CC : Clusters) {
10600     LLVM_DEBUG(
10601         dbgs() << "Scale the probablity for one cluster, before scaling: "
10602                << CC.Prob << "\n");
10603     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10604     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10605   }
10606   PeeledCaseProb = TopCaseProb;
10607   return PeeledSwitchMBB;
10608 }
10609 
10610 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10611   // Extract cases from the switch.
10612   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10613   CaseClusterVector Clusters;
10614   Clusters.reserve(SI.getNumCases());
10615   for (auto I : SI.cases()) {
10616     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10617     const ConstantInt *CaseVal = I.getCaseValue();
10618     BranchProbability Prob =
10619         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10620             : BranchProbability(1, SI.getNumCases() + 1);
10621     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10622   }
10623 
10624   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10625 
10626   // Cluster adjacent cases with the same destination. We do this at all
10627   // optimization levels because it's cheap to do and will make codegen faster
10628   // if there are many clusters.
10629   sortAndRangeify(Clusters);
10630 
10631   // The branch probablity of the peeled case.
10632   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10633   MachineBasicBlock *PeeledSwitchMBB =
10634       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10635 
10636   // If there is only the default destination, jump there directly.
10637   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10638   if (Clusters.empty()) {
10639     assert(PeeledSwitchMBB == SwitchMBB);
10640     SwitchMBB->addSuccessor(DefaultMBB);
10641     if (DefaultMBB != NextBlock(SwitchMBB)) {
10642       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10643                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10644     }
10645     return;
10646   }
10647 
10648   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10649   SL->findBitTestClusters(Clusters, &SI);
10650 
10651   LLVM_DEBUG({
10652     dbgs() << "Case clusters: ";
10653     for (const CaseCluster &C : Clusters) {
10654       if (C.Kind == CC_JumpTable)
10655         dbgs() << "JT:";
10656       if (C.Kind == CC_BitTests)
10657         dbgs() << "BT:";
10658 
10659       C.Low->getValue().print(dbgs(), true);
10660       if (C.Low != C.High) {
10661         dbgs() << '-';
10662         C.High->getValue().print(dbgs(), true);
10663       }
10664       dbgs() << ' ';
10665     }
10666     dbgs() << '\n';
10667   });
10668 
10669   assert(!Clusters.empty());
10670   SwitchWorkList WorkList;
10671   CaseClusterIt First = Clusters.begin();
10672   CaseClusterIt Last = Clusters.end() - 1;
10673   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10674   // Scale the branchprobability for DefaultMBB if the peel occurs and
10675   // DefaultMBB is not replaced.
10676   if (PeeledCaseProb != BranchProbability::getZero() &&
10677       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10678     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10679   WorkList.push_back(
10680       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10681 
10682   while (!WorkList.empty()) {
10683     SwitchWorkListItem W = WorkList.back();
10684     WorkList.pop_back();
10685     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10686 
10687     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10688         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10689       // For optimized builds, lower large range as a balanced binary tree.
10690       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10691       continue;
10692     }
10693 
10694     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10695   }
10696 }
10697 
10698 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10699   SDValue N = getValue(I.getOperand(0));
10700   setValue(&I, N);
10701 }
10702