xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 11448eeb72e1392f9f4ad072866c2c6dc82d14bc)
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(
442           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
443           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
444     }
445 
446     // Vector/Vector bitcast.
447     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
448       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
449 
450     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
451       "Cannot handle this kind of promotion");
452     // Promoted vector extract
453     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
454 
455   }
456 
457   // Trivial bitcast if the types are the same size and the destination
458   // vector type is legal.
459   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
460       TLI.isTypeLegal(ValueVT))
461     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
462 
463   if (ValueVT.getVectorNumElements() != 1) {
464      // Certain ABIs require that vectors are passed as integers. For vectors
465      // are the same size, this is an obvious bitcast.
466      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
467        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
468      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
469        // Bitcast Val back the original type and extract the corresponding
470        // vector we want.
471        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
472        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
473                                            ValueVT.getVectorElementType(), Elts);
474        Val = DAG.getBitcast(WiderVecType, Val);
475        return DAG.getNode(
476            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
477            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
478      }
479 
480      diagnosePossiblyInvalidConstraint(
481          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
482      return DAG.getUNDEF(ValueVT);
483   }
484 
485   // Handle cases such as i8 -> <1 x i1>
486   EVT ValueSVT = ValueVT.getVectorElementType();
487   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
488     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
489                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
490 
491   return DAG.getBuildVector(ValueVT, DL, Val);
492 }
493 
494 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
495                                  SDValue Val, SDValue *Parts, unsigned NumParts,
496                                  MVT PartVT, const Value *V,
497                                  Optional<CallingConv::ID> CallConv);
498 
499 /// getCopyToParts - Create a series of nodes that contain the specified value
500 /// split into legal parts.  If the parts contain more bits than Val, then, for
501 /// integers, ExtendKind can be used to specify how to generate the extra bits.
502 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
503                            SDValue *Parts, unsigned NumParts, MVT PartVT,
504                            const Value *V,
505                            Optional<CallingConv::ID> CallConv = None,
506                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
507   EVT ValueVT = Val.getValueType();
508 
509   // Handle the vector case separately.
510   if (ValueVT.isVector())
511     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
512                                 CallConv);
513 
514   unsigned PartBits = PartVT.getSizeInBits();
515   unsigned OrigNumParts = NumParts;
516   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
517          "Copying to an illegal type!");
518 
519   if (NumParts == 0)
520     return;
521 
522   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
523   EVT PartEVT = PartVT;
524   if (PartEVT == ValueVT) {
525     assert(NumParts == 1 && "No-op copy with multiple parts!");
526     Parts[0] = Val;
527     return;
528   }
529 
530   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
531     // If the parts cover more bits than the value has, promote the value.
532     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
533       assert(NumParts == 1 && "Do not know what to promote to!");
534       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
535     } else {
536       if (ValueVT.isFloatingPoint()) {
537         // FP values need to be bitcast, then extended if they are being put
538         // into a larger container.
539         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
540         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
541       }
542       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
543              ValueVT.isInteger() &&
544              "Unknown mismatch!");
545       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
546       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
547       if (PartVT == MVT::x86mmx)
548         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549     }
550   } else if (PartBits == ValueVT.getSizeInBits()) {
551     // Different types of the same size.
552     assert(NumParts == 1 && PartEVT != ValueVT);
553     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
554   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
555     // If the parts cover less bits than value has, truncate the value.
556     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
557            ValueVT.isInteger() &&
558            "Unknown mismatch!");
559     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
560     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
561     if (PartVT == MVT::x86mmx)
562       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   }
564 
565   // The value may have changed - recompute ValueVT.
566   ValueVT = Val.getValueType();
567   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
568          "Failed to tile the value with PartVT!");
569 
570   if (NumParts == 1) {
571     if (PartEVT != ValueVT) {
572       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
573                                         "scalar-to-vector conversion failed");
574       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
575     }
576 
577     Parts[0] = Val;
578     return;
579   }
580 
581   // Expand the value into multiple parts.
582   if (NumParts & (NumParts - 1)) {
583     // The number of parts is not a power of 2.  Split off and copy the tail.
584     assert(PartVT.isInteger() && ValueVT.isInteger() &&
585            "Do not know what to expand to!");
586     unsigned RoundParts = 1 << Log2_32(NumParts);
587     unsigned RoundBits = RoundParts * PartBits;
588     unsigned OddParts = NumParts - RoundParts;
589     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
590       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
591 
592     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
593                    CallConv);
594 
595     if (DAG.getDataLayout().isBigEndian())
596       // The odd parts were reversed by getCopyToParts - unreverse them.
597       std::reverse(Parts + RoundParts, Parts + NumParts);
598 
599     NumParts = RoundParts;
600     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
601     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
602   }
603 
604   // The number of parts is a power of 2.  Repeatedly bisect the value using
605   // EXTRACT_ELEMENT.
606   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
607                          EVT::getIntegerVT(*DAG.getContext(),
608                                            ValueVT.getSizeInBits()),
609                          Val);
610 
611   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
612     for (unsigned i = 0; i < NumParts; i += StepSize) {
613       unsigned ThisBits = StepSize * PartBits / 2;
614       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
615       SDValue &Part0 = Parts[i];
616       SDValue &Part1 = Parts[i+StepSize/2];
617 
618       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
619                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
620       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
621                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
622 
623       if (ThisBits == PartBits && ThisVT != PartVT) {
624         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
625         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
626       }
627     }
628   }
629 
630   if (DAG.getDataLayout().isBigEndian())
631     std::reverse(Parts, Parts + OrigNumParts);
632 }
633 
634 static SDValue widenVectorToPartType(SelectionDAG &DAG,
635                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
636   if (!PartVT.isVector())
637     return SDValue();
638 
639   EVT ValueVT = Val.getValueType();
640   unsigned PartNumElts = PartVT.getVectorNumElements();
641   unsigned ValueNumElts = ValueVT.getVectorNumElements();
642   if (PartNumElts > ValueNumElts &&
643       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
644     EVT ElementVT = PartVT.getVectorElementType();
645     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
646     // undef elements.
647     SmallVector<SDValue, 16> Ops;
648     DAG.ExtractVectorElements(Val, Ops);
649     SDValue EltUndef = DAG.getUNDEF(ElementVT);
650     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
651       Ops.push_back(EltUndef);
652 
653     // FIXME: Use CONCAT for 2x -> 4x.
654     return DAG.getBuildVector(PartVT, DL, Ops);
655   }
656 
657   return SDValue();
658 }
659 
660 /// getCopyToPartsVector - Create a series of nodes that contain the specified
661 /// value split into legal parts.
662 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
663                                  SDValue Val, SDValue *Parts, unsigned NumParts,
664                                  MVT PartVT, const Value *V,
665                                  Optional<CallingConv::ID> CallConv) {
666   EVT ValueVT = Val.getValueType();
667   assert(ValueVT.isVector() && "Not a vector");
668   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
669   const bool IsABIRegCopy = CallConv.hasValue();
670 
671   if (NumParts == 1) {
672     EVT PartEVT = PartVT;
673     if (PartEVT == ValueVT) {
674       // Nothing to do.
675     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
676       // Bitconvert vector->vector case.
677       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
678     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
679       Val = Widened;
680     } else if (PartVT.isVector() &&
681                PartEVT.getVectorElementType().bitsGE(
682                  ValueVT.getVectorElementType()) &&
683                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
684 
685       // Promoted vector extract
686       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
687     } else {
688       if (ValueVT.getVectorNumElements() == 1) {
689         Val = DAG.getNode(
690             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
691             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
692       } else {
693         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
694                "lossy conversion of vector to scalar type");
695         EVT IntermediateType =
696             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
697         Val = DAG.getBitcast(IntermediateType, Val);
698         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
699       }
700     }
701 
702     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
703     Parts[0] = Val;
704     return;
705   }
706 
707   // Handle a multi-element vector.
708   EVT IntermediateVT;
709   MVT RegisterVT;
710   unsigned NumIntermediates;
711   unsigned NumRegs;
712   if (IsABIRegCopy) {
713     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
714         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
715         NumIntermediates, RegisterVT);
716   } else {
717     NumRegs =
718         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
719                                    NumIntermediates, RegisterVT);
720   }
721 
722   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
723   NumParts = NumRegs; // Silence a compiler warning.
724   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
725 
726   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
727     IntermediateVT.getVectorNumElements() : 1;
728 
729   // Convert the vector to the appropriate type if necessary.
730   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
731 
732   EVT BuiltVectorTy = EVT::getVectorVT(
733       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
734   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
735   if (ValueVT != BuiltVectorTy) {
736     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
737       Val = Widened;
738 
739     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
740   }
741 
742   // Split the vector into intermediate operands.
743   SmallVector<SDValue, 8> Ops(NumIntermediates);
744   for (unsigned i = 0; i != NumIntermediates; ++i) {
745     if (IntermediateVT.isVector()) {
746       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
747                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
748     } else {
749       Ops[i] = DAG.getNode(
750           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
751           DAG.getConstant(i, DL, IdxVT));
752     }
753   }
754 
755   // Split the intermediate operands into legal parts.
756   if (NumParts == NumIntermediates) {
757     // If the register was not expanded, promote or copy the value,
758     // as appropriate.
759     for (unsigned i = 0; i != NumParts; ++i)
760       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
761   } else if (NumParts > 0) {
762     // If the intermediate type was expanded, split each the value into
763     // legal parts.
764     assert(NumIntermediates != 0 && "division by zero");
765     assert(NumParts % NumIntermediates == 0 &&
766            "Must expand into a divisible number of parts!");
767     unsigned Factor = NumParts / NumIntermediates;
768     for (unsigned i = 0; i != NumIntermediates; ++i)
769       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
770                      CallConv);
771   }
772 }
773 
774 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
775                            EVT valuevt, Optional<CallingConv::ID> CC)
776     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
777       RegCount(1, regs.size()), CallConv(CC) {}
778 
779 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
780                            const DataLayout &DL, unsigned Reg, Type *Ty,
781                            Optional<CallingConv::ID> CC) {
782   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
783 
784   CallConv = CC;
785 
786   for (EVT ValueVT : ValueVTs) {
787     unsigned NumRegs =
788         isABIMangled()
789             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
790             : TLI.getNumRegisters(Context, ValueVT);
791     MVT RegisterVT =
792         isABIMangled()
793             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
794             : TLI.getRegisterType(Context, ValueVT);
795     for (unsigned i = 0; i != NumRegs; ++i)
796       Regs.push_back(Reg + i);
797     RegVTs.push_back(RegisterVT);
798     RegCount.push_back(NumRegs);
799     Reg += NumRegs;
800   }
801 }
802 
803 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
804                                       FunctionLoweringInfo &FuncInfo,
805                                       const SDLoc &dl, SDValue &Chain,
806                                       SDValue *Flag, const Value *V) const {
807   // A Value with type {} or [0 x %t] needs no registers.
808   if (ValueVTs.empty())
809     return SDValue();
810 
811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
812 
813   // Assemble the legal parts into the final values.
814   SmallVector<SDValue, 4> Values(ValueVTs.size());
815   SmallVector<SDValue, 8> Parts;
816   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
817     // Copy the legal parts from the registers.
818     EVT ValueVT = ValueVTs[Value];
819     unsigned NumRegs = RegCount[Value];
820     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
821                                           *DAG.getContext(),
822                                           CallConv.getValue(), RegVTs[Value])
823                                     : RegVTs[Value];
824 
825     Parts.resize(NumRegs);
826     for (unsigned i = 0; i != NumRegs; ++i) {
827       SDValue P;
828       if (!Flag) {
829         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
830       } else {
831         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
832         *Flag = P.getValue(2);
833       }
834 
835       Chain = P.getValue(1);
836       Parts[i] = P;
837 
838       // If the source register was virtual and if we know something about it,
839       // add an assert node.
840       if (!Register::isVirtualRegister(Regs[Part + i]) ||
841           !RegisterVT.isInteger())
842         continue;
843 
844       const FunctionLoweringInfo::LiveOutInfo *LOI =
845         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
846       if (!LOI)
847         continue;
848 
849       unsigned RegSize = RegisterVT.getScalarSizeInBits();
850       unsigned NumSignBits = LOI->NumSignBits;
851       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
852 
853       if (NumZeroBits == RegSize) {
854         // The current value is a zero.
855         // Explicitly express that as it would be easier for
856         // optimizations to kick in.
857         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
858         continue;
859       }
860 
861       // FIXME: We capture more information than the dag can represent.  For
862       // now, just use the tightest assertzext/assertsext possible.
863       bool isSExt;
864       EVT FromVT(MVT::Other);
865       if (NumZeroBits) {
866         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
867         isSExt = false;
868       } else if (NumSignBits > 1) {
869         FromVT =
870             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
871         isSExt = true;
872       } else {
873         continue;
874       }
875       // Add an assertion node.
876       assert(FromVT != MVT::Other);
877       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
878                              RegisterVT, P, DAG.getValueType(FromVT));
879     }
880 
881     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
882                                      RegisterVT, ValueVT, V, CallConv);
883     Part += NumRegs;
884     Parts.clear();
885   }
886 
887   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
888 }
889 
890 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
891                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
892                                  const Value *V,
893                                  ISD::NodeType PreferredExtendType) const {
894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
895   ISD::NodeType ExtendKind = PreferredExtendType;
896 
897   // Get the list of the values's legal parts.
898   unsigned NumRegs = Regs.size();
899   SmallVector<SDValue, 8> Parts(NumRegs);
900   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
901     unsigned NumParts = RegCount[Value];
902 
903     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
904                                           *DAG.getContext(),
905                                           CallConv.getValue(), RegVTs[Value])
906                                     : RegVTs[Value];
907 
908     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
909       ExtendKind = ISD::ZERO_EXTEND;
910 
911     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
912                    NumParts, RegisterVT, V, CallConv, ExtendKind);
913     Part += NumParts;
914   }
915 
916   // Copy the parts into the registers.
917   SmallVector<SDValue, 8> Chains(NumRegs);
918   for (unsigned i = 0; i != NumRegs; ++i) {
919     SDValue Part;
920     if (!Flag) {
921       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
922     } else {
923       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
924       *Flag = Part.getValue(1);
925     }
926 
927     Chains[i] = Part.getValue(0);
928   }
929 
930   if (NumRegs == 1 || Flag)
931     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
932     // flagged to it. That is the CopyToReg nodes and the user are considered
933     // a single scheduling unit. If we create a TokenFactor and return it as
934     // chain, then the TokenFactor is both a predecessor (operand) of the
935     // user as well as a successor (the TF operands are flagged to the user).
936     // c1, f1 = CopyToReg
937     // c2, f2 = CopyToReg
938     // c3     = TokenFactor c1, c2
939     // ...
940     //        = op c3, ..., f2
941     Chain = Chains[NumRegs-1];
942   else
943     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
944 }
945 
946 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
947                                         unsigned MatchingIdx, const SDLoc &dl,
948                                         SelectionDAG &DAG,
949                                         std::vector<SDValue> &Ops) const {
950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
951 
952   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
953   if (HasMatching)
954     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
955   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
956     // Put the register class of the virtual registers in the flag word.  That
957     // way, later passes can recompute register class constraints for inline
958     // assembly as well as normal instructions.
959     // Don't do this for tied operands that can use the regclass information
960     // from the def.
961     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
962     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
963     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
964   }
965 
966   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
967   Ops.push_back(Res);
968 
969   if (Code == InlineAsm::Kind_Clobber) {
970     // Clobbers should always have a 1:1 mapping with registers, and may
971     // reference registers that have illegal (e.g. vector) types. Hence, we
972     // shouldn't try to apply any sort of splitting logic to them.
973     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
974            "No 1:1 mapping from clobbers to regs?");
975     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
976     (void)SP;
977     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
978       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
979       assert(
980           (Regs[I] != SP ||
981            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
982           "If we clobbered the stack pointer, MFI should know about it.");
983     }
984     return;
985   }
986 
987   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
988     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
989     MVT RegisterVT = RegVTs[Value];
990     for (unsigned i = 0; i != NumRegs; ++i) {
991       assert(Reg < Regs.size() && "Mismatch in # registers expected");
992       unsigned TheReg = Regs[Reg++];
993       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
994     }
995   }
996 }
997 
998 SmallVector<std::pair<unsigned, unsigned>, 4>
999 RegsForValue::getRegsAndSizes() const {
1000   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
1001   unsigned I = 0;
1002   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1003     unsigned RegCount = std::get<0>(CountAndVT);
1004     MVT RegisterVT = std::get<1>(CountAndVT);
1005     unsigned RegisterSize = RegisterVT.getSizeInBits();
1006     for (unsigned E = I + RegCount; I != E; ++I)
1007       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1008   }
1009   return OutVec;
1010 }
1011 
1012 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1013                                const TargetLibraryInfo *li) {
1014   AA = aa;
1015   GFI = gfi;
1016   LibInfo = li;
1017   DL = &DAG.getDataLayout();
1018   Context = DAG.getContext();
1019   LPadToCallSiteMap.clear();
1020   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1021 }
1022 
1023 void SelectionDAGBuilder::clear() {
1024   NodeMap.clear();
1025   UnusedArgNodeMap.clear();
1026   PendingLoads.clear();
1027   PendingExports.clear();
1028   CurInst = nullptr;
1029   HasTailCall = false;
1030   SDNodeOrder = LowestSDNodeOrder;
1031   StatepointLowering.clear();
1032 }
1033 
1034 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1035   DanglingDebugInfoMap.clear();
1036 }
1037 
1038 SDValue SelectionDAGBuilder::getRoot() {
1039   if (PendingLoads.empty())
1040     return DAG.getRoot();
1041 
1042   if (PendingLoads.size() == 1) {
1043     SDValue Root = PendingLoads[0];
1044     DAG.setRoot(Root);
1045     PendingLoads.clear();
1046     return Root;
1047   }
1048 
1049   // Otherwise, we have to make a token factor node.
1050   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1051   PendingLoads.clear();
1052   DAG.setRoot(Root);
1053   return Root;
1054 }
1055 
1056 SDValue SelectionDAGBuilder::getControlRoot() {
1057   SDValue Root = DAG.getRoot();
1058 
1059   if (PendingExports.empty())
1060     return Root;
1061 
1062   // Turn all of the CopyToReg chains into one factored node.
1063   if (Root.getOpcode() != ISD::EntryToken) {
1064     unsigned i = 0, e = PendingExports.size();
1065     for (; i != e; ++i) {
1066       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1067       if (PendingExports[i].getNode()->getOperand(0) == Root)
1068         break;  // Don't add the root if we already indirectly depend on it.
1069     }
1070 
1071     if (i == e)
1072       PendingExports.push_back(Root);
1073   }
1074 
1075   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1076                      PendingExports);
1077   PendingExports.clear();
1078   DAG.setRoot(Root);
1079   return Root;
1080 }
1081 
1082 void SelectionDAGBuilder::visit(const Instruction &I) {
1083   // Set up outgoing PHI node register values before emitting the terminator.
1084   if (I.isTerminator()) {
1085     HandlePHINodesInSuccessorBlocks(I.getParent());
1086   }
1087 
1088   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1089   if (!isa<DbgInfoIntrinsic>(I))
1090     ++SDNodeOrder;
1091 
1092   CurInst = &I;
1093 
1094   visit(I.getOpcode(), I);
1095 
1096   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1097     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1098     // maps to this instruction.
1099     // TODO: We could handle all flags (nsw, etc) here.
1100     // TODO: If an IR instruction maps to >1 node, only the final node will have
1101     //       flags set.
1102     if (SDNode *Node = getNodeForIRValue(&I)) {
1103       SDNodeFlags IncomingFlags;
1104       IncomingFlags.copyFMF(*FPMO);
1105       if (!Node->getFlags().isDefined())
1106         Node->setFlags(IncomingFlags);
1107       else
1108         Node->intersectFlagsWith(IncomingFlags);
1109     }
1110   }
1111 
1112   if (!I.isTerminator() && !HasTailCall &&
1113       !isStatepoint(&I)) // statepoints handle their exports internally
1114     CopyToExportRegsIfNeeded(&I);
1115 
1116   CurInst = nullptr;
1117 }
1118 
1119 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1120   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1121 }
1122 
1123 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1124   // Note: this doesn't use InstVisitor, because it has to work with
1125   // ConstantExpr's in addition to instructions.
1126   switch (Opcode) {
1127   default: llvm_unreachable("Unknown instruction type encountered!");
1128     // Build the switch statement using the Instruction.def file.
1129 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1130     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1131 #include "llvm/IR/Instruction.def"
1132   }
1133 }
1134 
1135 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1136                                                 const DIExpression *Expr) {
1137   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1138     const DbgValueInst *DI = DDI.getDI();
1139     DIVariable *DanglingVariable = DI->getVariable();
1140     DIExpression *DanglingExpr = DI->getExpression();
1141     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1142       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1143       return true;
1144     }
1145     return false;
1146   };
1147 
1148   for (auto &DDIMI : DanglingDebugInfoMap) {
1149     DanglingDebugInfoVector &DDIV = DDIMI.second;
1150 
1151     // If debug info is to be dropped, run it through final checks to see
1152     // whether it can be salvaged.
1153     for (auto &DDI : DDIV)
1154       if (isMatchingDbgValue(DDI))
1155         salvageUnresolvedDbgValue(DDI);
1156 
1157     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1158   }
1159 }
1160 
1161 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1162 // generate the debug data structures now that we've seen its definition.
1163 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1164                                                    SDValue Val) {
1165   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1166   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1167     return;
1168 
1169   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1170   for (auto &DDI : DDIV) {
1171     const DbgValueInst *DI = DDI.getDI();
1172     assert(DI && "Ill-formed DanglingDebugInfo");
1173     DebugLoc dl = DDI.getdl();
1174     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1175     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1176     DILocalVariable *Variable = DI->getVariable();
1177     DIExpression *Expr = DI->getExpression();
1178     assert(Variable->isValidLocationForIntrinsic(dl) &&
1179            "Expected inlined-at fields to agree");
1180     SDDbgValue *SDV;
1181     if (Val.getNode()) {
1182       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1183       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1184       // we couldn't resolve it directly when examining the DbgValue intrinsic
1185       // in the first place we should not be more successful here). Unless we
1186       // have some test case that prove this to be correct we should avoid
1187       // calling EmitFuncArgumentDbgValue here.
1188       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1189         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1190                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1191         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1192         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1193         // inserted after the definition of Val when emitting the instructions
1194         // after ISel. An alternative could be to teach
1195         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1196         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1197                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1198                    << ValSDNodeOrder << "\n");
1199         SDV = getDbgValue(Val, Variable, Expr, dl,
1200                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1201         DAG.AddDbgValue(SDV, Val.getNode(), false);
1202       } else
1203         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1204                           << "in EmitFuncArgumentDbgValue\n");
1205     } else {
1206       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1207       auto Undef =
1208           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1209       auto SDV =
1210           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1211       DAG.AddDbgValue(SDV, nullptr, false);
1212     }
1213   }
1214   DDIV.clear();
1215 }
1216 
1217 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1218   Value *V = DDI.getDI()->getValue();
1219   DILocalVariable *Var = DDI.getDI()->getVariable();
1220   DIExpression *Expr = DDI.getDI()->getExpression();
1221   DebugLoc DL = DDI.getdl();
1222   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1223   unsigned SDOrder = DDI.getSDNodeOrder();
1224 
1225   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1226   // that DW_OP_stack_value is desired.
1227   assert(isa<DbgValueInst>(DDI.getDI()));
1228   bool StackValue = true;
1229 
1230   // Can this Value can be encoded without any further work?
1231   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1232     return;
1233 
1234   // Attempt to salvage back through as many instructions as possible. Bail if
1235   // a non-instruction is seen, such as a constant expression or global
1236   // variable. FIXME: Further work could recover those too.
1237   while (isa<Instruction>(V)) {
1238     Instruction &VAsInst = *cast<Instruction>(V);
1239     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1240 
1241     // If we cannot salvage any further, and haven't yet found a suitable debug
1242     // expression, bail out.
1243     if (!NewExpr)
1244       break;
1245 
1246     // New value and expr now represent this debuginfo.
1247     V = VAsInst.getOperand(0);
1248     Expr = NewExpr;
1249 
1250     // Some kind of simplification occurred: check whether the operand of the
1251     // salvaged debug expression can be encoded in this DAG.
1252     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1253       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1254                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1255       return;
1256     }
1257   }
1258 
1259   // This was the final opportunity to salvage this debug information, and it
1260   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1261   // any earlier variable location.
1262   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1263   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1264   DAG.AddDbgValue(SDV, nullptr, false);
1265 
1266   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1267                     << "\n");
1268   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1269                     << "\n");
1270 }
1271 
1272 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1273                                            DIExpression *Expr, DebugLoc dl,
1274                                            DebugLoc InstDL, unsigned Order) {
1275   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1276   SDDbgValue *SDV;
1277   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1278       isa<ConstantPointerNull>(V)) {
1279     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1280     DAG.AddDbgValue(SDV, nullptr, false);
1281     return true;
1282   }
1283 
1284   // If the Value is a frame index, we can create a FrameIndex debug value
1285   // without relying on the DAG at all.
1286   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1287     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1288     if (SI != FuncInfo.StaticAllocaMap.end()) {
1289       auto SDV =
1290           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1291                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1292       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1293       // is still available even if the SDNode gets optimized out.
1294       DAG.AddDbgValue(SDV, nullptr, false);
1295       return true;
1296     }
1297   }
1298 
1299   // Do not use getValue() in here; we don't want to generate code at
1300   // this point if it hasn't been done yet.
1301   SDValue N = NodeMap[V];
1302   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1303     N = UnusedArgNodeMap[V];
1304   if (N.getNode()) {
1305     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1306       return true;
1307     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1308     DAG.AddDbgValue(SDV, N.getNode(), false);
1309     return true;
1310   }
1311 
1312   // Special rules apply for the first dbg.values of parameter variables in a
1313   // function. Identify them by the fact they reference Argument Values, that
1314   // they're parameters, and they are parameters of the current function. We
1315   // need to let them dangle until they get an SDNode.
1316   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1317                        !InstDL.getInlinedAt();
1318   if (!IsParamOfFunc) {
1319     // The value is not used in this block yet (or it would have an SDNode).
1320     // We still want the value to appear for the user if possible -- if it has
1321     // an associated VReg, we can refer to that instead.
1322     auto VMI = FuncInfo.ValueMap.find(V);
1323     if (VMI != FuncInfo.ValueMap.end()) {
1324       unsigned Reg = VMI->second;
1325       // If this is a PHI node, it may be split up into several MI PHI nodes
1326       // (in FunctionLoweringInfo::set).
1327       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1328                        V->getType(), None);
1329       if (RFV.occupiesMultipleRegs()) {
1330         unsigned Offset = 0;
1331         unsigned BitsToDescribe = 0;
1332         if (auto VarSize = Var->getSizeInBits())
1333           BitsToDescribe = *VarSize;
1334         if (auto Fragment = Expr->getFragmentInfo())
1335           BitsToDescribe = Fragment->SizeInBits;
1336         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1337           unsigned RegisterSize = RegAndSize.second;
1338           // Bail out if all bits are described already.
1339           if (Offset >= BitsToDescribe)
1340             break;
1341           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1342               ? BitsToDescribe - Offset
1343               : RegisterSize;
1344           auto FragmentExpr = DIExpression::createFragmentExpression(
1345               Expr, Offset, FragmentSize);
1346           if (!FragmentExpr)
1347               continue;
1348           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1349                                     false, dl, SDNodeOrder);
1350           DAG.AddDbgValue(SDV, nullptr, false);
1351           Offset += RegisterSize;
1352         }
1353       } else {
1354         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1355         DAG.AddDbgValue(SDV, nullptr, false);
1356       }
1357       return true;
1358     }
1359   }
1360 
1361   return false;
1362 }
1363 
1364 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1365   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1366   for (auto &Pair : DanglingDebugInfoMap)
1367     for (auto &DDI : Pair.second)
1368       salvageUnresolvedDbgValue(DDI);
1369   clearDanglingDebugInfo();
1370 }
1371 
1372 /// getCopyFromRegs - If there was virtual register allocated for the value V
1373 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1374 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1375   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1376   SDValue Result;
1377 
1378   if (It != FuncInfo.ValueMap.end()) {
1379     unsigned InReg = It->second;
1380 
1381     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1382                      DAG.getDataLayout(), InReg, Ty,
1383                      None); // This is not an ABI copy.
1384     SDValue Chain = DAG.getEntryNode();
1385     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1386                                  V);
1387     resolveDanglingDebugInfo(V, Result);
1388   }
1389 
1390   return Result;
1391 }
1392 
1393 /// getValue - Return an SDValue for the given Value.
1394 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1395   // If we already have an SDValue for this value, use it. It's important
1396   // to do this first, so that we don't create a CopyFromReg if we already
1397   // have a regular SDValue.
1398   SDValue &N = NodeMap[V];
1399   if (N.getNode()) return N;
1400 
1401   // If there's a virtual register allocated and initialized for this
1402   // value, use it.
1403   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1404     return copyFromReg;
1405 
1406   // Otherwise create a new SDValue and remember it.
1407   SDValue Val = getValueImpl(V);
1408   NodeMap[V] = Val;
1409   resolveDanglingDebugInfo(V, Val);
1410   return Val;
1411 }
1412 
1413 // Return true if SDValue exists for the given Value
1414 bool SelectionDAGBuilder::findValue(const Value *V) const {
1415   return (NodeMap.find(V) != NodeMap.end()) ||
1416     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1417 }
1418 
1419 /// getNonRegisterValue - Return an SDValue for the given Value, but
1420 /// don't look in FuncInfo.ValueMap for a virtual register.
1421 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1422   // If we already have an SDValue for this value, use it.
1423   SDValue &N = NodeMap[V];
1424   if (N.getNode()) {
1425     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1426       // Remove the debug location from the node as the node is about to be used
1427       // in a location which may differ from the original debug location.  This
1428       // is relevant to Constant and ConstantFP nodes because they can appear
1429       // as constant expressions inside PHI nodes.
1430       N->setDebugLoc(DebugLoc());
1431     }
1432     return N;
1433   }
1434 
1435   // Otherwise create a new SDValue and remember it.
1436   SDValue Val = getValueImpl(V);
1437   NodeMap[V] = Val;
1438   resolveDanglingDebugInfo(V, Val);
1439   return Val;
1440 }
1441 
1442 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1443 /// Create an SDValue for the given value.
1444 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1445   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1446 
1447   if (const Constant *C = dyn_cast<Constant>(V)) {
1448     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1449 
1450     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1451       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1452 
1453     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1454       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1455 
1456     if (isa<ConstantPointerNull>(C)) {
1457       unsigned AS = V->getType()->getPointerAddressSpace();
1458       return DAG.getConstant(0, getCurSDLoc(),
1459                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1460     }
1461 
1462     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1463       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1464 
1465     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1466       return DAG.getUNDEF(VT);
1467 
1468     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1469       visit(CE->getOpcode(), *CE);
1470       SDValue N1 = NodeMap[V];
1471       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1472       return N1;
1473     }
1474 
1475     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1476       SmallVector<SDValue, 4> Constants;
1477       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1478            OI != OE; ++OI) {
1479         SDNode *Val = getValue(*OI).getNode();
1480         // If the operand is an empty aggregate, there are no values.
1481         if (!Val) continue;
1482         // Add each leaf value from the operand to the Constants list
1483         // to form a flattened list of all the values.
1484         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1485           Constants.push_back(SDValue(Val, i));
1486       }
1487 
1488       return DAG.getMergeValues(Constants, getCurSDLoc());
1489     }
1490 
1491     if (const ConstantDataSequential *CDS =
1492           dyn_cast<ConstantDataSequential>(C)) {
1493       SmallVector<SDValue, 4> Ops;
1494       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1495         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1496         // Add each leaf value from the operand to the Constants list
1497         // to form a flattened list of all the values.
1498         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1499           Ops.push_back(SDValue(Val, i));
1500       }
1501 
1502       if (isa<ArrayType>(CDS->getType()))
1503         return DAG.getMergeValues(Ops, getCurSDLoc());
1504       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1505     }
1506 
1507     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1508       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1509              "Unknown struct or array constant!");
1510 
1511       SmallVector<EVT, 4> ValueVTs;
1512       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1513       unsigned NumElts = ValueVTs.size();
1514       if (NumElts == 0)
1515         return SDValue(); // empty struct
1516       SmallVector<SDValue, 4> Constants(NumElts);
1517       for (unsigned i = 0; i != NumElts; ++i) {
1518         EVT EltVT = ValueVTs[i];
1519         if (isa<UndefValue>(C))
1520           Constants[i] = DAG.getUNDEF(EltVT);
1521         else if (EltVT.isFloatingPoint())
1522           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1523         else
1524           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1525       }
1526 
1527       return DAG.getMergeValues(Constants, getCurSDLoc());
1528     }
1529 
1530     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1531       return DAG.getBlockAddress(BA, VT);
1532 
1533     VectorType *VecTy = cast<VectorType>(V->getType());
1534     unsigned NumElements = VecTy->getNumElements();
1535 
1536     // Now that we know the number and type of the elements, get that number of
1537     // elements into the Ops array based on what kind of constant it is.
1538     SmallVector<SDValue, 16> Ops;
1539     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1540       for (unsigned i = 0; i != NumElements; ++i)
1541         Ops.push_back(getValue(CV->getOperand(i)));
1542     } else {
1543       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1544       EVT EltVT =
1545           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1546 
1547       SDValue Op;
1548       if (EltVT.isFloatingPoint())
1549         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1550       else
1551         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1552       Ops.assign(NumElements, Op);
1553     }
1554 
1555     // Create a BUILD_VECTOR node.
1556     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1557   }
1558 
1559   // If this is a static alloca, generate it as the frameindex instead of
1560   // computation.
1561   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1562     DenseMap<const AllocaInst*, int>::iterator SI =
1563       FuncInfo.StaticAllocaMap.find(AI);
1564     if (SI != FuncInfo.StaticAllocaMap.end())
1565       return DAG.getFrameIndex(SI->second,
1566                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1567   }
1568 
1569   // If this is an instruction which fast-isel has deferred, select it now.
1570   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1571     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1572 
1573     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1574                      Inst->getType(), getABIRegCopyCC(V));
1575     SDValue Chain = DAG.getEntryNode();
1576     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1577   }
1578 
1579   llvm_unreachable("Can't get register for value!");
1580 }
1581 
1582 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1583   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1584   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1585   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1586   bool IsSEH = isAsynchronousEHPersonality(Pers);
1587   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1588   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1589   if (!IsSEH)
1590     CatchPadMBB->setIsEHScopeEntry();
1591   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1592   if (IsMSVCCXX || IsCoreCLR)
1593     CatchPadMBB->setIsEHFuncletEntry();
1594   // Wasm does not need catchpads anymore
1595   if (!IsWasmCXX)
1596     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1597                             getControlRoot()));
1598 }
1599 
1600 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1601   // Update machine-CFG edge.
1602   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1603   FuncInfo.MBB->addSuccessor(TargetMBB);
1604 
1605   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1606   bool IsSEH = isAsynchronousEHPersonality(Pers);
1607   if (IsSEH) {
1608     // If this is not a fall-through branch or optimizations are switched off,
1609     // emit the branch.
1610     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1611         TM.getOptLevel() == CodeGenOpt::None)
1612       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1613                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1614     return;
1615   }
1616 
1617   // Figure out the funclet membership for the catchret's successor.
1618   // This will be used by the FuncletLayout pass to determine how to order the
1619   // BB's.
1620   // A 'catchret' returns to the outer scope's color.
1621   Value *ParentPad = I.getCatchSwitchParentPad();
1622   const BasicBlock *SuccessorColor;
1623   if (isa<ConstantTokenNone>(ParentPad))
1624     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1625   else
1626     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1627   assert(SuccessorColor && "No parent funclet for catchret!");
1628   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1629   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1630 
1631   // Create the terminator node.
1632   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1633                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1634                             DAG.getBasicBlock(SuccessorColorMBB));
1635   DAG.setRoot(Ret);
1636 }
1637 
1638 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1639   // Don't emit any special code for the cleanuppad instruction. It just marks
1640   // the start of an EH scope/funclet.
1641   FuncInfo.MBB->setIsEHScopeEntry();
1642   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1643   if (Pers != EHPersonality::Wasm_CXX) {
1644     FuncInfo.MBB->setIsEHFuncletEntry();
1645     FuncInfo.MBB->setIsCleanupFuncletEntry();
1646   }
1647 }
1648 
1649 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1650 // the control flow always stops at the single catch pad, as it does for a
1651 // cleanup pad. In case the exception caught is not of the types the catch pad
1652 // catches, it will be rethrown by a rethrow.
1653 static void findWasmUnwindDestinations(
1654     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1655     BranchProbability Prob,
1656     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1657         &UnwindDests) {
1658   while (EHPadBB) {
1659     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1660     if (isa<CleanupPadInst>(Pad)) {
1661       // Stop on cleanup pads.
1662       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1663       UnwindDests.back().first->setIsEHScopeEntry();
1664       break;
1665     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1666       // Add the catchpad handlers to the possible destinations. We don't
1667       // continue to the unwind destination of the catchswitch for wasm.
1668       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1669         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1670         UnwindDests.back().first->setIsEHScopeEntry();
1671       }
1672       break;
1673     } else {
1674       continue;
1675     }
1676   }
1677 }
1678 
1679 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1680 /// many places it could ultimately go. In the IR, we have a single unwind
1681 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1682 /// This function skips over imaginary basic blocks that hold catchswitch
1683 /// instructions, and finds all the "real" machine
1684 /// basic block destinations. As those destinations may not be successors of
1685 /// EHPadBB, here we also calculate the edge probability to those destinations.
1686 /// The passed-in Prob is the edge probability to EHPadBB.
1687 static void findUnwindDestinations(
1688     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1689     BranchProbability Prob,
1690     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1691         &UnwindDests) {
1692   EHPersonality Personality =
1693     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1694   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1695   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1696   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1697   bool IsSEH = isAsynchronousEHPersonality(Personality);
1698 
1699   if (IsWasmCXX) {
1700     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1701     assert(UnwindDests.size() <= 1 &&
1702            "There should be at most one unwind destination for wasm");
1703     return;
1704   }
1705 
1706   while (EHPadBB) {
1707     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1708     BasicBlock *NewEHPadBB = nullptr;
1709     if (isa<LandingPadInst>(Pad)) {
1710       // Stop on landingpads. They are not funclets.
1711       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1712       break;
1713     } else if (isa<CleanupPadInst>(Pad)) {
1714       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1715       // personalities.
1716       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1717       UnwindDests.back().first->setIsEHScopeEntry();
1718       UnwindDests.back().first->setIsEHFuncletEntry();
1719       break;
1720     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1721       // Add the catchpad handlers to the possible destinations.
1722       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1723         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1724         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1725         if (IsMSVCCXX || IsCoreCLR)
1726           UnwindDests.back().first->setIsEHFuncletEntry();
1727         if (!IsSEH)
1728           UnwindDests.back().first->setIsEHScopeEntry();
1729       }
1730       NewEHPadBB = CatchSwitch->getUnwindDest();
1731     } else {
1732       continue;
1733     }
1734 
1735     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1736     if (BPI && NewEHPadBB)
1737       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1738     EHPadBB = NewEHPadBB;
1739   }
1740 }
1741 
1742 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1743   // Update successor info.
1744   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1745   auto UnwindDest = I.getUnwindDest();
1746   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1747   BranchProbability UnwindDestProb =
1748       (BPI && UnwindDest)
1749           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1750           : BranchProbability::getZero();
1751   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1752   for (auto &UnwindDest : UnwindDests) {
1753     UnwindDest.first->setIsEHPad();
1754     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1755   }
1756   FuncInfo.MBB->normalizeSuccProbs();
1757 
1758   // Create the terminator node.
1759   SDValue Ret =
1760       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1761   DAG.setRoot(Ret);
1762 }
1763 
1764 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1765   report_fatal_error("visitCatchSwitch not yet implemented!");
1766 }
1767 
1768 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1769   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1770   auto &DL = DAG.getDataLayout();
1771   SDValue Chain = getControlRoot();
1772   SmallVector<ISD::OutputArg, 8> Outs;
1773   SmallVector<SDValue, 8> OutVals;
1774 
1775   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1776   // lower
1777   //
1778   //   %val = call <ty> @llvm.experimental.deoptimize()
1779   //   ret <ty> %val
1780   //
1781   // differently.
1782   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1783     LowerDeoptimizingReturn();
1784     return;
1785   }
1786 
1787   if (!FuncInfo.CanLowerReturn) {
1788     unsigned DemoteReg = FuncInfo.DemoteRegister;
1789     const Function *F = I.getParent()->getParent();
1790 
1791     // Emit a store of the return value through the virtual register.
1792     // Leave Outs empty so that LowerReturn won't try to load return
1793     // registers the usual way.
1794     SmallVector<EVT, 1> PtrValueVTs;
1795     ComputeValueVTs(TLI, DL,
1796                     F->getReturnType()->getPointerTo(
1797                         DAG.getDataLayout().getAllocaAddrSpace()),
1798                     PtrValueVTs);
1799 
1800     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1801                                         DemoteReg, PtrValueVTs[0]);
1802     SDValue RetOp = getValue(I.getOperand(0));
1803 
1804     SmallVector<EVT, 4> ValueVTs, MemVTs;
1805     SmallVector<uint64_t, 4> Offsets;
1806     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1807                     &Offsets);
1808     unsigned NumValues = ValueVTs.size();
1809 
1810     SmallVector<SDValue, 4> Chains(NumValues);
1811     for (unsigned i = 0; i != NumValues; ++i) {
1812       // An aggregate return value cannot wrap around the address space, so
1813       // offsets to its parts don't wrap either.
1814       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1815 
1816       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
1817       if (MemVTs[i] != ValueVTs[i])
1818         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1819       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1820           // FIXME: better loc info would be nice.
1821           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1822     }
1823 
1824     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1825                         MVT::Other, Chains);
1826   } else if (I.getNumOperands() != 0) {
1827     SmallVector<EVT, 4> ValueVTs;
1828     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1829     unsigned NumValues = ValueVTs.size();
1830     if (NumValues) {
1831       SDValue RetOp = getValue(I.getOperand(0));
1832 
1833       const Function *F = I.getParent()->getParent();
1834 
1835       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1836           I.getOperand(0)->getType(), F->getCallingConv(),
1837           /*IsVarArg*/ false);
1838 
1839       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1840       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1841                                           Attribute::SExt))
1842         ExtendKind = ISD::SIGN_EXTEND;
1843       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1844                                                Attribute::ZExt))
1845         ExtendKind = ISD::ZERO_EXTEND;
1846 
1847       LLVMContext &Context = F->getContext();
1848       bool RetInReg = F->getAttributes().hasAttribute(
1849           AttributeList::ReturnIndex, Attribute::InReg);
1850 
1851       for (unsigned j = 0; j != NumValues; ++j) {
1852         EVT VT = ValueVTs[j];
1853 
1854         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1855           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1856 
1857         CallingConv::ID CC = F->getCallingConv();
1858 
1859         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1860         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1861         SmallVector<SDValue, 4> Parts(NumParts);
1862         getCopyToParts(DAG, getCurSDLoc(),
1863                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1864                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1865 
1866         // 'inreg' on function refers to return value
1867         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1868         if (RetInReg)
1869           Flags.setInReg();
1870 
1871         if (I.getOperand(0)->getType()->isPointerTy()) {
1872           Flags.setPointer();
1873           Flags.setPointerAddrSpace(
1874               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1875         }
1876 
1877         if (NeedsRegBlock) {
1878           Flags.setInConsecutiveRegs();
1879           if (j == NumValues - 1)
1880             Flags.setInConsecutiveRegsLast();
1881         }
1882 
1883         // Propagate extension type if any
1884         if (ExtendKind == ISD::SIGN_EXTEND)
1885           Flags.setSExt();
1886         else if (ExtendKind == ISD::ZERO_EXTEND)
1887           Flags.setZExt();
1888 
1889         for (unsigned i = 0; i < NumParts; ++i) {
1890           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1891                                         VT, /*isfixed=*/true, 0, 0));
1892           OutVals.push_back(Parts[i]);
1893         }
1894       }
1895     }
1896   }
1897 
1898   // Push in swifterror virtual register as the last element of Outs. This makes
1899   // sure swifterror virtual register will be returned in the swifterror
1900   // physical register.
1901   const Function *F = I.getParent()->getParent();
1902   if (TLI.supportSwiftError() &&
1903       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1904     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1905     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1906     Flags.setSwiftError();
1907     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1908                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1909                                   true /*isfixed*/, 1 /*origidx*/,
1910                                   0 /*partOffs*/));
1911     // Create SDNode for the swifterror virtual register.
1912     OutVals.push_back(
1913         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1914                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1915                         EVT(TLI.getPointerTy(DL))));
1916   }
1917 
1918   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1919   CallingConv::ID CallConv =
1920     DAG.getMachineFunction().getFunction().getCallingConv();
1921   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1922       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1923 
1924   // Verify that the target's LowerReturn behaved as expected.
1925   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1926          "LowerReturn didn't return a valid chain!");
1927 
1928   // Update the DAG with the new chain value resulting from return lowering.
1929   DAG.setRoot(Chain);
1930 }
1931 
1932 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1933 /// created for it, emit nodes to copy the value into the virtual
1934 /// registers.
1935 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1936   // Skip empty types
1937   if (V->getType()->isEmptyTy())
1938     return;
1939 
1940   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1941   if (VMI != FuncInfo.ValueMap.end()) {
1942     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1943     CopyValueToVirtualRegister(V, VMI->second);
1944   }
1945 }
1946 
1947 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1948 /// the current basic block, add it to ValueMap now so that we'll get a
1949 /// CopyTo/FromReg.
1950 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1951   // No need to export constants.
1952   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1953 
1954   // Already exported?
1955   if (FuncInfo.isExportedInst(V)) return;
1956 
1957   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1958   CopyValueToVirtualRegister(V, Reg);
1959 }
1960 
1961 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1962                                                      const BasicBlock *FromBB) {
1963   // The operands of the setcc have to be in this block.  We don't know
1964   // how to export them from some other block.
1965   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1966     // Can export from current BB.
1967     if (VI->getParent() == FromBB)
1968       return true;
1969 
1970     // Is already exported, noop.
1971     return FuncInfo.isExportedInst(V);
1972   }
1973 
1974   // If this is an argument, we can export it if the BB is the entry block or
1975   // if it is already exported.
1976   if (isa<Argument>(V)) {
1977     if (FromBB == &FromBB->getParent()->getEntryBlock())
1978       return true;
1979 
1980     // Otherwise, can only export this if it is already exported.
1981     return FuncInfo.isExportedInst(V);
1982   }
1983 
1984   // Otherwise, constants can always be exported.
1985   return true;
1986 }
1987 
1988 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1989 BranchProbability
1990 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1991                                         const MachineBasicBlock *Dst) const {
1992   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1993   const BasicBlock *SrcBB = Src->getBasicBlock();
1994   const BasicBlock *DstBB = Dst->getBasicBlock();
1995   if (!BPI) {
1996     // If BPI is not available, set the default probability as 1 / N, where N is
1997     // the number of successors.
1998     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1999     return BranchProbability(1, SuccSize);
2000   }
2001   return BPI->getEdgeProbability(SrcBB, DstBB);
2002 }
2003 
2004 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2005                                                MachineBasicBlock *Dst,
2006                                                BranchProbability Prob) {
2007   if (!FuncInfo.BPI)
2008     Src->addSuccessorWithoutProb(Dst);
2009   else {
2010     if (Prob.isUnknown())
2011       Prob = getEdgeProbability(Src, Dst);
2012     Src->addSuccessor(Dst, Prob);
2013   }
2014 }
2015 
2016 static bool InBlock(const Value *V, const BasicBlock *BB) {
2017   if (const Instruction *I = dyn_cast<Instruction>(V))
2018     return I->getParent() == BB;
2019   return true;
2020 }
2021 
2022 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2023 /// This function emits a branch and is used at the leaves of an OR or an
2024 /// AND operator tree.
2025 void
2026 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2027                                                   MachineBasicBlock *TBB,
2028                                                   MachineBasicBlock *FBB,
2029                                                   MachineBasicBlock *CurBB,
2030                                                   MachineBasicBlock *SwitchBB,
2031                                                   BranchProbability TProb,
2032                                                   BranchProbability FProb,
2033                                                   bool InvertCond) {
2034   const BasicBlock *BB = CurBB->getBasicBlock();
2035 
2036   // If the leaf of the tree is a comparison, merge the condition into
2037   // the caseblock.
2038   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2039     // The operands of the cmp have to be in this block.  We don't know
2040     // how to export them from some other block.  If this is the first block
2041     // of the sequence, no exporting is needed.
2042     if (CurBB == SwitchBB ||
2043         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2044          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2045       ISD::CondCode Condition;
2046       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2047         ICmpInst::Predicate Pred =
2048             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2049         Condition = getICmpCondCode(Pred);
2050       } else {
2051         const FCmpInst *FC = cast<FCmpInst>(Cond);
2052         FCmpInst::Predicate Pred =
2053             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2054         Condition = getFCmpCondCode(Pred);
2055         if (TM.Options.NoNaNsFPMath)
2056           Condition = getFCmpCodeWithoutNaN(Condition);
2057       }
2058 
2059       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2060                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2061       SL->SwitchCases.push_back(CB);
2062       return;
2063     }
2064   }
2065 
2066   // Create a CaseBlock record representing this branch.
2067   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2068   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2069                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2070   SL->SwitchCases.push_back(CB);
2071 }
2072 
2073 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2074                                                MachineBasicBlock *TBB,
2075                                                MachineBasicBlock *FBB,
2076                                                MachineBasicBlock *CurBB,
2077                                                MachineBasicBlock *SwitchBB,
2078                                                Instruction::BinaryOps Opc,
2079                                                BranchProbability TProb,
2080                                                BranchProbability FProb,
2081                                                bool InvertCond) {
2082   // Skip over not part of the tree and remember to invert op and operands at
2083   // next level.
2084   Value *NotCond;
2085   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2086       InBlock(NotCond, CurBB->getBasicBlock())) {
2087     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2088                          !InvertCond);
2089     return;
2090   }
2091 
2092   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2093   // Compute the effective opcode for Cond, taking into account whether it needs
2094   // to be inverted, e.g.
2095   //   and (not (or A, B)), C
2096   // gets lowered as
2097   //   and (and (not A, not B), C)
2098   unsigned BOpc = 0;
2099   if (BOp) {
2100     BOpc = BOp->getOpcode();
2101     if (InvertCond) {
2102       if (BOpc == Instruction::And)
2103         BOpc = Instruction::Or;
2104       else if (BOpc == Instruction::Or)
2105         BOpc = Instruction::And;
2106     }
2107   }
2108 
2109   // If this node is not part of the or/and tree, emit it as a branch.
2110   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2111       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2112       BOp->getParent() != CurBB->getBasicBlock() ||
2113       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2114       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2115     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2116                                  TProb, FProb, InvertCond);
2117     return;
2118   }
2119 
2120   //  Create TmpBB after CurBB.
2121   MachineFunction::iterator BBI(CurBB);
2122   MachineFunction &MF = DAG.getMachineFunction();
2123   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2124   CurBB->getParent()->insert(++BBI, TmpBB);
2125 
2126   if (Opc == Instruction::Or) {
2127     // Codegen X | Y as:
2128     // BB1:
2129     //   jmp_if_X TBB
2130     //   jmp TmpBB
2131     // TmpBB:
2132     //   jmp_if_Y TBB
2133     //   jmp FBB
2134     //
2135 
2136     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2137     // The requirement is that
2138     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2139     //     = TrueProb for original BB.
2140     // Assuming the original probabilities are A and B, one choice is to set
2141     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2142     // A/(1+B) and 2B/(1+B). This choice assumes that
2143     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2144     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2145     // TmpBB, but the math is more complicated.
2146 
2147     auto NewTrueProb = TProb / 2;
2148     auto NewFalseProb = TProb / 2 + FProb;
2149     // Emit the LHS condition.
2150     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2151                          NewTrueProb, NewFalseProb, InvertCond);
2152 
2153     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2154     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2155     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2156     // Emit the RHS condition into TmpBB.
2157     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2158                          Probs[0], Probs[1], InvertCond);
2159   } else {
2160     assert(Opc == Instruction::And && "Unknown merge op!");
2161     // Codegen X & Y as:
2162     // BB1:
2163     //   jmp_if_X TmpBB
2164     //   jmp FBB
2165     // TmpBB:
2166     //   jmp_if_Y TBB
2167     //   jmp FBB
2168     //
2169     //  This requires creation of TmpBB after CurBB.
2170 
2171     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2172     // The requirement is that
2173     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2174     //     = FalseProb for original BB.
2175     // Assuming the original probabilities are A and B, one choice is to set
2176     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2177     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2178     // TrueProb for BB1 * FalseProb for TmpBB.
2179 
2180     auto NewTrueProb = TProb + FProb / 2;
2181     auto NewFalseProb = FProb / 2;
2182     // Emit the LHS condition.
2183     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2184                          NewTrueProb, NewFalseProb, InvertCond);
2185 
2186     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2187     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2188     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2189     // Emit the RHS condition into TmpBB.
2190     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2191                          Probs[0], Probs[1], InvertCond);
2192   }
2193 }
2194 
2195 /// If the set of cases should be emitted as a series of branches, return true.
2196 /// If we should emit this as a bunch of and/or'd together conditions, return
2197 /// false.
2198 bool
2199 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2200   if (Cases.size() != 2) return true;
2201 
2202   // If this is two comparisons of the same values or'd or and'd together, they
2203   // will get folded into a single comparison, so don't emit two blocks.
2204   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2205        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2206       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2207        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2208     return false;
2209   }
2210 
2211   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2212   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2213   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2214       Cases[0].CC == Cases[1].CC &&
2215       isa<Constant>(Cases[0].CmpRHS) &&
2216       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2217     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2218       return false;
2219     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2220       return false;
2221   }
2222 
2223   return true;
2224 }
2225 
2226 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2227   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2228 
2229   // Update machine-CFG edges.
2230   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2231 
2232   if (I.isUnconditional()) {
2233     // Update machine-CFG edges.
2234     BrMBB->addSuccessor(Succ0MBB);
2235 
2236     // If this is not a fall-through branch or optimizations are switched off,
2237     // emit the branch.
2238     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2239       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2240                               MVT::Other, getControlRoot(),
2241                               DAG.getBasicBlock(Succ0MBB)));
2242 
2243     return;
2244   }
2245 
2246   // If this condition is one of the special cases we handle, do special stuff
2247   // now.
2248   const Value *CondVal = I.getCondition();
2249   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2250 
2251   // If this is a series of conditions that are or'd or and'd together, emit
2252   // this as a sequence of branches instead of setcc's with and/or operations.
2253   // As long as jumps are not expensive, this should improve performance.
2254   // For example, instead of something like:
2255   //     cmp A, B
2256   //     C = seteq
2257   //     cmp D, E
2258   //     F = setle
2259   //     or C, F
2260   //     jnz foo
2261   // Emit:
2262   //     cmp A, B
2263   //     je foo
2264   //     cmp D, E
2265   //     jle foo
2266   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2267     Instruction::BinaryOps Opcode = BOp->getOpcode();
2268     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2269         !I.hasMetadata(LLVMContext::MD_unpredictable) &&
2270         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2271       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2272                            Opcode,
2273                            getEdgeProbability(BrMBB, Succ0MBB),
2274                            getEdgeProbability(BrMBB, Succ1MBB),
2275                            /*InvertCond=*/false);
2276       // If the compares in later blocks need to use values not currently
2277       // exported from this block, export them now.  This block should always
2278       // be the first entry.
2279       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2280 
2281       // Allow some cases to be rejected.
2282       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2283         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2284           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2285           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2286         }
2287 
2288         // Emit the branch for this block.
2289         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2290         SL->SwitchCases.erase(SL->SwitchCases.begin());
2291         return;
2292       }
2293 
2294       // Okay, we decided not to do this, remove any inserted MBB's and clear
2295       // SwitchCases.
2296       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2297         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2298 
2299       SL->SwitchCases.clear();
2300     }
2301   }
2302 
2303   // Create a CaseBlock record representing this branch.
2304   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2305                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2306 
2307   // Use visitSwitchCase to actually insert the fast branch sequence for this
2308   // cond branch.
2309   visitSwitchCase(CB, BrMBB);
2310 }
2311 
2312 /// visitSwitchCase - Emits the necessary code to represent a single node in
2313 /// the binary search tree resulting from lowering a switch instruction.
2314 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2315                                           MachineBasicBlock *SwitchBB) {
2316   SDValue Cond;
2317   SDValue CondLHS = getValue(CB.CmpLHS);
2318   SDLoc dl = CB.DL;
2319 
2320   if (CB.CC == ISD::SETTRUE) {
2321     // Branch or fall through to TrueBB.
2322     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2323     SwitchBB->normalizeSuccProbs();
2324     if (CB.TrueBB != NextBlock(SwitchBB)) {
2325       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2326                               DAG.getBasicBlock(CB.TrueBB)));
2327     }
2328     return;
2329   }
2330 
2331   auto &TLI = DAG.getTargetLoweringInfo();
2332   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2333 
2334   // Build the setcc now.
2335   if (!CB.CmpMHS) {
2336     // Fold "(X == true)" to X and "(X == false)" to !X to
2337     // handle common cases produced by branch lowering.
2338     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2339         CB.CC == ISD::SETEQ)
2340       Cond = CondLHS;
2341     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2342              CB.CC == ISD::SETEQ) {
2343       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2344       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2345     } else {
2346       SDValue CondRHS = getValue(CB.CmpRHS);
2347 
2348       // If a pointer's DAG type is larger than its memory type then the DAG
2349       // values are zero-extended. This breaks signed comparisons so truncate
2350       // back to the underlying type before doing the compare.
2351       if (CondLHS.getValueType() != MemVT) {
2352         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2353         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2354       }
2355       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2356     }
2357   } else {
2358     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2359 
2360     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2361     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2362 
2363     SDValue CmpOp = getValue(CB.CmpMHS);
2364     EVT VT = CmpOp.getValueType();
2365 
2366     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2367       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2368                           ISD::SETLE);
2369     } else {
2370       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2371                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2372       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2373                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2374     }
2375   }
2376 
2377   // Update successor info
2378   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2379   // TrueBB and FalseBB are always different unless the incoming IR is
2380   // degenerate. This only happens when running llc on weird IR.
2381   if (CB.TrueBB != CB.FalseBB)
2382     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2383   SwitchBB->normalizeSuccProbs();
2384 
2385   // If the lhs block is the next block, invert the condition so that we can
2386   // fall through to the lhs instead of the rhs block.
2387   if (CB.TrueBB == NextBlock(SwitchBB)) {
2388     std::swap(CB.TrueBB, CB.FalseBB);
2389     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2390     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2391   }
2392 
2393   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2394                                MVT::Other, getControlRoot(), Cond,
2395                                DAG.getBasicBlock(CB.TrueBB));
2396 
2397   // Insert the false branch. Do this even if it's a fall through branch,
2398   // this makes it easier to do DAG optimizations which require inverting
2399   // the branch condition.
2400   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2401                        DAG.getBasicBlock(CB.FalseBB));
2402 
2403   DAG.setRoot(BrCond);
2404 }
2405 
2406 /// visitJumpTable - Emit JumpTable node in the current MBB
2407 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2408   // Emit the code for the jump table
2409   assert(JT.Reg != -1U && "Should lower JT Header first!");
2410   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2411   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2412                                      JT.Reg, PTy);
2413   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2414   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2415                                     MVT::Other, Index.getValue(1),
2416                                     Table, Index);
2417   DAG.setRoot(BrJumpTable);
2418 }
2419 
2420 /// visitJumpTableHeader - This function emits necessary code to produce index
2421 /// in the JumpTable from switch case.
2422 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2423                                                JumpTableHeader &JTH,
2424                                                MachineBasicBlock *SwitchBB) {
2425   SDLoc dl = getCurSDLoc();
2426 
2427   // Subtract the lowest switch case value from the value being switched on.
2428   SDValue SwitchOp = getValue(JTH.SValue);
2429   EVT VT = SwitchOp.getValueType();
2430   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2431                             DAG.getConstant(JTH.First, dl, VT));
2432 
2433   // The SDNode we just created, which holds the value being switched on minus
2434   // the smallest case value, needs to be copied to a virtual register so it
2435   // can be used as an index into the jump table in a subsequent basic block.
2436   // This value may be smaller or larger than the target's pointer type, and
2437   // therefore require extension or truncating.
2438   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2439   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2440 
2441   unsigned JumpTableReg =
2442       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2443   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2444                                     JumpTableReg, SwitchOp);
2445   JT.Reg = JumpTableReg;
2446 
2447   if (!JTH.OmitRangeCheck) {
2448     // Emit the range check for the jump table, and branch to the default block
2449     // for the switch statement if the value being switched on exceeds the
2450     // largest case in the switch.
2451     SDValue CMP = DAG.getSetCC(
2452         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2453                                    Sub.getValueType()),
2454         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2455 
2456     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2457                                  MVT::Other, CopyTo, CMP,
2458                                  DAG.getBasicBlock(JT.Default));
2459 
2460     // Avoid emitting unnecessary branches to the next block.
2461     if (JT.MBB != NextBlock(SwitchBB))
2462       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2463                            DAG.getBasicBlock(JT.MBB));
2464 
2465     DAG.setRoot(BrCond);
2466   } else {
2467     // Avoid emitting unnecessary branches to the next block.
2468     if (JT.MBB != NextBlock(SwitchBB))
2469       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2470                               DAG.getBasicBlock(JT.MBB)));
2471     else
2472       DAG.setRoot(CopyTo);
2473   }
2474 }
2475 
2476 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2477 /// variable if there exists one.
2478 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2479                                  SDValue &Chain) {
2480   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2481   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2482   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2483   MachineFunction &MF = DAG.getMachineFunction();
2484   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2485   MachineSDNode *Node =
2486       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2487   if (Global) {
2488     MachinePointerInfo MPInfo(Global);
2489     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2490                  MachineMemOperand::MODereferenceable;
2491     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2492         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2493     DAG.setNodeMemRefs(Node, {MemRef});
2494   }
2495   if (PtrTy != PtrMemTy)
2496     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2497   return SDValue(Node, 0);
2498 }
2499 
2500 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2501 /// tail spliced into a stack protector check success bb.
2502 ///
2503 /// For a high level explanation of how this fits into the stack protector
2504 /// generation see the comment on the declaration of class
2505 /// StackProtectorDescriptor.
2506 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2507                                                   MachineBasicBlock *ParentBB) {
2508 
2509   // First create the loads to the guard/stack slot for the comparison.
2510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2511   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2512   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2513 
2514   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2515   int FI = MFI.getStackProtectorIndex();
2516 
2517   SDValue Guard;
2518   SDLoc dl = getCurSDLoc();
2519   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2520   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2521   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2522 
2523   // Generate code to load the content of the guard slot.
2524   SDValue GuardVal = DAG.getLoad(
2525       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2526       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2527       MachineMemOperand::MOVolatile);
2528 
2529   if (TLI.useStackGuardXorFP())
2530     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2531 
2532   // Retrieve guard check function, nullptr if instrumentation is inlined.
2533   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2534     // The target provides a guard check function to validate the guard value.
2535     // Generate a call to that function with the content of the guard slot as
2536     // argument.
2537     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2538     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2539 
2540     TargetLowering::ArgListTy Args;
2541     TargetLowering::ArgListEntry Entry;
2542     Entry.Node = GuardVal;
2543     Entry.Ty = FnTy->getParamType(0);
2544     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2545       Entry.IsInReg = true;
2546     Args.push_back(Entry);
2547 
2548     TargetLowering::CallLoweringInfo CLI(DAG);
2549     CLI.setDebugLoc(getCurSDLoc())
2550         .setChain(DAG.getEntryNode())
2551         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2552                    getValue(GuardCheckFn), std::move(Args));
2553 
2554     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2555     DAG.setRoot(Result.second);
2556     return;
2557   }
2558 
2559   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2560   // Otherwise, emit a volatile load to retrieve the stack guard value.
2561   SDValue Chain = DAG.getEntryNode();
2562   if (TLI.useLoadStackGuardNode()) {
2563     Guard = getLoadStackGuard(DAG, dl, Chain);
2564   } else {
2565     const Value *IRGuard = TLI.getSDagStackGuard(M);
2566     SDValue GuardPtr = getValue(IRGuard);
2567 
2568     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2569                         MachinePointerInfo(IRGuard, 0), Align,
2570                         MachineMemOperand::MOVolatile);
2571   }
2572 
2573   // Perform the comparison via a subtract/getsetcc.
2574   EVT VT = Guard.getValueType();
2575   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2576 
2577   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2578                                                         *DAG.getContext(),
2579                                                         Sub.getValueType()),
2580                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2581 
2582   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2583   // branch to failure MBB.
2584   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2585                                MVT::Other, GuardVal.getOperand(0),
2586                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2587   // Otherwise branch to success MBB.
2588   SDValue Br = DAG.getNode(ISD::BR, dl,
2589                            MVT::Other, BrCond,
2590                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2591 
2592   DAG.setRoot(Br);
2593 }
2594 
2595 /// Codegen the failure basic block for a stack protector check.
2596 ///
2597 /// A failure stack protector machine basic block consists simply of a call to
2598 /// __stack_chk_fail().
2599 ///
2600 /// For a high level explanation of how this fits into the stack protector
2601 /// generation see the comment on the declaration of class
2602 /// StackProtectorDescriptor.
2603 void
2604 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2605   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2606   TargetLowering::MakeLibCallOptions CallOptions;
2607   CallOptions.setDiscardResult(true);
2608   SDValue Chain =
2609       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2610                       None, CallOptions, getCurSDLoc()).second;
2611   // On PS4, the "return address" must still be within the calling function,
2612   // even if it's at the very end, so emit an explicit TRAP here.
2613   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2614   if (TM.getTargetTriple().isPS4CPU())
2615     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2616 
2617   DAG.setRoot(Chain);
2618 }
2619 
2620 /// visitBitTestHeader - This function emits necessary code to produce value
2621 /// suitable for "bit tests"
2622 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2623                                              MachineBasicBlock *SwitchBB) {
2624   SDLoc dl = getCurSDLoc();
2625 
2626   // Subtract the minimum value.
2627   SDValue SwitchOp = getValue(B.SValue);
2628   EVT VT = SwitchOp.getValueType();
2629   SDValue RangeSub =
2630       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
2631 
2632   // Determine the type of the test operands.
2633   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2634   bool UsePtrType = false;
2635   if (!TLI.isTypeLegal(VT)) {
2636     UsePtrType = true;
2637   } else {
2638     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2639       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2640         // Switch table case range are encoded into series of masks.
2641         // Just use pointer type, it's guaranteed to fit.
2642         UsePtrType = true;
2643         break;
2644       }
2645   }
2646   SDValue Sub = RangeSub;
2647   if (UsePtrType) {
2648     VT = TLI.getPointerTy(DAG.getDataLayout());
2649     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2650   }
2651 
2652   B.RegVT = VT.getSimpleVT();
2653   B.Reg = FuncInfo.CreateReg(B.RegVT);
2654   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2655 
2656   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2657 
2658   if (!B.OmitRangeCheck)
2659     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2660   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2661   SwitchBB->normalizeSuccProbs();
2662 
2663   SDValue Root = CopyTo;
2664   if (!B.OmitRangeCheck) {
2665     // Conditional branch to the default block.
2666     SDValue RangeCmp = DAG.getSetCC(dl,
2667         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2668                                RangeSub.getValueType()),
2669         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
2670         ISD::SETUGT);
2671 
2672     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
2673                        DAG.getBasicBlock(B.Default));
2674   }
2675 
2676   // Avoid emitting unnecessary branches to the next block.
2677   if (MBB != NextBlock(SwitchBB))
2678     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
2679 
2680   DAG.setRoot(Root);
2681 }
2682 
2683 /// visitBitTestCase - this function produces one "bit test"
2684 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2685                                            MachineBasicBlock* NextMBB,
2686                                            BranchProbability BranchProbToNext,
2687                                            unsigned Reg,
2688                                            BitTestCase &B,
2689                                            MachineBasicBlock *SwitchBB) {
2690   SDLoc dl = getCurSDLoc();
2691   MVT VT = BB.RegVT;
2692   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2693   SDValue Cmp;
2694   unsigned PopCount = countPopulation(B.Mask);
2695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2696   if (PopCount == 1) {
2697     // Testing for a single bit; just compare the shift count with what it
2698     // would need to be to shift a 1 bit in that position.
2699     Cmp = DAG.getSetCC(
2700         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2701         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2702         ISD::SETEQ);
2703   } else if (PopCount == BB.Range) {
2704     // There is only one zero bit in the range, test for it directly.
2705     Cmp = DAG.getSetCC(
2706         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2707         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2708         ISD::SETNE);
2709   } else {
2710     // Make desired shift
2711     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2712                                     DAG.getConstant(1, dl, VT), ShiftOp);
2713 
2714     // Emit bit tests and jumps
2715     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2716                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2717     Cmp = DAG.getSetCC(
2718         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2719         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2720   }
2721 
2722   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2723   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2724   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2725   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2726   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2727   // one as they are relative probabilities (and thus work more like weights),
2728   // and hence we need to normalize them to let the sum of them become one.
2729   SwitchBB->normalizeSuccProbs();
2730 
2731   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2732                               MVT::Other, getControlRoot(),
2733                               Cmp, DAG.getBasicBlock(B.TargetBB));
2734 
2735   // Avoid emitting unnecessary branches to the next block.
2736   if (NextMBB != NextBlock(SwitchBB))
2737     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2738                         DAG.getBasicBlock(NextMBB));
2739 
2740   DAG.setRoot(BrAnd);
2741 }
2742 
2743 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2744   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2745 
2746   // Retrieve successors. Look through artificial IR level blocks like
2747   // catchswitch for successors.
2748   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2749   const BasicBlock *EHPadBB = I.getSuccessor(1);
2750 
2751   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2752   // have to do anything here to lower funclet bundles.
2753   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
2754                                         LLVMContext::OB_funclet,
2755                                         LLVMContext::OB_cfguardtarget}) &&
2756          "Cannot lower invokes with arbitrary operand bundles yet!");
2757 
2758   const Value *Callee(I.getCalledValue());
2759   const Function *Fn = dyn_cast<Function>(Callee);
2760   if (isa<InlineAsm>(Callee))
2761     visitInlineAsm(&I);
2762   else if (Fn && Fn->isIntrinsic()) {
2763     switch (Fn->getIntrinsicID()) {
2764     default:
2765       llvm_unreachable("Cannot invoke this intrinsic");
2766     case Intrinsic::donothing:
2767       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2768       break;
2769     case Intrinsic::experimental_patchpoint_void:
2770     case Intrinsic::experimental_patchpoint_i64:
2771       visitPatchpoint(&I, EHPadBB);
2772       break;
2773     case Intrinsic::experimental_gc_statepoint:
2774       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2775       break;
2776     case Intrinsic::wasm_rethrow_in_catch: {
2777       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2778       // special because it can be invoked, so we manually lower it to a DAG
2779       // node here.
2780       SmallVector<SDValue, 8> Ops;
2781       Ops.push_back(getRoot()); // inchain
2782       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2783       Ops.push_back(
2784           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2785                                 TLI.getPointerTy(DAG.getDataLayout())));
2786       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2787       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2788       break;
2789     }
2790     }
2791   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2792     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2793     // Eventually we will support lowering the @llvm.experimental.deoptimize
2794     // intrinsic, and right now there are no plans to support other intrinsics
2795     // with deopt state.
2796     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2797   } else {
2798     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2799   }
2800 
2801   // If the value of the invoke is used outside of its defining block, make it
2802   // available as a virtual register.
2803   // We already took care of the exported value for the statepoint instruction
2804   // during call to the LowerStatepoint.
2805   if (!isStatepoint(I)) {
2806     CopyToExportRegsIfNeeded(&I);
2807   }
2808 
2809   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2810   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2811   BranchProbability EHPadBBProb =
2812       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2813           : BranchProbability::getZero();
2814   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2815 
2816   // Update successor info.
2817   addSuccessorWithProb(InvokeMBB, Return);
2818   for (auto &UnwindDest : UnwindDests) {
2819     UnwindDest.first->setIsEHPad();
2820     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2821   }
2822   InvokeMBB->normalizeSuccProbs();
2823 
2824   // Drop into normal successor.
2825   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2826                           DAG.getBasicBlock(Return)));
2827 }
2828 
2829 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2830   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2831 
2832   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2833   // have to do anything here to lower funclet bundles.
2834   assert(!I.hasOperandBundlesOtherThan(
2835              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2836          "Cannot lower callbrs with arbitrary operand bundles yet!");
2837 
2838   assert(isa<InlineAsm>(I.getCalledValue()) &&
2839          "Only know how to handle inlineasm callbr");
2840   visitInlineAsm(&I);
2841 
2842   // Retrieve successors.
2843   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2844 
2845   // Update successor info.
2846   addSuccessorWithProb(CallBrMBB, Return);
2847   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2848     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2849     addSuccessorWithProb(CallBrMBB, Target);
2850   }
2851   CallBrMBB->normalizeSuccProbs();
2852 
2853   // Drop into default successor.
2854   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2855                           MVT::Other, getControlRoot(),
2856                           DAG.getBasicBlock(Return)));
2857 }
2858 
2859 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2860   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2861 }
2862 
2863 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2864   assert(FuncInfo.MBB->isEHPad() &&
2865          "Call to landingpad not in landing pad!");
2866 
2867   // If there aren't registers to copy the values into (e.g., during SjLj
2868   // exceptions), then don't bother to create these DAG nodes.
2869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2870   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2871   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2872       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2873     return;
2874 
2875   // If landingpad's return type is token type, we don't create DAG nodes
2876   // for its exception pointer and selector value. The extraction of exception
2877   // pointer or selector value from token type landingpads is not currently
2878   // supported.
2879   if (LP.getType()->isTokenTy())
2880     return;
2881 
2882   SmallVector<EVT, 2> ValueVTs;
2883   SDLoc dl = getCurSDLoc();
2884   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2885   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2886 
2887   // Get the two live-in registers as SDValues. The physregs have already been
2888   // copied into virtual registers.
2889   SDValue Ops[2];
2890   if (FuncInfo.ExceptionPointerVirtReg) {
2891     Ops[0] = DAG.getZExtOrTrunc(
2892         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2893                            FuncInfo.ExceptionPointerVirtReg,
2894                            TLI.getPointerTy(DAG.getDataLayout())),
2895         dl, ValueVTs[0]);
2896   } else {
2897     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2898   }
2899   Ops[1] = DAG.getZExtOrTrunc(
2900       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2901                          FuncInfo.ExceptionSelectorVirtReg,
2902                          TLI.getPointerTy(DAG.getDataLayout())),
2903       dl, ValueVTs[1]);
2904 
2905   // Merge into one.
2906   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2907                             DAG.getVTList(ValueVTs), Ops);
2908   setValue(&LP, Res);
2909 }
2910 
2911 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2912                                            MachineBasicBlock *Last) {
2913   // Update JTCases.
2914   for (unsigned i = 0, e = SL->JTCases.size(); i != e; ++i)
2915     if (SL->JTCases[i].first.HeaderBB == First)
2916       SL->JTCases[i].first.HeaderBB = Last;
2917 
2918   // Update BitTestCases.
2919   for (unsigned i = 0, e = SL->BitTestCases.size(); i != e; ++i)
2920     if (SL->BitTestCases[i].Parent == First)
2921       SL->BitTestCases[i].Parent = Last;
2922 }
2923 
2924 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2925   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2926 
2927   // Update machine-CFG edges with unique successors.
2928   SmallSet<BasicBlock*, 32> Done;
2929   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2930     BasicBlock *BB = I.getSuccessor(i);
2931     bool Inserted = Done.insert(BB).second;
2932     if (!Inserted)
2933         continue;
2934 
2935     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2936     addSuccessorWithProb(IndirectBrMBB, Succ);
2937   }
2938   IndirectBrMBB->normalizeSuccProbs();
2939 
2940   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2941                           MVT::Other, getControlRoot(),
2942                           getValue(I.getAddress())));
2943 }
2944 
2945 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2946   if (!DAG.getTarget().Options.TrapUnreachable)
2947     return;
2948 
2949   // We may be able to ignore unreachable behind a noreturn call.
2950   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2951     const BasicBlock &BB = *I.getParent();
2952     if (&I != &BB.front()) {
2953       BasicBlock::const_iterator PredI =
2954         std::prev(BasicBlock::const_iterator(&I));
2955       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2956         if (Call->doesNotReturn())
2957           return;
2958       }
2959     }
2960   }
2961 
2962   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2963 }
2964 
2965 void SelectionDAGBuilder::visitFSub(const User &I) {
2966   // -0.0 - X --> fneg
2967   Type *Ty = I.getType();
2968   if (isa<Constant>(I.getOperand(0)) &&
2969       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2970     SDValue Op2 = getValue(I.getOperand(1));
2971     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2972                              Op2.getValueType(), Op2));
2973     return;
2974   }
2975 
2976   visitBinary(I, ISD::FSUB);
2977 }
2978 
2979 /// Checks if the given instruction performs a vector reduction, in which case
2980 /// we have the freedom to alter the elements in the result as long as the
2981 /// reduction of them stays unchanged.
2982 static bool isVectorReductionOp(const User *I) {
2983   const Instruction *Inst = dyn_cast<Instruction>(I);
2984   if (!Inst || !Inst->getType()->isVectorTy())
2985     return false;
2986 
2987   auto OpCode = Inst->getOpcode();
2988   switch (OpCode) {
2989   case Instruction::Add:
2990   case Instruction::Mul:
2991   case Instruction::And:
2992   case Instruction::Or:
2993   case Instruction::Xor:
2994     break;
2995   case Instruction::FAdd:
2996   case Instruction::FMul:
2997     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2998       if (FPOp->getFastMathFlags().isFast())
2999         break;
3000     LLVM_FALLTHROUGH;
3001   default:
3002     return false;
3003   }
3004 
3005   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3006   // Ensure the reduction size is a power of 2.
3007   if (!isPowerOf2_32(ElemNum))
3008     return false;
3009 
3010   unsigned ElemNumToReduce = ElemNum;
3011 
3012   // Do DFS search on the def-use chain from the given instruction. We only
3013   // allow four kinds of operations during the search until we reach the
3014   // instruction that extracts the first element from the vector:
3015   //
3016   //   1. The reduction operation of the same opcode as the given instruction.
3017   //
3018   //   2. PHI node.
3019   //
3020   //   3. ShuffleVector instruction together with a reduction operation that
3021   //      does a partial reduction.
3022   //
3023   //   4. ExtractElement that extracts the first element from the vector, and we
3024   //      stop searching the def-use chain here.
3025   //
3026   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3027   // from 1-3 to the stack to continue the DFS. The given instruction is not
3028   // a reduction operation if we meet any other instructions other than those
3029   // listed above.
3030 
3031   SmallVector<const User *, 16> UsersToVisit{Inst};
3032   SmallPtrSet<const User *, 16> Visited;
3033   bool ReduxExtracted = false;
3034 
3035   while (!UsersToVisit.empty()) {
3036     auto User = UsersToVisit.back();
3037     UsersToVisit.pop_back();
3038     if (!Visited.insert(User).second)
3039       continue;
3040 
3041     for (const auto &U : User->users()) {
3042       auto Inst = dyn_cast<Instruction>(U);
3043       if (!Inst)
3044         return false;
3045 
3046       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3047         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3048           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3049             return false;
3050         UsersToVisit.push_back(U);
3051       } else if (const ShuffleVectorInst *ShufInst =
3052                      dyn_cast<ShuffleVectorInst>(U)) {
3053         // Detect the following pattern: A ShuffleVector instruction together
3054         // with a reduction that do partial reduction on the first and second
3055         // ElemNumToReduce / 2 elements, and store the result in
3056         // ElemNumToReduce / 2 elements in another vector.
3057 
3058         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3059         if (ResultElements < ElemNum)
3060           return false;
3061 
3062         if (ElemNumToReduce == 1)
3063           return false;
3064         if (!isa<UndefValue>(U->getOperand(1)))
3065           return false;
3066         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3067           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3068             return false;
3069         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3070           if (ShufInst->getMaskValue(i) != -1)
3071             return false;
3072 
3073         // There is only one user of this ShuffleVector instruction, which
3074         // must be a reduction operation.
3075         if (!U->hasOneUse())
3076           return false;
3077 
3078         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3079         if (!U2 || U2->getOpcode() != OpCode)
3080           return false;
3081 
3082         // Check operands of the reduction operation.
3083         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3084             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3085           UsersToVisit.push_back(U2);
3086           ElemNumToReduce /= 2;
3087         } else
3088           return false;
3089       } else if (isa<ExtractElementInst>(U)) {
3090         // At this moment we should have reduced all elements in the vector.
3091         if (ElemNumToReduce != 1)
3092           return false;
3093 
3094         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3095         if (!Val || !Val->isZero())
3096           return false;
3097 
3098         ReduxExtracted = true;
3099       } else
3100         return false;
3101     }
3102   }
3103   return ReduxExtracted;
3104 }
3105 
3106 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3107   SDNodeFlags Flags;
3108 
3109   SDValue Op = getValue(I.getOperand(0));
3110   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3111                                     Op, Flags);
3112   setValue(&I, UnNodeValue);
3113 }
3114 
3115 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3116   SDNodeFlags Flags;
3117   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3118     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3119     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3120   }
3121   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3122     Flags.setExact(ExactOp->isExact());
3123   }
3124   if (isVectorReductionOp(&I)) {
3125     Flags.setVectorReduction(true);
3126     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3127   }
3128 
3129   SDValue Op1 = getValue(I.getOperand(0));
3130   SDValue Op2 = getValue(I.getOperand(1));
3131   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3132                                      Op1, Op2, Flags);
3133   setValue(&I, BinNodeValue);
3134 }
3135 
3136 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3137   SDValue Op1 = getValue(I.getOperand(0));
3138   SDValue Op2 = getValue(I.getOperand(1));
3139 
3140   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3141       Op1.getValueType(), DAG.getDataLayout());
3142 
3143   // Coerce the shift amount to the right type if we can.
3144   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3145     unsigned ShiftSize = ShiftTy.getSizeInBits();
3146     unsigned Op2Size = Op2.getValueSizeInBits();
3147     SDLoc DL = getCurSDLoc();
3148 
3149     // If the operand is smaller than the shift count type, promote it.
3150     if (ShiftSize > Op2Size)
3151       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3152 
3153     // If the operand is larger than the shift count type but the shift
3154     // count type has enough bits to represent any shift value, truncate
3155     // it now. This is a common case and it exposes the truncate to
3156     // optimization early.
3157     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3158       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3159     // Otherwise we'll need to temporarily settle for some other convenient
3160     // type.  Type legalization will make adjustments once the shiftee is split.
3161     else
3162       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3163   }
3164 
3165   bool nuw = false;
3166   bool nsw = false;
3167   bool exact = false;
3168 
3169   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3170 
3171     if (const OverflowingBinaryOperator *OFBinOp =
3172             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3173       nuw = OFBinOp->hasNoUnsignedWrap();
3174       nsw = OFBinOp->hasNoSignedWrap();
3175     }
3176     if (const PossiblyExactOperator *ExactOp =
3177             dyn_cast<const PossiblyExactOperator>(&I))
3178       exact = ExactOp->isExact();
3179   }
3180   SDNodeFlags Flags;
3181   Flags.setExact(exact);
3182   Flags.setNoSignedWrap(nsw);
3183   Flags.setNoUnsignedWrap(nuw);
3184   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3185                             Flags);
3186   setValue(&I, Res);
3187 }
3188 
3189 void SelectionDAGBuilder::visitSDiv(const User &I) {
3190   SDValue Op1 = getValue(I.getOperand(0));
3191   SDValue Op2 = getValue(I.getOperand(1));
3192 
3193   SDNodeFlags Flags;
3194   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3195                  cast<PossiblyExactOperator>(&I)->isExact());
3196   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3197                            Op2, Flags));
3198 }
3199 
3200 void SelectionDAGBuilder::visitICmp(const User &I) {
3201   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3202   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3203     predicate = IC->getPredicate();
3204   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3205     predicate = ICmpInst::Predicate(IC->getPredicate());
3206   SDValue Op1 = getValue(I.getOperand(0));
3207   SDValue Op2 = getValue(I.getOperand(1));
3208   ISD::CondCode Opcode = getICmpCondCode(predicate);
3209 
3210   auto &TLI = DAG.getTargetLoweringInfo();
3211   EVT MemVT =
3212       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3213 
3214   // If a pointer's DAG type is larger than its memory type then the DAG values
3215   // are zero-extended. This breaks signed comparisons so truncate back to the
3216   // underlying type before doing the compare.
3217   if (Op1.getValueType() != MemVT) {
3218     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3219     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3220   }
3221 
3222   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3223                                                         I.getType());
3224   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3225 }
3226 
3227 void SelectionDAGBuilder::visitFCmp(const User &I) {
3228   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3229   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3230     predicate = FC->getPredicate();
3231   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3232     predicate = FCmpInst::Predicate(FC->getPredicate());
3233   SDValue Op1 = getValue(I.getOperand(0));
3234   SDValue Op2 = getValue(I.getOperand(1));
3235 
3236   ISD::CondCode Condition = getFCmpCondCode(predicate);
3237   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3238   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3239     Condition = getFCmpCodeWithoutNaN(Condition);
3240 
3241   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3242                                                         I.getType());
3243   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3244 }
3245 
3246 // Check if the condition of the select has one use or two users that are both
3247 // selects with the same condition.
3248 static bool hasOnlySelectUsers(const Value *Cond) {
3249   return llvm::all_of(Cond->users(), [](const Value *V) {
3250     return isa<SelectInst>(V);
3251   });
3252 }
3253 
3254 void SelectionDAGBuilder::visitSelect(const User &I) {
3255   SmallVector<EVT, 4> ValueVTs;
3256   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3257                   ValueVTs);
3258   unsigned NumValues = ValueVTs.size();
3259   if (NumValues == 0) return;
3260 
3261   SmallVector<SDValue, 4> Values(NumValues);
3262   SDValue Cond     = getValue(I.getOperand(0));
3263   SDValue LHSVal   = getValue(I.getOperand(1));
3264   SDValue RHSVal   = getValue(I.getOperand(2));
3265   auto BaseOps = {Cond};
3266   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3267     ISD::VSELECT : ISD::SELECT;
3268 
3269   bool IsUnaryAbs = false;
3270 
3271   // Min/max matching is only viable if all output VTs are the same.
3272   if (is_splat(ValueVTs)) {
3273     EVT VT = ValueVTs[0];
3274     LLVMContext &Ctx = *DAG.getContext();
3275     auto &TLI = DAG.getTargetLoweringInfo();
3276 
3277     // We care about the legality of the operation after it has been type
3278     // legalized.
3279     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3280       VT = TLI.getTypeToTransformTo(Ctx, VT);
3281 
3282     // If the vselect is legal, assume we want to leave this as a vector setcc +
3283     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3284     // min/max is legal on the scalar type.
3285     bool UseScalarMinMax = VT.isVector() &&
3286       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3287 
3288     Value *LHS, *RHS;
3289     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3290     ISD::NodeType Opc = ISD::DELETED_NODE;
3291     switch (SPR.Flavor) {
3292     case SPF_UMAX:    Opc = ISD::UMAX; break;
3293     case SPF_UMIN:    Opc = ISD::UMIN; break;
3294     case SPF_SMAX:    Opc = ISD::SMAX; break;
3295     case SPF_SMIN:    Opc = ISD::SMIN; break;
3296     case SPF_FMINNUM:
3297       switch (SPR.NaNBehavior) {
3298       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3299       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3300       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3301       case SPNB_RETURNS_ANY: {
3302         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3303           Opc = ISD::FMINNUM;
3304         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3305           Opc = ISD::FMINIMUM;
3306         else if (UseScalarMinMax)
3307           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3308             ISD::FMINNUM : ISD::FMINIMUM;
3309         break;
3310       }
3311       }
3312       break;
3313     case SPF_FMAXNUM:
3314       switch (SPR.NaNBehavior) {
3315       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3316       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3317       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3318       case SPNB_RETURNS_ANY:
3319 
3320         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3321           Opc = ISD::FMAXNUM;
3322         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3323           Opc = ISD::FMAXIMUM;
3324         else if (UseScalarMinMax)
3325           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3326             ISD::FMAXNUM : ISD::FMAXIMUM;
3327         break;
3328       }
3329       break;
3330     case SPF_ABS:
3331       IsUnaryAbs = true;
3332       Opc = ISD::ABS;
3333       break;
3334     case SPF_NABS:
3335       // TODO: we need to produce sub(0, abs(X)).
3336     default: break;
3337     }
3338 
3339     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3340         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3341          (UseScalarMinMax &&
3342           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3343         // If the underlying comparison instruction is used by any other
3344         // instruction, the consumed instructions won't be destroyed, so it is
3345         // not profitable to convert to a min/max.
3346         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3347       OpCode = Opc;
3348       LHSVal = getValue(LHS);
3349       RHSVal = getValue(RHS);
3350       BaseOps = {};
3351     }
3352 
3353     if (IsUnaryAbs) {
3354       OpCode = Opc;
3355       LHSVal = getValue(LHS);
3356       BaseOps = {};
3357     }
3358   }
3359 
3360   if (IsUnaryAbs) {
3361     for (unsigned i = 0; i != NumValues; ++i) {
3362       Values[i] =
3363           DAG.getNode(OpCode, getCurSDLoc(),
3364                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3365                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3366     }
3367   } else {
3368     for (unsigned i = 0; i != NumValues; ++i) {
3369       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3370       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3371       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3372       Values[i] = DAG.getNode(
3373           OpCode, getCurSDLoc(),
3374           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3375     }
3376   }
3377 
3378   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3379                            DAG.getVTList(ValueVTs), Values));
3380 }
3381 
3382 void SelectionDAGBuilder::visitTrunc(const User &I) {
3383   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3384   SDValue N = getValue(I.getOperand(0));
3385   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3386                                                         I.getType());
3387   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3388 }
3389 
3390 void SelectionDAGBuilder::visitZExt(const User &I) {
3391   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3392   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3393   SDValue N = getValue(I.getOperand(0));
3394   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3395                                                         I.getType());
3396   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3397 }
3398 
3399 void SelectionDAGBuilder::visitSExt(const User &I) {
3400   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3401   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3402   SDValue N = getValue(I.getOperand(0));
3403   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3404                                                         I.getType());
3405   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3406 }
3407 
3408 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3409   // FPTrunc is never a no-op cast, no need to check
3410   SDValue N = getValue(I.getOperand(0));
3411   SDLoc dl = getCurSDLoc();
3412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3413   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3414   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3415                            DAG.getTargetConstant(
3416                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3417 }
3418 
3419 void SelectionDAGBuilder::visitFPExt(const User &I) {
3420   // FPExt is never a no-op cast, no need to check
3421   SDValue N = getValue(I.getOperand(0));
3422   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3423                                                         I.getType());
3424   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3425 }
3426 
3427 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3428   // FPToUI is never a no-op cast, no need to check
3429   SDValue N = getValue(I.getOperand(0));
3430   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3431                                                         I.getType());
3432   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3433 }
3434 
3435 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3436   // FPToSI is never a no-op cast, no need to check
3437   SDValue N = getValue(I.getOperand(0));
3438   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3439                                                         I.getType());
3440   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3441 }
3442 
3443 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3444   // UIToFP is never a no-op cast, no need to check
3445   SDValue N = getValue(I.getOperand(0));
3446   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3447                                                         I.getType());
3448   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3449 }
3450 
3451 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3452   // SIToFP is never a no-op cast, no need to check
3453   SDValue N = getValue(I.getOperand(0));
3454   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3455                                                         I.getType());
3456   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3457 }
3458 
3459 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3460   // What to do depends on the size of the integer and the size of the pointer.
3461   // We can either truncate, zero extend, or no-op, accordingly.
3462   SDValue N = getValue(I.getOperand(0));
3463   auto &TLI = DAG.getTargetLoweringInfo();
3464   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3465                                                         I.getType());
3466   EVT PtrMemVT =
3467       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3468   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3469   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3470   setValue(&I, N);
3471 }
3472 
3473 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3474   // What to do depends on the size of the integer and the size of the pointer.
3475   // We can either truncate, zero extend, or no-op, accordingly.
3476   SDValue N = getValue(I.getOperand(0));
3477   auto &TLI = DAG.getTargetLoweringInfo();
3478   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3479   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3480   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3481   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3482   setValue(&I, N);
3483 }
3484 
3485 void SelectionDAGBuilder::visitBitCast(const User &I) {
3486   SDValue N = getValue(I.getOperand(0));
3487   SDLoc dl = getCurSDLoc();
3488   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3489                                                         I.getType());
3490 
3491   // BitCast assures us that source and destination are the same size so this is
3492   // either a BITCAST or a no-op.
3493   if (DestVT != N.getValueType())
3494     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3495                              DestVT, N)); // convert types.
3496   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3497   // might fold any kind of constant expression to an integer constant and that
3498   // is not what we are looking for. Only recognize a bitcast of a genuine
3499   // constant integer as an opaque constant.
3500   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3501     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3502                                  /*isOpaque*/true));
3503   else
3504     setValue(&I, N);            // noop cast.
3505 }
3506 
3507 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3508   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3509   const Value *SV = I.getOperand(0);
3510   SDValue N = getValue(SV);
3511   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3512 
3513   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3514   unsigned DestAS = I.getType()->getPointerAddressSpace();
3515 
3516   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3517     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3518 
3519   setValue(&I, N);
3520 }
3521 
3522 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3524   SDValue InVec = getValue(I.getOperand(0));
3525   SDValue InVal = getValue(I.getOperand(1));
3526   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3527                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3528   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3529                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3530                            InVec, InVal, InIdx));
3531 }
3532 
3533 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3534   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3535   SDValue InVec = getValue(I.getOperand(0));
3536   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3537                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3538   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3539                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3540                            InVec, InIdx));
3541 }
3542 
3543 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3544   SDValue Src1 = getValue(I.getOperand(0));
3545   SDValue Src2 = getValue(I.getOperand(1));
3546   Constant *MaskV = cast<Constant>(I.getOperand(2));
3547   SDLoc DL = getCurSDLoc();
3548   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3549   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3550   EVT SrcVT = Src1.getValueType();
3551   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3552 
3553   if (MaskV->isNullValue() && VT.isScalableVector()) {
3554     // Canonical splat form of first element of first input vector.
3555     SDValue FirstElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3556                                    SrcVT.getScalarType(), Src1,
3557                                    DAG.getConstant(0, DL,
3558                                    TLI.getVectorIdxTy(DAG.getDataLayout())));
3559     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
3560     return;
3561   }
3562 
3563   // For now, we only handle splats for scalable vectors.
3564   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
3565   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
3566   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
3567 
3568   SmallVector<int, 8> Mask;
3569   ShuffleVectorInst::getShuffleMask(MaskV, Mask);
3570   unsigned MaskNumElts = Mask.size();
3571 
3572   if (SrcNumElts == MaskNumElts) {
3573     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3574     return;
3575   }
3576 
3577   // Normalize the shuffle vector since mask and vector length don't match.
3578   if (SrcNumElts < MaskNumElts) {
3579     // Mask is longer than the source vectors. We can use concatenate vector to
3580     // make the mask and vectors lengths match.
3581 
3582     if (MaskNumElts % SrcNumElts == 0) {
3583       // Mask length is a multiple of the source vector length.
3584       // Check if the shuffle is some kind of concatenation of the input
3585       // vectors.
3586       unsigned NumConcat = MaskNumElts / SrcNumElts;
3587       bool IsConcat = true;
3588       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3589       for (unsigned i = 0; i != MaskNumElts; ++i) {
3590         int Idx = Mask[i];
3591         if (Idx < 0)
3592           continue;
3593         // Ensure the indices in each SrcVT sized piece are sequential and that
3594         // the same source is used for the whole piece.
3595         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3596             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3597              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3598           IsConcat = false;
3599           break;
3600         }
3601         // Remember which source this index came from.
3602         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3603       }
3604 
3605       // The shuffle is concatenating multiple vectors together. Just emit
3606       // a CONCAT_VECTORS operation.
3607       if (IsConcat) {
3608         SmallVector<SDValue, 8> ConcatOps;
3609         for (auto Src : ConcatSrcs) {
3610           if (Src < 0)
3611             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3612           else if (Src == 0)
3613             ConcatOps.push_back(Src1);
3614           else
3615             ConcatOps.push_back(Src2);
3616         }
3617         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3618         return;
3619       }
3620     }
3621 
3622     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3623     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3624     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3625                                     PaddedMaskNumElts);
3626 
3627     // Pad both vectors with undefs to make them the same length as the mask.
3628     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3629 
3630     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3631     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3632     MOps1[0] = Src1;
3633     MOps2[0] = Src2;
3634 
3635     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3636     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3637 
3638     // Readjust mask for new input vector length.
3639     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3640     for (unsigned i = 0; i != MaskNumElts; ++i) {
3641       int Idx = Mask[i];
3642       if (Idx >= (int)SrcNumElts)
3643         Idx -= SrcNumElts - PaddedMaskNumElts;
3644       MappedOps[i] = Idx;
3645     }
3646 
3647     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3648 
3649     // If the concatenated vector was padded, extract a subvector with the
3650     // correct number of elements.
3651     if (MaskNumElts != PaddedMaskNumElts)
3652       Result = DAG.getNode(
3653           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3654           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3655 
3656     setValue(&I, Result);
3657     return;
3658   }
3659 
3660   if (SrcNumElts > MaskNumElts) {
3661     // Analyze the access pattern of the vector to see if we can extract
3662     // two subvectors and do the shuffle.
3663     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3664     bool CanExtract = true;
3665     for (int Idx : Mask) {
3666       unsigned Input = 0;
3667       if (Idx < 0)
3668         continue;
3669 
3670       if (Idx >= (int)SrcNumElts) {
3671         Input = 1;
3672         Idx -= SrcNumElts;
3673       }
3674 
3675       // If all the indices come from the same MaskNumElts sized portion of
3676       // the sources we can use extract. Also make sure the extract wouldn't
3677       // extract past the end of the source.
3678       int NewStartIdx = alignDown(Idx, MaskNumElts);
3679       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3680           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3681         CanExtract = false;
3682       // Make sure we always update StartIdx as we use it to track if all
3683       // elements are undef.
3684       StartIdx[Input] = NewStartIdx;
3685     }
3686 
3687     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3688       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3689       return;
3690     }
3691     if (CanExtract) {
3692       // Extract appropriate subvector and generate a vector shuffle
3693       for (unsigned Input = 0; Input < 2; ++Input) {
3694         SDValue &Src = Input == 0 ? Src1 : Src2;
3695         if (StartIdx[Input] < 0)
3696           Src = DAG.getUNDEF(VT);
3697         else {
3698           Src = DAG.getNode(
3699               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3700               DAG.getConstant(StartIdx[Input], DL,
3701                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3702         }
3703       }
3704 
3705       // Calculate new mask.
3706       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3707       for (int &Idx : MappedOps) {
3708         if (Idx >= (int)SrcNumElts)
3709           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3710         else if (Idx >= 0)
3711           Idx -= StartIdx[0];
3712       }
3713 
3714       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3715       return;
3716     }
3717   }
3718 
3719   // We can't use either concat vectors or extract subvectors so fall back to
3720   // replacing the shuffle with extract and build vector.
3721   // to insert and build vector.
3722   EVT EltVT = VT.getVectorElementType();
3723   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3724   SmallVector<SDValue,8> Ops;
3725   for (int Idx : Mask) {
3726     SDValue Res;
3727 
3728     if (Idx < 0) {
3729       Res = DAG.getUNDEF(EltVT);
3730     } else {
3731       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3732       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3733 
3734       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3735                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3736     }
3737 
3738     Ops.push_back(Res);
3739   }
3740 
3741   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3742 }
3743 
3744 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3745   ArrayRef<unsigned> Indices;
3746   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3747     Indices = IV->getIndices();
3748   else
3749     Indices = cast<ConstantExpr>(&I)->getIndices();
3750 
3751   const Value *Op0 = I.getOperand(0);
3752   const Value *Op1 = I.getOperand(1);
3753   Type *AggTy = I.getType();
3754   Type *ValTy = Op1->getType();
3755   bool IntoUndef = isa<UndefValue>(Op0);
3756   bool FromUndef = isa<UndefValue>(Op1);
3757 
3758   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3759 
3760   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3761   SmallVector<EVT, 4> AggValueVTs;
3762   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3763   SmallVector<EVT, 4> ValValueVTs;
3764   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3765 
3766   unsigned NumAggValues = AggValueVTs.size();
3767   unsigned NumValValues = ValValueVTs.size();
3768   SmallVector<SDValue, 4> Values(NumAggValues);
3769 
3770   // Ignore an insertvalue that produces an empty object
3771   if (!NumAggValues) {
3772     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3773     return;
3774   }
3775 
3776   SDValue Agg = getValue(Op0);
3777   unsigned i = 0;
3778   // Copy the beginning value(s) from the original aggregate.
3779   for (; i != LinearIndex; ++i)
3780     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3781                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3782   // Copy values from the inserted value(s).
3783   if (NumValValues) {
3784     SDValue Val = getValue(Op1);
3785     for (; i != LinearIndex + NumValValues; ++i)
3786       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3787                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3788   }
3789   // Copy remaining value(s) from the original aggregate.
3790   for (; i != NumAggValues; ++i)
3791     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3792                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3793 
3794   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3795                            DAG.getVTList(AggValueVTs), Values));
3796 }
3797 
3798 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3799   ArrayRef<unsigned> Indices;
3800   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3801     Indices = EV->getIndices();
3802   else
3803     Indices = cast<ConstantExpr>(&I)->getIndices();
3804 
3805   const Value *Op0 = I.getOperand(0);
3806   Type *AggTy = Op0->getType();
3807   Type *ValTy = I.getType();
3808   bool OutOfUndef = isa<UndefValue>(Op0);
3809 
3810   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3811 
3812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3813   SmallVector<EVT, 4> ValValueVTs;
3814   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3815 
3816   unsigned NumValValues = ValValueVTs.size();
3817 
3818   // Ignore a extractvalue that produces an empty object
3819   if (!NumValValues) {
3820     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3821     return;
3822   }
3823 
3824   SmallVector<SDValue, 4> Values(NumValValues);
3825 
3826   SDValue Agg = getValue(Op0);
3827   // Copy out the selected value(s).
3828   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3829     Values[i - LinearIndex] =
3830       OutOfUndef ?
3831         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3832         SDValue(Agg.getNode(), Agg.getResNo() + i);
3833 
3834   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3835                            DAG.getVTList(ValValueVTs), Values));
3836 }
3837 
3838 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3839   Value *Op0 = I.getOperand(0);
3840   // Note that the pointer operand may be a vector of pointers. Take the scalar
3841   // element which holds a pointer.
3842   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3843   SDValue N = getValue(Op0);
3844   SDLoc dl = getCurSDLoc();
3845   auto &TLI = DAG.getTargetLoweringInfo();
3846   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3847   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3848 
3849   // Normalize Vector GEP - all scalar operands should be converted to the
3850   // splat vector.
3851   unsigned VectorWidth = I.getType()->isVectorTy() ?
3852     I.getType()->getVectorNumElements() : 0;
3853 
3854   if (VectorWidth && !N.getValueType().isVector()) {
3855     LLVMContext &Context = *DAG.getContext();
3856     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3857     N = DAG.getSplatBuildVector(VT, dl, N);
3858   }
3859 
3860   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3861        GTI != E; ++GTI) {
3862     const Value *Idx = GTI.getOperand();
3863     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3864       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3865       if (Field) {
3866         // N = N + Offset
3867         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3868 
3869         // In an inbounds GEP with an offset that is nonnegative even when
3870         // interpreted as signed, assume there is no unsigned overflow.
3871         SDNodeFlags Flags;
3872         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3873           Flags.setNoUnsignedWrap(true);
3874 
3875         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3876                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3877       }
3878     } else {
3879       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3880       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3881       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3882 
3883       // If this is a scalar constant or a splat vector of constants,
3884       // handle it quickly.
3885       const auto *C = dyn_cast<Constant>(Idx);
3886       if (C && isa<VectorType>(C->getType()))
3887         C = C->getSplatValue();
3888 
3889       if (const auto *CI = dyn_cast_or_null<ConstantInt>(C)) {
3890         if (CI->isZero())
3891           continue;
3892         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3893         LLVMContext &Context = *DAG.getContext();
3894         SDValue OffsVal = VectorWidth ?
3895           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3896           DAG.getConstant(Offs, dl, IdxTy);
3897 
3898         // In an inbounds GEP with an offset that is nonnegative even when
3899         // interpreted as signed, assume there is no unsigned overflow.
3900         SDNodeFlags Flags;
3901         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3902           Flags.setNoUnsignedWrap(true);
3903 
3904         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3905 
3906         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3907         continue;
3908       }
3909 
3910       // N = N + Idx * ElementSize;
3911       SDValue IdxN = getValue(Idx);
3912 
3913       if (!IdxN.getValueType().isVector() && VectorWidth) {
3914         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3915         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3916       }
3917 
3918       // If the index is smaller or larger than intptr_t, truncate or extend
3919       // it.
3920       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3921 
3922       // If this is a multiply by a power of two, turn it into a shl
3923       // immediately.  This is a very common case.
3924       if (ElementSize != 1) {
3925         if (ElementSize.isPowerOf2()) {
3926           unsigned Amt = ElementSize.logBase2();
3927           IdxN = DAG.getNode(ISD::SHL, dl,
3928                              N.getValueType(), IdxN,
3929                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3930         } else {
3931           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3932                                           IdxN.getValueType());
3933           IdxN = DAG.getNode(ISD::MUL, dl,
3934                              N.getValueType(), IdxN, Scale);
3935         }
3936       }
3937 
3938       N = DAG.getNode(ISD::ADD, dl,
3939                       N.getValueType(), N, IdxN);
3940     }
3941   }
3942 
3943   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3944     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3945 
3946   setValue(&I, N);
3947 }
3948 
3949 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3950   // If this is a fixed sized alloca in the entry block of the function,
3951   // allocate it statically on the stack.
3952   if (FuncInfo.StaticAllocaMap.count(&I))
3953     return;   // getValue will auto-populate this.
3954 
3955   SDLoc dl = getCurSDLoc();
3956   Type *Ty = I.getAllocatedType();
3957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3958   auto &DL = DAG.getDataLayout();
3959   uint64_t TySize = DL.getTypeAllocSize(Ty);
3960   unsigned Align =
3961       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3962 
3963   SDValue AllocSize = getValue(I.getArraySize());
3964 
3965   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3966   if (AllocSize.getValueType() != IntPtr)
3967     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3968 
3969   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3970                           AllocSize,
3971                           DAG.getConstant(TySize, dl, IntPtr));
3972 
3973   // Handle alignment.  If the requested alignment is less than or equal to
3974   // the stack alignment, ignore it.  If the size is greater than or equal to
3975   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3976   unsigned StackAlign =
3977       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3978   if (Align <= StackAlign)
3979     Align = 0;
3980 
3981   // Round the size of the allocation up to the stack alignment size
3982   // by add SA-1 to the size. This doesn't overflow because we're computing
3983   // an address inside an alloca.
3984   SDNodeFlags Flags;
3985   Flags.setNoUnsignedWrap(true);
3986   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3987                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3988 
3989   // Mask out the low bits for alignment purposes.
3990   AllocSize =
3991       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3992                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3993 
3994   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3995   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3996   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3997   setValue(&I, DSA);
3998   DAG.setRoot(DSA.getValue(1));
3999 
4000   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4001 }
4002 
4003 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4004   if (I.isAtomic())
4005     return visitAtomicLoad(I);
4006 
4007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4008   const Value *SV = I.getOperand(0);
4009   if (TLI.supportSwiftError()) {
4010     // Swifterror values can come from either a function parameter with
4011     // swifterror attribute or an alloca with swifterror attribute.
4012     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4013       if (Arg->hasSwiftErrorAttr())
4014         return visitLoadFromSwiftError(I);
4015     }
4016 
4017     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4018       if (Alloca->isSwiftError())
4019         return visitLoadFromSwiftError(I);
4020     }
4021   }
4022 
4023   SDValue Ptr = getValue(SV);
4024 
4025   Type *Ty = I.getType();
4026 
4027   bool isVolatile = I.isVolatile();
4028   bool isNonTemporal = I.hasMetadata(LLVMContext::MD_nontemporal);
4029   bool isInvariant = I.hasMetadata(LLVMContext::MD_invariant_load);
4030   bool isDereferenceable =
4031       isDereferenceablePointer(SV, I.getType(), DAG.getDataLayout());
4032   unsigned Alignment = I.getAlignment();
4033 
4034   AAMDNodes AAInfo;
4035   I.getAAMetadata(AAInfo);
4036   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4037 
4038   SmallVector<EVT, 4> ValueVTs, MemVTs;
4039   SmallVector<uint64_t, 4> Offsets;
4040   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4041   unsigned NumValues = ValueVTs.size();
4042   if (NumValues == 0)
4043     return;
4044 
4045   SDValue Root;
4046   bool ConstantMemory = false;
4047   if (isVolatile || NumValues > MaxParallelChains)
4048     // Serialize volatile loads with other side effects.
4049     Root = getRoot();
4050   else if (AA &&
4051            AA->pointsToConstantMemory(MemoryLocation(
4052                SV,
4053                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4054                AAInfo))) {
4055     // Do not serialize (non-volatile) loads of constant memory with anything.
4056     Root = DAG.getEntryNode();
4057     ConstantMemory = true;
4058   } else {
4059     // Do not serialize non-volatile loads against each other.
4060     Root = DAG.getRoot();
4061   }
4062 
4063   SDLoc dl = getCurSDLoc();
4064 
4065   if (isVolatile)
4066     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4067 
4068   // An aggregate load cannot wrap around the address space, so offsets to its
4069   // parts don't wrap either.
4070   SDNodeFlags Flags;
4071   Flags.setNoUnsignedWrap(true);
4072 
4073   SmallVector<SDValue, 4> Values(NumValues);
4074   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4075   EVT PtrVT = Ptr.getValueType();
4076   unsigned ChainI = 0;
4077   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4078     // Serializing loads here may result in excessive register pressure, and
4079     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4080     // could recover a bit by hoisting nodes upward in the chain by recognizing
4081     // they are side-effect free or do not alias. The optimizer should really
4082     // avoid this case by converting large object/array copies to llvm.memcpy
4083     // (MaxParallelChains should always remain as failsafe).
4084     if (ChainI == MaxParallelChains) {
4085       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4086       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4087                                   makeArrayRef(Chains.data(), ChainI));
4088       Root = Chain;
4089       ChainI = 0;
4090     }
4091     SDValue A = DAG.getNode(ISD::ADD, dl,
4092                             PtrVT, Ptr,
4093                             DAG.getConstant(Offsets[i], dl, PtrVT),
4094                             Flags);
4095     auto MMOFlags = MachineMemOperand::MONone;
4096     if (isVolatile)
4097       MMOFlags |= MachineMemOperand::MOVolatile;
4098     if (isNonTemporal)
4099       MMOFlags |= MachineMemOperand::MONonTemporal;
4100     if (isInvariant)
4101       MMOFlags |= MachineMemOperand::MOInvariant;
4102     if (isDereferenceable)
4103       MMOFlags |= MachineMemOperand::MODereferenceable;
4104     MMOFlags |= TLI.getMMOFlags(I);
4105 
4106     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4107                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4108                             MMOFlags, AAInfo, Ranges);
4109     Chains[ChainI] = L.getValue(1);
4110 
4111     if (MemVTs[i] != ValueVTs[i])
4112       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4113 
4114     Values[i] = L;
4115   }
4116 
4117   if (!ConstantMemory) {
4118     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4119                                 makeArrayRef(Chains.data(), ChainI));
4120     if (isVolatile)
4121       DAG.setRoot(Chain);
4122     else
4123       PendingLoads.push_back(Chain);
4124   }
4125 
4126   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4127                            DAG.getVTList(ValueVTs), Values));
4128 }
4129 
4130 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4131   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4132          "call visitStoreToSwiftError when backend supports swifterror");
4133 
4134   SmallVector<EVT, 4> ValueVTs;
4135   SmallVector<uint64_t, 4> Offsets;
4136   const Value *SrcV = I.getOperand(0);
4137   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4138                   SrcV->getType(), ValueVTs, &Offsets);
4139   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4140          "expect a single EVT for swifterror");
4141 
4142   SDValue Src = getValue(SrcV);
4143   // Create a virtual register, then update the virtual register.
4144   Register VReg =
4145       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4146   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4147   // Chain can be getRoot or getControlRoot.
4148   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4149                                       SDValue(Src.getNode(), Src.getResNo()));
4150   DAG.setRoot(CopyNode);
4151 }
4152 
4153 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4154   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4155          "call visitLoadFromSwiftError when backend supports swifterror");
4156 
4157   assert(!I.isVolatile() &&
4158          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4159          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4160          "Support volatile, non temporal, invariant for load_from_swift_error");
4161 
4162   const Value *SV = I.getOperand(0);
4163   Type *Ty = I.getType();
4164   AAMDNodes AAInfo;
4165   I.getAAMetadata(AAInfo);
4166   assert(
4167       (!AA ||
4168        !AA->pointsToConstantMemory(MemoryLocation(
4169            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4170            AAInfo))) &&
4171       "load_from_swift_error should not be constant memory");
4172 
4173   SmallVector<EVT, 4> ValueVTs;
4174   SmallVector<uint64_t, 4> Offsets;
4175   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4176                   ValueVTs, &Offsets);
4177   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4178          "expect a single EVT for swifterror");
4179 
4180   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4181   SDValue L = DAG.getCopyFromReg(
4182       getRoot(), getCurSDLoc(),
4183       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4184 
4185   setValue(&I, L);
4186 }
4187 
4188 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4189   if (I.isAtomic())
4190     return visitAtomicStore(I);
4191 
4192   const Value *SrcV = I.getOperand(0);
4193   const Value *PtrV = I.getOperand(1);
4194 
4195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4196   if (TLI.supportSwiftError()) {
4197     // Swifterror values can come from either a function parameter with
4198     // swifterror attribute or an alloca with swifterror attribute.
4199     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4200       if (Arg->hasSwiftErrorAttr())
4201         return visitStoreToSwiftError(I);
4202     }
4203 
4204     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4205       if (Alloca->isSwiftError())
4206         return visitStoreToSwiftError(I);
4207     }
4208   }
4209 
4210   SmallVector<EVT, 4> ValueVTs, MemVTs;
4211   SmallVector<uint64_t, 4> Offsets;
4212   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4213                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4214   unsigned NumValues = ValueVTs.size();
4215   if (NumValues == 0)
4216     return;
4217 
4218   // Get the lowered operands. Note that we do this after
4219   // checking if NumResults is zero, because with zero results
4220   // the operands won't have values in the map.
4221   SDValue Src = getValue(SrcV);
4222   SDValue Ptr = getValue(PtrV);
4223 
4224   SDValue Root = getRoot();
4225   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4226   SDLoc dl = getCurSDLoc();
4227   unsigned Alignment = I.getAlignment();
4228   AAMDNodes AAInfo;
4229   I.getAAMetadata(AAInfo);
4230 
4231   auto MMOFlags = MachineMemOperand::MONone;
4232   if (I.isVolatile())
4233     MMOFlags |= MachineMemOperand::MOVolatile;
4234   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4235     MMOFlags |= MachineMemOperand::MONonTemporal;
4236   MMOFlags |= TLI.getMMOFlags(I);
4237 
4238   // An aggregate load cannot wrap around the address space, so offsets to its
4239   // parts don't wrap either.
4240   SDNodeFlags Flags;
4241   Flags.setNoUnsignedWrap(true);
4242 
4243   unsigned ChainI = 0;
4244   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4245     // See visitLoad comments.
4246     if (ChainI == MaxParallelChains) {
4247       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4248                                   makeArrayRef(Chains.data(), ChainI));
4249       Root = Chain;
4250       ChainI = 0;
4251     }
4252     SDValue Add = DAG.getMemBasePlusOffset(Ptr, Offsets[i], dl, Flags);
4253     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4254     if (MemVTs[i] != ValueVTs[i])
4255       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4256     SDValue St =
4257         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4258                      Alignment, MMOFlags, AAInfo);
4259     Chains[ChainI] = St;
4260   }
4261 
4262   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4263                                   makeArrayRef(Chains.data(), ChainI));
4264   DAG.setRoot(StoreNode);
4265 }
4266 
4267 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4268                                            bool IsCompressing) {
4269   SDLoc sdl = getCurSDLoc();
4270 
4271   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4272                            unsigned& Alignment) {
4273     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4274     Src0 = I.getArgOperand(0);
4275     Ptr = I.getArgOperand(1);
4276     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4277     Mask = I.getArgOperand(3);
4278   };
4279   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4280                            unsigned& Alignment) {
4281     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4282     Src0 = I.getArgOperand(0);
4283     Ptr = I.getArgOperand(1);
4284     Mask = I.getArgOperand(2);
4285     Alignment = 0;
4286   };
4287 
4288   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4289   unsigned Alignment;
4290   if (IsCompressing)
4291     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4292   else
4293     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4294 
4295   SDValue Ptr = getValue(PtrOperand);
4296   SDValue Src0 = getValue(Src0Operand);
4297   SDValue Mask = getValue(MaskOperand);
4298   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4299 
4300   EVT VT = Src0.getValueType();
4301   if (!Alignment)
4302     Alignment = DAG.getEVTAlignment(VT);
4303 
4304   AAMDNodes AAInfo;
4305   I.getAAMetadata(AAInfo);
4306 
4307   MachineMemOperand *MMO =
4308     DAG.getMachineFunction().
4309     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4310                           MachineMemOperand::MOStore,
4311                           // TODO: Make MachineMemOperands aware of scalable
4312                           // vectors.
4313                           VT.getStoreSize().getKnownMinSize(),
4314                           Alignment, AAInfo);
4315   SDValue StoreNode =
4316       DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4317                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4318   DAG.setRoot(StoreNode);
4319   setValue(&I, StoreNode);
4320 }
4321 
4322 // Get a uniform base for the Gather/Scatter intrinsic.
4323 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4324 // We try to represent it as a base pointer + vector of indices.
4325 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4326 // The first operand of the GEP may be a single pointer or a vector of pointers
4327 // Example:
4328 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4329 //  or
4330 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4331 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4332 //
4333 // When the first GEP operand is a single pointer - it is the uniform base we
4334 // are looking for. If first operand of the GEP is a splat vector - we
4335 // extract the splat value and use it as a uniform base.
4336 // In all other cases the function returns 'false'.
4337 static bool getUniformBase(const Value *&Ptr, SDValue &Base, SDValue &Index,
4338                            ISD::MemIndexType &IndexType, SDValue &Scale,
4339                            SelectionDAGBuilder *SDB) {
4340   SelectionDAG& DAG = SDB->DAG;
4341   LLVMContext &Context = *DAG.getContext();
4342 
4343   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4344   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4345   if (!GEP)
4346     return false;
4347 
4348   const Value *GEPPtr = GEP->getPointerOperand();
4349   if (!GEPPtr->getType()->isVectorTy())
4350     Ptr = GEPPtr;
4351   else if (!(Ptr = getSplatValue(GEPPtr)))
4352     return false;
4353 
4354   unsigned FinalIndex = GEP->getNumOperands() - 1;
4355   Value *IndexVal = GEP->getOperand(FinalIndex);
4356 
4357   // Ensure all the other indices are 0.
4358   for (unsigned i = 1; i < FinalIndex; ++i) {
4359     auto *C = dyn_cast<Constant>(GEP->getOperand(i));
4360     if (!C)
4361       return false;
4362     if (isa<VectorType>(C->getType()))
4363       C = C->getSplatValue();
4364     auto *CI = dyn_cast_or_null<ConstantInt>(C);
4365     if (!CI || !CI->isZero())
4366       return false;
4367   }
4368 
4369   // The operands of the GEP may be defined in another basic block.
4370   // In this case we'll not find nodes for the operands.
4371   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4372     return false;
4373 
4374   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4375   const DataLayout &DL = DAG.getDataLayout();
4376   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4377                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4378   Base = SDB->getValue(Ptr);
4379   Index = SDB->getValue(IndexVal);
4380   IndexType = ISD::SIGNED_SCALED;
4381 
4382   if (!Index.getValueType().isVector()) {
4383     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4384     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4385     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4386   }
4387   return true;
4388 }
4389 
4390 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4391   SDLoc sdl = getCurSDLoc();
4392 
4393   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4394   const Value *Ptr = I.getArgOperand(1);
4395   SDValue Src0 = getValue(I.getArgOperand(0));
4396   SDValue Mask = getValue(I.getArgOperand(3));
4397   EVT VT = Src0.getValueType();
4398   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4399   if (!Alignment)
4400     Alignment = DAG.getEVTAlignment(VT);
4401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4402 
4403   AAMDNodes AAInfo;
4404   I.getAAMetadata(AAInfo);
4405 
4406   SDValue Base;
4407   SDValue Index;
4408   ISD::MemIndexType IndexType;
4409   SDValue Scale;
4410   const Value *BasePtr = Ptr;
4411   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4412                                     this);
4413 
4414   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4415   MachineMemOperand *MMO = DAG.getMachineFunction().
4416     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4417                          MachineMemOperand::MOStore,
4418                          // TODO: Make MachineMemOperands aware of scalable
4419                          // vectors.
4420                          VT.getStoreSize().getKnownMinSize(),
4421                          Alignment, AAInfo);
4422   if (!UniformBase) {
4423     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4424     Index = getValue(Ptr);
4425     IndexType = ISD::SIGNED_SCALED;
4426     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4427   }
4428   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4429   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4430                                          Ops, MMO, IndexType);
4431   DAG.setRoot(Scatter);
4432   setValue(&I, Scatter);
4433 }
4434 
4435 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4436   SDLoc sdl = getCurSDLoc();
4437 
4438   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4439                            unsigned& Alignment) {
4440     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4441     Ptr = I.getArgOperand(0);
4442     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4443     Mask = I.getArgOperand(2);
4444     Src0 = I.getArgOperand(3);
4445   };
4446   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4447                            unsigned& Alignment) {
4448     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4449     Ptr = I.getArgOperand(0);
4450     Alignment = 0;
4451     Mask = I.getArgOperand(1);
4452     Src0 = I.getArgOperand(2);
4453   };
4454 
4455   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4456   unsigned Alignment;
4457   if (IsExpanding)
4458     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4459   else
4460     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4461 
4462   SDValue Ptr = getValue(PtrOperand);
4463   SDValue Src0 = getValue(Src0Operand);
4464   SDValue Mask = getValue(MaskOperand);
4465   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4466 
4467   EVT VT = Src0.getValueType();
4468   if (!Alignment)
4469     Alignment = DAG.getEVTAlignment(VT);
4470 
4471   AAMDNodes AAInfo;
4472   I.getAAMetadata(AAInfo);
4473   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4474 
4475   // Do not serialize masked loads of constant memory with anything.
4476   MemoryLocation ML;
4477   if (VT.isScalableVector())
4478     ML = MemoryLocation(PtrOperand);
4479   else
4480     ML = MemoryLocation(PtrOperand, LocationSize::precise(
4481                            DAG.getDataLayout().getTypeStoreSize(I.getType())),
4482                            AAInfo);
4483   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4484 
4485   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4486 
4487   MachineMemOperand *MMO =
4488     DAG.getMachineFunction().
4489     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4490                           MachineMemOperand::MOLoad,
4491                           // TODO: Make MachineMemOperands aware of scalable
4492                           // vectors.
4493                           VT.getStoreSize().getKnownMinSize(),
4494                           Alignment, AAInfo, Ranges);
4495 
4496   SDValue Load =
4497       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4498                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4499   if (AddToChain)
4500     PendingLoads.push_back(Load.getValue(1));
4501   setValue(&I, Load);
4502 }
4503 
4504 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4505   SDLoc sdl = getCurSDLoc();
4506 
4507   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4508   const Value *Ptr = I.getArgOperand(0);
4509   SDValue Src0 = getValue(I.getArgOperand(3));
4510   SDValue Mask = getValue(I.getArgOperand(2));
4511 
4512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4513   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4514   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4515   if (!Alignment)
4516     Alignment = DAG.getEVTAlignment(VT);
4517 
4518   AAMDNodes AAInfo;
4519   I.getAAMetadata(AAInfo);
4520   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4521 
4522   SDValue Root = DAG.getRoot();
4523   SDValue Base;
4524   SDValue Index;
4525   ISD::MemIndexType IndexType;
4526   SDValue Scale;
4527   const Value *BasePtr = Ptr;
4528   bool UniformBase = getUniformBase(BasePtr, Base, Index, IndexType, Scale,
4529                                     this);
4530   bool ConstantMemory = false;
4531   if (UniformBase && AA &&
4532       AA->pointsToConstantMemory(
4533           MemoryLocation(BasePtr,
4534                          LocationSize::precise(
4535                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4536                          AAInfo))) {
4537     // Do not serialize (non-volatile) loads of constant memory with anything.
4538     Root = DAG.getEntryNode();
4539     ConstantMemory = true;
4540   }
4541 
4542   MachineMemOperand *MMO =
4543     DAG.getMachineFunction().
4544     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4545                          MachineMemOperand::MOLoad,
4546                          // TODO: Make MachineMemOperands aware of scalable
4547                          // vectors.
4548                          VT.getStoreSize().getKnownMinSize(),
4549                          Alignment, AAInfo, Ranges);
4550 
4551   if (!UniformBase) {
4552     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4553     Index = getValue(Ptr);
4554     IndexType = ISD::SIGNED_SCALED;
4555     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4556   }
4557   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4558   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4559                                        Ops, MMO, IndexType);
4560 
4561   SDValue OutChain = Gather.getValue(1);
4562   if (!ConstantMemory)
4563     PendingLoads.push_back(OutChain);
4564   setValue(&I, Gather);
4565 }
4566 
4567 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4568   SDLoc dl = getCurSDLoc();
4569   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4570   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4571   SyncScope::ID SSID = I.getSyncScopeID();
4572 
4573   SDValue InChain = getRoot();
4574 
4575   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4576   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4577 
4578   auto Alignment = DAG.getEVTAlignment(MemVT);
4579 
4580   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4581   if (I.isVolatile())
4582     Flags |= MachineMemOperand::MOVolatile;
4583   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4584 
4585   MachineFunction &MF = DAG.getMachineFunction();
4586   MachineMemOperand *MMO =
4587     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4588                             Flags, MemVT.getStoreSize(), Alignment,
4589                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4590                             FailureOrdering);
4591 
4592   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4593                                    dl, MemVT, VTs, InChain,
4594                                    getValue(I.getPointerOperand()),
4595                                    getValue(I.getCompareOperand()),
4596                                    getValue(I.getNewValOperand()), MMO);
4597 
4598   SDValue OutChain = L.getValue(2);
4599 
4600   setValue(&I, L);
4601   DAG.setRoot(OutChain);
4602 }
4603 
4604 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4605   SDLoc dl = getCurSDLoc();
4606   ISD::NodeType NT;
4607   switch (I.getOperation()) {
4608   default: llvm_unreachable("Unknown atomicrmw operation");
4609   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4610   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4611   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4612   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4613   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4614   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4615   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4616   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4617   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4618   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4619   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4620   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4621   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4622   }
4623   AtomicOrdering Ordering = I.getOrdering();
4624   SyncScope::ID SSID = I.getSyncScopeID();
4625 
4626   SDValue InChain = getRoot();
4627 
4628   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4629   auto Alignment = DAG.getEVTAlignment(MemVT);
4630 
4631   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4632   if (I.isVolatile())
4633     Flags |= MachineMemOperand::MOVolatile;
4634   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4635 
4636   MachineFunction &MF = DAG.getMachineFunction();
4637   MachineMemOperand *MMO =
4638     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4639                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4640                             nullptr, SSID, Ordering);
4641 
4642   SDValue L =
4643     DAG.getAtomic(NT, dl, MemVT, InChain,
4644                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4645                   MMO);
4646 
4647   SDValue OutChain = L.getValue(1);
4648 
4649   setValue(&I, L);
4650   DAG.setRoot(OutChain);
4651 }
4652 
4653 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4654   SDLoc dl = getCurSDLoc();
4655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4656   SDValue Ops[3];
4657   Ops[0] = getRoot();
4658   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4659                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4660   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4661                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4662   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4663 }
4664 
4665 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4666   SDLoc dl = getCurSDLoc();
4667   AtomicOrdering Order = I.getOrdering();
4668   SyncScope::ID SSID = I.getSyncScopeID();
4669 
4670   SDValue InChain = getRoot();
4671 
4672   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4673   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4674   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4675 
4676   if (!TLI.supportsUnalignedAtomics() &&
4677       I.getAlignment() < MemVT.getSizeInBits() / 8)
4678     report_fatal_error("Cannot generate unaligned atomic load");
4679 
4680   auto Flags = MachineMemOperand::MOLoad;
4681   if (I.isVolatile())
4682     Flags |= MachineMemOperand::MOVolatile;
4683   if (I.hasMetadata(LLVMContext::MD_invariant_load))
4684     Flags |= MachineMemOperand::MOInvariant;
4685   if (isDereferenceablePointer(I.getPointerOperand(), I.getType(),
4686                                DAG.getDataLayout()))
4687     Flags |= MachineMemOperand::MODereferenceable;
4688 
4689   Flags |= TLI.getMMOFlags(I);
4690 
4691   MachineMemOperand *MMO =
4692       DAG.getMachineFunction().
4693       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4694                            Flags, MemVT.getStoreSize(),
4695                            I.getAlignment() ? I.getAlignment() :
4696                                               DAG.getEVTAlignment(MemVT),
4697                            AAMDNodes(), nullptr, SSID, Order);
4698 
4699   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4700 
4701   SDValue Ptr = getValue(I.getPointerOperand());
4702 
4703   if (TLI.lowerAtomicLoadAsLoadSDNode(I)) {
4704     // TODO: Once this is better exercised by tests, it should be merged with
4705     // the normal path for loads to prevent future divergence.
4706     SDValue L = DAG.getLoad(MemVT, dl, InChain, Ptr, MMO);
4707     if (MemVT != VT)
4708       L = DAG.getPtrExtOrTrunc(L, dl, VT);
4709 
4710     setValue(&I, L);
4711     SDValue OutChain = L.getValue(1);
4712     if (!I.isUnordered())
4713       DAG.setRoot(OutChain);
4714     else
4715       PendingLoads.push_back(OutChain);
4716     return;
4717   }
4718 
4719   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4720                             Ptr, MMO);
4721 
4722   SDValue OutChain = L.getValue(1);
4723   if (MemVT != VT)
4724     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4725 
4726   setValue(&I, L);
4727   DAG.setRoot(OutChain);
4728 }
4729 
4730 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4731   SDLoc dl = getCurSDLoc();
4732 
4733   AtomicOrdering Ordering = I.getOrdering();
4734   SyncScope::ID SSID = I.getSyncScopeID();
4735 
4736   SDValue InChain = getRoot();
4737 
4738   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4739   EVT MemVT =
4740       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4741 
4742   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4743     report_fatal_error("Cannot generate unaligned atomic store");
4744 
4745   auto Flags = MachineMemOperand::MOStore;
4746   if (I.isVolatile())
4747     Flags |= MachineMemOperand::MOVolatile;
4748   Flags |= TLI.getMMOFlags(I);
4749 
4750   MachineFunction &MF = DAG.getMachineFunction();
4751   MachineMemOperand *MMO =
4752     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4753                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4754                             nullptr, SSID, Ordering);
4755 
4756   SDValue Val = getValue(I.getValueOperand());
4757   if (Val.getValueType() != MemVT)
4758     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4759   SDValue Ptr = getValue(I.getPointerOperand());
4760 
4761   if (TLI.lowerAtomicStoreAsStoreSDNode(I)) {
4762     // TODO: Once this is better exercised by tests, it should be merged with
4763     // the normal path for stores to prevent future divergence.
4764     SDValue S = DAG.getStore(InChain, dl, Val, Ptr, MMO);
4765     DAG.setRoot(S);
4766     return;
4767   }
4768   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4769                                    Ptr, Val, MMO);
4770 
4771 
4772   DAG.setRoot(OutChain);
4773 }
4774 
4775 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4776 /// node.
4777 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4778                                                unsigned Intrinsic) {
4779   // Ignore the callsite's attributes. A specific call site may be marked with
4780   // readnone, but the lowering code will expect the chain based on the
4781   // definition.
4782   const Function *F = I.getCalledFunction();
4783   bool HasChain = !F->doesNotAccessMemory();
4784   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4785 
4786   // Build the operand list.
4787   SmallVector<SDValue, 8> Ops;
4788   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4789     if (OnlyLoad) {
4790       // We don't need to serialize loads against other loads.
4791       Ops.push_back(DAG.getRoot());
4792     } else {
4793       Ops.push_back(getRoot());
4794     }
4795   }
4796 
4797   // Info is set by getTgtMemInstrinsic
4798   TargetLowering::IntrinsicInfo Info;
4799   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4800   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4801                                                DAG.getMachineFunction(),
4802                                                Intrinsic);
4803 
4804   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4805   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4806       Info.opc == ISD::INTRINSIC_W_CHAIN)
4807     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4808                                         TLI.getPointerTy(DAG.getDataLayout())));
4809 
4810   // Add all operands of the call to the operand list.
4811   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4812     const Value *Arg = I.getArgOperand(i);
4813     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
4814       Ops.push_back(getValue(Arg));
4815       continue;
4816     }
4817 
4818     // Use TargetConstant instead of a regular constant for immarg.
4819     EVT VT = TLI.getValueType(*DL, Arg->getType(), true);
4820     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
4821       assert(CI->getBitWidth() <= 64 &&
4822              "large intrinsic immediates not handled");
4823       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
4824     } else {
4825       Ops.push_back(
4826           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
4827     }
4828   }
4829 
4830   SmallVector<EVT, 4> ValueVTs;
4831   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4832 
4833   if (HasChain)
4834     ValueVTs.push_back(MVT::Other);
4835 
4836   SDVTList VTs = DAG.getVTList(ValueVTs);
4837 
4838   // Create the node.
4839   SDValue Result;
4840   if (IsTgtIntrinsic) {
4841     // This is target intrinsic that touches memory
4842     AAMDNodes AAInfo;
4843     I.getAAMetadata(AAInfo);
4844     Result = DAG.getMemIntrinsicNode(
4845         Info.opc, getCurSDLoc(), VTs, Ops, Info.memVT,
4846         MachinePointerInfo(Info.ptrVal, Info.offset),
4847         Info.align ? Info.align->value() : 0, Info.flags, Info.size, AAInfo);
4848   } else if (!HasChain) {
4849     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4850   } else if (!I.getType()->isVoidTy()) {
4851     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4852   } else {
4853     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4854   }
4855 
4856   if (HasChain) {
4857     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4858     if (OnlyLoad)
4859       PendingLoads.push_back(Chain);
4860     else
4861       DAG.setRoot(Chain);
4862   }
4863 
4864   if (!I.getType()->isVoidTy()) {
4865     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4866       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4867       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4868     } else
4869       Result = lowerRangeToAssertZExt(DAG, I, Result);
4870 
4871     setValue(&I, Result);
4872   }
4873 }
4874 
4875 /// GetSignificand - Get the significand and build it into a floating-point
4876 /// number with exponent of 1:
4877 ///
4878 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4879 ///
4880 /// where Op is the hexadecimal representation of floating point value.
4881 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4882   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4883                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4884   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4885                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4886   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4887 }
4888 
4889 /// GetExponent - Get the exponent:
4890 ///
4891 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4892 ///
4893 /// where Op is the hexadecimal representation of floating point value.
4894 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4895                            const TargetLowering &TLI, const SDLoc &dl) {
4896   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4897                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4898   SDValue t1 = DAG.getNode(
4899       ISD::SRL, dl, MVT::i32, t0,
4900       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4901   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4902                            DAG.getConstant(127, dl, MVT::i32));
4903   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4904 }
4905 
4906 /// getF32Constant - Get 32-bit floating point constant.
4907 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4908                               const SDLoc &dl) {
4909   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4910                            MVT::f32);
4911 }
4912 
4913 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4914                                        SelectionDAG &DAG) {
4915   // TODO: What fast-math-flags should be set on the floating-point nodes?
4916 
4917   //   IntegerPartOfX = ((int32_t)(t0);
4918   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4919 
4920   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4921   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4922   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4923 
4924   //   IntegerPartOfX <<= 23;
4925   IntegerPartOfX = DAG.getNode(
4926       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4927       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4928                                   DAG.getDataLayout())));
4929 
4930   SDValue TwoToFractionalPartOfX;
4931   if (LimitFloatPrecision <= 6) {
4932     // For floating-point precision of 6:
4933     //
4934     //   TwoToFractionalPartOfX =
4935     //     0.997535578f +
4936     //       (0.735607626f + 0.252464424f * x) * x;
4937     //
4938     // error 0.0144103317, which is 6 bits
4939     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4940                              getF32Constant(DAG, 0x3e814304, dl));
4941     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4942                              getF32Constant(DAG, 0x3f3c50c8, dl));
4943     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4944     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4945                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4946   } else if (LimitFloatPrecision <= 12) {
4947     // For floating-point precision of 12:
4948     //
4949     //   TwoToFractionalPartOfX =
4950     //     0.999892986f +
4951     //       (0.696457318f +
4952     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4953     //
4954     // error 0.000107046256, which is 13 to 14 bits
4955     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4956                              getF32Constant(DAG, 0x3da235e3, dl));
4957     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4958                              getF32Constant(DAG, 0x3e65b8f3, dl));
4959     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4960     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4961                              getF32Constant(DAG, 0x3f324b07, dl));
4962     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4963     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4964                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4965   } else { // LimitFloatPrecision <= 18
4966     // For floating-point precision of 18:
4967     //
4968     //   TwoToFractionalPartOfX =
4969     //     0.999999982f +
4970     //       (0.693148872f +
4971     //         (0.240227044f +
4972     //           (0.554906021e-1f +
4973     //             (0.961591928e-2f +
4974     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4975     // error 2.47208000*10^(-7), which is better than 18 bits
4976     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4977                              getF32Constant(DAG, 0x3924b03e, dl));
4978     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4979                              getF32Constant(DAG, 0x3ab24b87, dl));
4980     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4981     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4982                              getF32Constant(DAG, 0x3c1d8c17, dl));
4983     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4984     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4985                              getF32Constant(DAG, 0x3d634a1d, dl));
4986     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4987     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4988                              getF32Constant(DAG, 0x3e75fe14, dl));
4989     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4990     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4991                               getF32Constant(DAG, 0x3f317234, dl));
4992     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4993     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4994                                          getF32Constant(DAG, 0x3f800000, dl));
4995   }
4996 
4997   // Add the exponent into the result in integer domain.
4998   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4999   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5000                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5001 }
5002 
5003 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5004 /// limited-precision mode.
5005 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5006                          const TargetLowering &TLI) {
5007   if (Op.getValueType() == MVT::f32 &&
5008       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5009 
5010     // Put the exponent in the right bit position for later addition to the
5011     // final result:
5012     //
5013     // t0 = Op * log2(e)
5014 
5015     // TODO: What fast-math-flags should be set here?
5016     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5017                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5018     return getLimitedPrecisionExp2(t0, dl, DAG);
5019   }
5020 
5021   // No special expansion.
5022   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
5023 }
5024 
5025 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5026 /// limited-precision mode.
5027 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5028                          const TargetLowering &TLI) {
5029   // TODO: What fast-math-flags should be set on the floating-point nodes?
5030 
5031   if (Op.getValueType() == MVT::f32 &&
5032       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5033     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5034 
5035     // Scale the exponent by log(2).
5036     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5037     SDValue LogOfExponent =
5038         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5039                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5040 
5041     // Get the significand and build it into a floating-point number with
5042     // exponent of 1.
5043     SDValue X = GetSignificand(DAG, Op1, dl);
5044 
5045     SDValue LogOfMantissa;
5046     if (LimitFloatPrecision <= 6) {
5047       // For floating-point precision of 6:
5048       //
5049       //   LogofMantissa =
5050       //     -1.1609546f +
5051       //       (1.4034025f - 0.23903021f * x) * x;
5052       //
5053       // error 0.0034276066, which is better than 8 bits
5054       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5055                                getF32Constant(DAG, 0xbe74c456, dl));
5056       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5057                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5058       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5059       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5060                                   getF32Constant(DAG, 0x3f949a29, dl));
5061     } else if (LimitFloatPrecision <= 12) {
5062       // For floating-point precision of 12:
5063       //
5064       //   LogOfMantissa =
5065       //     -1.7417939f +
5066       //       (2.8212026f +
5067       //         (-1.4699568f +
5068       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5069       //
5070       // error 0.000061011436, which is 14 bits
5071       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5072                                getF32Constant(DAG, 0xbd67b6d6, dl));
5073       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5074                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5075       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5076       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5077                                getF32Constant(DAG, 0x3fbc278b, dl));
5078       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5079       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5080                                getF32Constant(DAG, 0x40348e95, dl));
5081       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5082       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5083                                   getF32Constant(DAG, 0x3fdef31a, dl));
5084     } else { // LimitFloatPrecision <= 18
5085       // For floating-point precision of 18:
5086       //
5087       //   LogOfMantissa =
5088       //     -2.1072184f +
5089       //       (4.2372794f +
5090       //         (-3.7029485f +
5091       //           (2.2781945f +
5092       //             (-0.87823314f +
5093       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5094       //
5095       // error 0.0000023660568, which is better than 18 bits
5096       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5097                                getF32Constant(DAG, 0xbc91e5ac, dl));
5098       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5099                                getF32Constant(DAG, 0x3e4350aa, dl));
5100       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5101       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5102                                getF32Constant(DAG, 0x3f60d3e3, dl));
5103       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5104       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5105                                getF32Constant(DAG, 0x4011cdf0, dl));
5106       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5107       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5108                                getF32Constant(DAG, 0x406cfd1c, dl));
5109       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5110       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5111                                getF32Constant(DAG, 0x408797cb, dl));
5112       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5113       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5114                                   getF32Constant(DAG, 0x4006dcab, dl));
5115     }
5116 
5117     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5118   }
5119 
5120   // No special expansion.
5121   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5122 }
5123 
5124 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5125 /// limited-precision mode.
5126 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5127                           const TargetLowering &TLI) {
5128   // TODO: What fast-math-flags should be set on the floating-point nodes?
5129 
5130   if (Op.getValueType() == MVT::f32 &&
5131       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5132     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5133 
5134     // Get the exponent.
5135     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5136 
5137     // Get the significand and build it into a floating-point number with
5138     // exponent of 1.
5139     SDValue X = GetSignificand(DAG, Op1, dl);
5140 
5141     // Different possible minimax approximations of significand in
5142     // floating-point for various degrees of accuracy over [1,2].
5143     SDValue Log2ofMantissa;
5144     if (LimitFloatPrecision <= 6) {
5145       // For floating-point precision of 6:
5146       //
5147       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5148       //
5149       // error 0.0049451742, which is more than 7 bits
5150       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5151                                getF32Constant(DAG, 0xbeb08fe0, dl));
5152       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5153                                getF32Constant(DAG, 0x40019463, dl));
5154       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5155       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5156                                    getF32Constant(DAG, 0x3fd6633d, dl));
5157     } else if (LimitFloatPrecision <= 12) {
5158       // For floating-point precision of 12:
5159       //
5160       //   Log2ofMantissa =
5161       //     -2.51285454f +
5162       //       (4.07009056f +
5163       //         (-2.12067489f +
5164       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5165       //
5166       // error 0.0000876136000, which is better than 13 bits
5167       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5168                                getF32Constant(DAG, 0xbda7262e, dl));
5169       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5170                                getF32Constant(DAG, 0x3f25280b, dl));
5171       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5172       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5173                                getF32Constant(DAG, 0x4007b923, dl));
5174       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5175       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5176                                getF32Constant(DAG, 0x40823e2f, dl));
5177       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5178       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5179                                    getF32Constant(DAG, 0x4020d29c, dl));
5180     } else { // LimitFloatPrecision <= 18
5181       // For floating-point precision of 18:
5182       //
5183       //   Log2ofMantissa =
5184       //     -3.0400495f +
5185       //       (6.1129976f +
5186       //         (-5.3420409f +
5187       //           (3.2865683f +
5188       //             (-1.2669343f +
5189       //               (0.27515199f -
5190       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5191       //
5192       // error 0.0000018516, which is better than 18 bits
5193       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5194                                getF32Constant(DAG, 0xbcd2769e, dl));
5195       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5196                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5197       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5198       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5199                                getF32Constant(DAG, 0x3fa22ae7, dl));
5200       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5201       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5202                                getF32Constant(DAG, 0x40525723, dl));
5203       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5204       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5205                                getF32Constant(DAG, 0x40aaf200, dl));
5206       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5207       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5208                                getF32Constant(DAG, 0x40c39dad, dl));
5209       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5210       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5211                                    getF32Constant(DAG, 0x4042902c, dl));
5212     }
5213 
5214     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5215   }
5216 
5217   // No special expansion.
5218   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5219 }
5220 
5221 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5222 /// limited-precision mode.
5223 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5224                            const TargetLowering &TLI) {
5225   // TODO: What fast-math-flags should be set on the floating-point nodes?
5226 
5227   if (Op.getValueType() == MVT::f32 &&
5228       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5229     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5230 
5231     // Scale the exponent by log10(2) [0.30102999f].
5232     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5233     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5234                                         getF32Constant(DAG, 0x3e9a209a, dl));
5235 
5236     // Get the significand and build it into a floating-point number with
5237     // exponent of 1.
5238     SDValue X = GetSignificand(DAG, Op1, dl);
5239 
5240     SDValue Log10ofMantissa;
5241     if (LimitFloatPrecision <= 6) {
5242       // For floating-point precision of 6:
5243       //
5244       //   Log10ofMantissa =
5245       //     -0.50419619f +
5246       //       (0.60948995f - 0.10380950f * x) * x;
5247       //
5248       // error 0.0014886165, which is 6 bits
5249       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5250                                getF32Constant(DAG, 0xbdd49a13, dl));
5251       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5252                                getF32Constant(DAG, 0x3f1c0789, dl));
5253       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5254       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5255                                     getF32Constant(DAG, 0x3f011300, dl));
5256     } else if (LimitFloatPrecision <= 12) {
5257       // For floating-point precision of 12:
5258       //
5259       //   Log10ofMantissa =
5260       //     -0.64831180f +
5261       //       (0.91751397f +
5262       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5263       //
5264       // error 0.00019228036, which is better than 12 bits
5265       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5266                                getF32Constant(DAG, 0x3d431f31, dl));
5267       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5268                                getF32Constant(DAG, 0x3ea21fb2, dl));
5269       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5270       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5271                                getF32Constant(DAG, 0x3f6ae232, dl));
5272       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5273       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5274                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5275     } else { // LimitFloatPrecision <= 18
5276       // For floating-point precision of 18:
5277       //
5278       //   Log10ofMantissa =
5279       //     -0.84299375f +
5280       //       (1.5327582f +
5281       //         (-1.0688956f +
5282       //           (0.49102474f +
5283       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5284       //
5285       // error 0.0000037995730, which is better than 18 bits
5286       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5287                                getF32Constant(DAG, 0x3c5d51ce, dl));
5288       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5289                                getF32Constant(DAG, 0x3e00685a, dl));
5290       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5291       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5292                                getF32Constant(DAG, 0x3efb6798, dl));
5293       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5294       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5295                                getF32Constant(DAG, 0x3f88d192, dl));
5296       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5297       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5298                                getF32Constant(DAG, 0x3fc4316c, dl));
5299       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5300       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5301                                     getF32Constant(DAG, 0x3f57ce70, dl));
5302     }
5303 
5304     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5305   }
5306 
5307   // No special expansion.
5308   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5309 }
5310 
5311 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5312 /// limited-precision mode.
5313 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5314                           const TargetLowering &TLI) {
5315   if (Op.getValueType() == MVT::f32 &&
5316       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5317     return getLimitedPrecisionExp2(Op, dl, DAG);
5318 
5319   // No special expansion.
5320   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5321 }
5322 
5323 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5324 /// limited-precision mode with x == 10.0f.
5325 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5326                          SelectionDAG &DAG, const TargetLowering &TLI) {
5327   bool IsExp10 = false;
5328   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5329       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5330     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5331       APFloat Ten(10.0f);
5332       IsExp10 = LHSC->isExactlyValue(Ten);
5333     }
5334   }
5335 
5336   // TODO: What fast-math-flags should be set on the FMUL node?
5337   if (IsExp10) {
5338     // Put the exponent in the right bit position for later addition to the
5339     // final result:
5340     //
5341     //   #define LOG2OF10 3.3219281f
5342     //   t0 = Op * LOG2OF10;
5343     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5344                              getF32Constant(DAG, 0x40549a78, dl));
5345     return getLimitedPrecisionExp2(t0, dl, DAG);
5346   }
5347 
5348   // No special expansion.
5349   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5350 }
5351 
5352 /// ExpandPowI - Expand a llvm.powi intrinsic.
5353 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5354                           SelectionDAG &DAG) {
5355   // If RHS is a constant, we can expand this out to a multiplication tree,
5356   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5357   // optimizing for size, we only want to do this if the expansion would produce
5358   // a small number of multiplies, otherwise we do the full expansion.
5359   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5360     // Get the exponent as a positive value.
5361     unsigned Val = RHSC->getSExtValue();
5362     if ((int)Val < 0) Val = -Val;
5363 
5364     // powi(x, 0) -> 1.0
5365     if (Val == 0)
5366       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5367 
5368     bool OptForSize = DAG.shouldOptForSize();
5369     if (!OptForSize ||
5370         // If optimizing for size, don't insert too many multiplies.
5371         // This inserts up to 5 multiplies.
5372         countPopulation(Val) + Log2_32(Val) < 7) {
5373       // We use the simple binary decomposition method to generate the multiply
5374       // sequence.  There are more optimal ways to do this (for example,
5375       // powi(x,15) generates one more multiply than it should), but this has
5376       // the benefit of being both really simple and much better than a libcall.
5377       SDValue Res;  // Logically starts equal to 1.0
5378       SDValue CurSquare = LHS;
5379       // TODO: Intrinsics should have fast-math-flags that propagate to these
5380       // nodes.
5381       while (Val) {
5382         if (Val & 1) {
5383           if (Res.getNode())
5384             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5385           else
5386             Res = CurSquare;  // 1.0*CurSquare.
5387         }
5388 
5389         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5390                                 CurSquare, CurSquare);
5391         Val >>= 1;
5392       }
5393 
5394       // If the original was negative, invert the result, producing 1/(x*x*x).
5395       if (RHSC->getSExtValue() < 0)
5396         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5397                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5398       return Res;
5399     }
5400   }
5401 
5402   // Otherwise, expand to a libcall.
5403   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5404 }
5405 
5406 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5407 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5408 static void
5409 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
5410                      const SDValue &N) {
5411   switch (N.getOpcode()) {
5412   case ISD::CopyFromReg: {
5413     SDValue Op = N.getOperand(1);
5414     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5415                       Op.getValueType().getSizeInBits());
5416     return;
5417   }
5418   case ISD::BITCAST:
5419   case ISD::AssertZext:
5420   case ISD::AssertSext:
5421   case ISD::TRUNCATE:
5422     getUnderlyingArgRegs(Regs, N.getOperand(0));
5423     return;
5424   case ISD::BUILD_PAIR:
5425   case ISD::BUILD_VECTOR:
5426   case ISD::CONCAT_VECTORS:
5427     for (SDValue Op : N->op_values())
5428       getUnderlyingArgRegs(Regs, Op);
5429     return;
5430   default:
5431     return;
5432   }
5433 }
5434 
5435 /// If the DbgValueInst is a dbg_value of a function argument, create the
5436 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5437 /// instruction selection, they will be inserted to the entry BB.
5438 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5439     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5440     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5441   const Argument *Arg = dyn_cast<Argument>(V);
5442   if (!Arg)
5443     return false;
5444 
5445   if (!IsDbgDeclare) {
5446     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5447     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5448     // the entry block.
5449     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5450     if (!IsInEntryBlock)
5451       return false;
5452 
5453     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5454     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5455     // variable that also is a param.
5456     //
5457     // Although, if we are at the top of the entry block already, we can still
5458     // emit using ArgDbgValue. This might catch some situations when the
5459     // dbg.value refers to an argument that isn't used in the entry block, so
5460     // any CopyToReg node would be optimized out and the only way to express
5461     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5462     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5463     // we should only emit as ArgDbgValue if the Variable is an argument to the
5464     // current function, and the dbg.value intrinsic is found in the entry
5465     // block.
5466     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5467         !DL->getInlinedAt();
5468     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5469     if (!IsInPrologue && !VariableIsFunctionInputArg)
5470       return false;
5471 
5472     // Here we assume that a function argument on IR level only can be used to
5473     // describe one input parameter on source level. If we for example have
5474     // source code like this
5475     //
5476     //    struct A { long x, y; };
5477     //    void foo(struct A a, long b) {
5478     //      ...
5479     //      b = a.x;
5480     //      ...
5481     //    }
5482     //
5483     // and IR like this
5484     //
5485     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5486     //  entry:
5487     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5488     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5489     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5490     //    ...
5491     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5492     //    ...
5493     //
5494     // then the last dbg.value is describing a parameter "b" using a value that
5495     // is an argument. But since we already has used %a1 to describe a parameter
5496     // we should not handle that last dbg.value here (that would result in an
5497     // incorrect hoisting of the DBG_VALUE to the function entry).
5498     // Notice that we allow one dbg.value per IR level argument, to accommodate
5499     // for the situation with fragments above.
5500     if (VariableIsFunctionInputArg) {
5501       unsigned ArgNo = Arg->getArgNo();
5502       if (ArgNo >= FuncInfo.DescribedArgs.size())
5503         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5504       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5505         return false;
5506       FuncInfo.DescribedArgs.set(ArgNo);
5507     }
5508   }
5509 
5510   MachineFunction &MF = DAG.getMachineFunction();
5511   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5512 
5513   Optional<MachineOperand> Op;
5514   // Some arguments' frame index is recorded during argument lowering.
5515   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5516   if (FI != std::numeric_limits<int>::max())
5517     Op = MachineOperand::CreateFI(FI);
5518 
5519   SmallVector<std::pair<unsigned, unsigned>, 8> ArgRegsAndSizes;
5520   if (!Op && N.getNode()) {
5521     getUnderlyingArgRegs(ArgRegsAndSizes, N);
5522     Register Reg;
5523     if (ArgRegsAndSizes.size() == 1)
5524       Reg = ArgRegsAndSizes.front().first;
5525 
5526     if (Reg && Reg.isVirtual()) {
5527       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5528       Register PR = RegInfo.getLiveInPhysReg(Reg);
5529       if (PR)
5530         Reg = PR;
5531     }
5532     if (Reg) {
5533       Op = MachineOperand::CreateReg(Reg, false);
5534     }
5535   }
5536 
5537   if (!Op && N.getNode()) {
5538     // Check if frame index is available.
5539     SDValue LCandidate = peekThroughBitcasts(N);
5540     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5541       if (FrameIndexSDNode *FINode =
5542           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5543         Op = MachineOperand::CreateFI(FINode->getIndex());
5544   }
5545 
5546   if (!Op) {
5547     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
5548     auto splitMultiRegDbgValue
5549       = [&](ArrayRef<std::pair<unsigned, unsigned>> SplitRegs) {
5550       unsigned Offset = 0;
5551       for (auto RegAndSize : SplitRegs) {
5552         auto FragmentExpr = DIExpression::createFragmentExpression(
5553           Expr, Offset, RegAndSize.second);
5554         // If a valid fragment expression cannot be created, the variable's
5555         // correct value cannot be determined and so it is set as Undef.
5556         if (!FragmentExpr) {
5557           SDDbgValue *SDV = DAG.getConstantDbgValue(
5558               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
5559           DAG.AddDbgValue(SDV, nullptr, false);
5560           continue;
5561         }
5562         assert(!IsDbgDeclare && "DbgDeclare operand is not in memory?");
5563         FuncInfo.ArgDbgValues.push_back(
5564           BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5565                   RegAndSize.first, Variable, *FragmentExpr));
5566         Offset += RegAndSize.second;
5567       }
5568     };
5569 
5570     // Check if ValueMap has reg number.
5571     DenseMap<const Value *, unsigned>::const_iterator
5572       VMI = FuncInfo.ValueMap.find(V);
5573     if (VMI != FuncInfo.ValueMap.end()) {
5574       const auto &TLI = DAG.getTargetLoweringInfo();
5575       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5576                        V->getType(), getABIRegCopyCC(V));
5577       if (RFV.occupiesMultipleRegs()) {
5578         splitMultiRegDbgValue(RFV.getRegsAndSizes());
5579         return true;
5580       }
5581 
5582       Op = MachineOperand::CreateReg(VMI->second, false);
5583     } else if (ArgRegsAndSizes.size() > 1) {
5584       // This was split due to the calling convention, and no virtual register
5585       // mapping exists for the value.
5586       splitMultiRegDbgValue(ArgRegsAndSizes);
5587       return true;
5588     }
5589   }
5590 
5591   if (!Op)
5592     return false;
5593 
5594   assert(Variable->isValidLocationForIntrinsic(DL) &&
5595          "Expected inlined-at fields to agree");
5596 
5597   // If the argument arrives in a stack slot, then what the IR thought was a
5598   // normal Value is actually in memory, and we must add a deref to load it.
5599   if (Op->isFI()) {
5600     int FI = Op->getIndex();
5601     unsigned Size = DAG.getMachineFunction().getFrameInfo().getObjectSize(FI);
5602     if (Expr->isImplicit()) {
5603       SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
5604       Expr = DIExpression::prependOpcodes(Expr, Ops);
5605     } else {
5606       Expr = DIExpression::prepend(Expr, DIExpression::DerefBefore);
5607     }
5608   }
5609 
5610   // If this location was specified with a dbg.declare, then it and its
5611   // expression calculate the address of the variable. Append a deref to
5612   // force it to be a memory location.
5613   if (IsDbgDeclare)
5614     Expr = DIExpression::append(Expr, {dwarf::DW_OP_deref});
5615 
5616   FuncInfo.ArgDbgValues.push_back(
5617       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), false,
5618               *Op, Variable, Expr));
5619 
5620   return true;
5621 }
5622 
5623 /// Return the appropriate SDDbgValue based on N.
5624 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5625                                              DILocalVariable *Variable,
5626                                              DIExpression *Expr,
5627                                              const DebugLoc &dl,
5628                                              unsigned DbgSDNodeOrder) {
5629   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5630     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5631     // stack slot locations.
5632     //
5633     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5634     // debug values here after optimization:
5635     //
5636     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5637     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5638     //
5639     // Both describe the direct values of their associated variables.
5640     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5641                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5642   }
5643   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5644                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5645 }
5646 
5647 // VisualStudio defines setjmp as _setjmp
5648 #if defined(_MSC_VER) && defined(setjmp) && \
5649                          !defined(setjmp_undefined_for_msvc)
5650 #  pragma push_macro("setjmp")
5651 #  undef setjmp
5652 #  define setjmp_undefined_for_msvc
5653 #endif
5654 
5655 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5656   switch (Intrinsic) {
5657   case Intrinsic::smul_fix:
5658     return ISD::SMULFIX;
5659   case Intrinsic::umul_fix:
5660     return ISD::UMULFIX;
5661   default:
5662     llvm_unreachable("Unhandled fixed point intrinsic");
5663   }
5664 }
5665 
5666 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5667                                            const char *FunctionName) {
5668   assert(FunctionName && "FunctionName must not be nullptr");
5669   SDValue Callee = DAG.getExternalSymbol(
5670       FunctionName,
5671       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5672   LowerCallTo(&I, Callee, I.isTailCall());
5673 }
5674 
5675 /// Lower the call to the specified intrinsic function.
5676 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5677                                              unsigned Intrinsic) {
5678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5679   SDLoc sdl = getCurSDLoc();
5680   DebugLoc dl = getCurDebugLoc();
5681   SDValue Res;
5682 
5683   switch (Intrinsic) {
5684   default:
5685     // By default, turn this into a target intrinsic node.
5686     visitTargetIntrinsic(I, Intrinsic);
5687     return;
5688   case Intrinsic::vastart:  visitVAStart(I); return;
5689   case Intrinsic::vaend:    visitVAEnd(I); return;
5690   case Intrinsic::vacopy:   visitVACopy(I); return;
5691   case Intrinsic::returnaddress:
5692     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5693                              TLI.getPointerTy(DAG.getDataLayout()),
5694                              getValue(I.getArgOperand(0))));
5695     return;
5696   case Intrinsic::addressofreturnaddress:
5697     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5698                              TLI.getPointerTy(DAG.getDataLayout())));
5699     return;
5700   case Intrinsic::sponentry:
5701     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5702                              TLI.getFrameIndexTy(DAG.getDataLayout())));
5703     return;
5704   case Intrinsic::frameaddress:
5705     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5706                              TLI.getFrameIndexTy(DAG.getDataLayout()),
5707                              getValue(I.getArgOperand(0))));
5708     return;
5709   case Intrinsic::read_register: {
5710     Value *Reg = I.getArgOperand(0);
5711     SDValue Chain = getRoot();
5712     SDValue RegName =
5713         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5714     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5715     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5716       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5717     setValue(&I, Res);
5718     DAG.setRoot(Res.getValue(1));
5719     return;
5720   }
5721   case Intrinsic::write_register: {
5722     Value *Reg = I.getArgOperand(0);
5723     Value *RegValue = I.getArgOperand(1);
5724     SDValue Chain = getRoot();
5725     SDValue RegName =
5726         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5727     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5728                             RegName, getValue(RegValue)));
5729     return;
5730   }
5731   case Intrinsic::setjmp:
5732     lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
5733     return;
5734   case Intrinsic::longjmp:
5735     lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
5736     return;
5737   case Intrinsic::memcpy: {
5738     const auto &MCI = cast<MemCpyInst>(I);
5739     SDValue Op1 = getValue(I.getArgOperand(0));
5740     SDValue Op2 = getValue(I.getArgOperand(1));
5741     SDValue Op3 = getValue(I.getArgOperand(2));
5742     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5743     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5744     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5745     unsigned Align = MinAlign(DstAlign, SrcAlign);
5746     bool isVol = MCI.isVolatile();
5747     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5748     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5749     // node.
5750     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5751                                false, isTC,
5752                                MachinePointerInfo(I.getArgOperand(0)),
5753                                MachinePointerInfo(I.getArgOperand(1)));
5754     updateDAGForMaybeTailCall(MC);
5755     return;
5756   }
5757   case Intrinsic::memset: {
5758     const auto &MSI = cast<MemSetInst>(I);
5759     SDValue Op1 = getValue(I.getArgOperand(0));
5760     SDValue Op2 = getValue(I.getArgOperand(1));
5761     SDValue Op3 = getValue(I.getArgOperand(2));
5762     // @llvm.memset defines 0 and 1 to both mean no alignment.
5763     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5764     bool isVol = MSI.isVolatile();
5765     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5766     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5767                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5768     updateDAGForMaybeTailCall(MS);
5769     return;
5770   }
5771   case Intrinsic::memmove: {
5772     const auto &MMI = cast<MemMoveInst>(I);
5773     SDValue Op1 = getValue(I.getArgOperand(0));
5774     SDValue Op2 = getValue(I.getArgOperand(1));
5775     SDValue Op3 = getValue(I.getArgOperand(2));
5776     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5777     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5778     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5779     unsigned Align = MinAlign(DstAlign, SrcAlign);
5780     bool isVol = MMI.isVolatile();
5781     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5782     // FIXME: Support passing different dest/src alignments to the memmove DAG
5783     // node.
5784     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5785                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5786                                 MachinePointerInfo(I.getArgOperand(1)));
5787     updateDAGForMaybeTailCall(MM);
5788     return;
5789   }
5790   case Intrinsic::memcpy_element_unordered_atomic: {
5791     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5792     SDValue Dst = getValue(MI.getRawDest());
5793     SDValue Src = getValue(MI.getRawSource());
5794     SDValue Length = getValue(MI.getLength());
5795 
5796     unsigned DstAlign = MI.getDestAlignment();
5797     unsigned SrcAlign = MI.getSourceAlignment();
5798     Type *LengthTy = MI.getLength()->getType();
5799     unsigned ElemSz = MI.getElementSizeInBytes();
5800     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5801     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5802                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5803                                      MachinePointerInfo(MI.getRawDest()),
5804                                      MachinePointerInfo(MI.getRawSource()));
5805     updateDAGForMaybeTailCall(MC);
5806     return;
5807   }
5808   case Intrinsic::memmove_element_unordered_atomic: {
5809     auto &MI = cast<AtomicMemMoveInst>(I);
5810     SDValue Dst = getValue(MI.getRawDest());
5811     SDValue Src = getValue(MI.getRawSource());
5812     SDValue Length = getValue(MI.getLength());
5813 
5814     unsigned DstAlign = MI.getDestAlignment();
5815     unsigned SrcAlign = MI.getSourceAlignment();
5816     Type *LengthTy = MI.getLength()->getType();
5817     unsigned ElemSz = MI.getElementSizeInBytes();
5818     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5819     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5820                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5821                                       MachinePointerInfo(MI.getRawDest()),
5822                                       MachinePointerInfo(MI.getRawSource()));
5823     updateDAGForMaybeTailCall(MC);
5824     return;
5825   }
5826   case Intrinsic::memset_element_unordered_atomic: {
5827     auto &MI = cast<AtomicMemSetInst>(I);
5828     SDValue Dst = getValue(MI.getRawDest());
5829     SDValue Val = getValue(MI.getValue());
5830     SDValue Length = getValue(MI.getLength());
5831 
5832     unsigned DstAlign = MI.getDestAlignment();
5833     Type *LengthTy = MI.getLength()->getType();
5834     unsigned ElemSz = MI.getElementSizeInBytes();
5835     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5836     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5837                                      LengthTy, ElemSz, isTC,
5838                                      MachinePointerInfo(MI.getRawDest()));
5839     updateDAGForMaybeTailCall(MC);
5840     return;
5841   }
5842   case Intrinsic::dbg_addr:
5843   case Intrinsic::dbg_declare: {
5844     const auto &DI = cast<DbgVariableIntrinsic>(I);
5845     DILocalVariable *Variable = DI.getVariable();
5846     DIExpression *Expression = DI.getExpression();
5847     dropDanglingDebugInfo(Variable, Expression);
5848     assert(Variable && "Missing variable");
5849 
5850     // Check if address has undef value.
5851     const Value *Address = DI.getVariableLocation();
5852     if (!Address || isa<UndefValue>(Address) ||
5853         (Address->use_empty() && !isa<Argument>(Address))) {
5854       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5855       return;
5856     }
5857 
5858     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5859 
5860     // Check if this variable can be described by a frame index, typically
5861     // either as a static alloca or a byval parameter.
5862     int FI = std::numeric_limits<int>::max();
5863     if (const auto *AI =
5864             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5865       if (AI->isStaticAlloca()) {
5866         auto I = FuncInfo.StaticAllocaMap.find(AI);
5867         if (I != FuncInfo.StaticAllocaMap.end())
5868           FI = I->second;
5869       }
5870     } else if (const auto *Arg = dyn_cast<Argument>(
5871                    Address->stripInBoundsConstantOffsets())) {
5872       FI = FuncInfo.getArgumentFrameIndex(Arg);
5873     }
5874 
5875     // llvm.dbg.addr is control dependent and always generates indirect
5876     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5877     // the MachineFunction variable table.
5878     if (FI != std::numeric_limits<int>::max()) {
5879       if (Intrinsic == Intrinsic::dbg_addr) {
5880         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5881             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5882         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5883       }
5884       return;
5885     }
5886 
5887     SDValue &N = NodeMap[Address];
5888     if (!N.getNode() && isa<Argument>(Address))
5889       // Check unused arguments map.
5890       N = UnusedArgNodeMap[Address];
5891     SDDbgValue *SDV;
5892     if (N.getNode()) {
5893       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5894         Address = BCI->getOperand(0);
5895       // Parameters are handled specially.
5896       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5897       if (isParameter && FINode) {
5898         // Byval parameter. We have a frame index at this point.
5899         SDV =
5900             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5901                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5902       } else if (isa<Argument>(Address)) {
5903         // Address is an argument, so try to emit its dbg value using
5904         // virtual register info from the FuncInfo.ValueMap.
5905         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5906         return;
5907       } else {
5908         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5909                               true, dl, SDNodeOrder);
5910       }
5911       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5912     } else {
5913       // If Address is an argument then try to emit its dbg value using
5914       // virtual register info from the FuncInfo.ValueMap.
5915       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5916                                     N)) {
5917         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5918       }
5919     }
5920     return;
5921   }
5922   case Intrinsic::dbg_label: {
5923     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5924     DILabel *Label = DI.getLabel();
5925     assert(Label && "Missing label");
5926 
5927     SDDbgLabel *SDV;
5928     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5929     DAG.AddDbgLabel(SDV);
5930     return;
5931   }
5932   case Intrinsic::dbg_value: {
5933     const DbgValueInst &DI = cast<DbgValueInst>(I);
5934     assert(DI.getVariable() && "Missing variable");
5935 
5936     DILocalVariable *Variable = DI.getVariable();
5937     DIExpression *Expression = DI.getExpression();
5938     dropDanglingDebugInfo(Variable, Expression);
5939     const Value *V = DI.getValue();
5940     if (!V)
5941       return;
5942 
5943     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5944         SDNodeOrder))
5945       return;
5946 
5947     // TODO: Dangling debug info will eventually either be resolved or produce
5948     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5949     // between the original dbg.value location and its resolved DBG_VALUE, which
5950     // we should ideally fill with an extra Undef DBG_VALUE.
5951 
5952     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5953     return;
5954   }
5955 
5956   case Intrinsic::eh_typeid_for: {
5957     // Find the type id for the given typeinfo.
5958     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5959     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5960     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5961     setValue(&I, Res);
5962     return;
5963   }
5964 
5965   case Intrinsic::eh_return_i32:
5966   case Intrinsic::eh_return_i64:
5967     DAG.getMachineFunction().setCallsEHReturn(true);
5968     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5969                             MVT::Other,
5970                             getControlRoot(),
5971                             getValue(I.getArgOperand(0)),
5972                             getValue(I.getArgOperand(1))));
5973     return;
5974   case Intrinsic::eh_unwind_init:
5975     DAG.getMachineFunction().setCallsUnwindInit(true);
5976     return;
5977   case Intrinsic::eh_dwarf_cfa:
5978     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5979                              TLI.getPointerTy(DAG.getDataLayout()),
5980                              getValue(I.getArgOperand(0))));
5981     return;
5982   case Intrinsic::eh_sjlj_callsite: {
5983     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5984     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5985     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5986     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5987 
5988     MMI.setCurrentCallSite(CI->getZExtValue());
5989     return;
5990   }
5991   case Intrinsic::eh_sjlj_functioncontext: {
5992     // Get and store the index of the function context.
5993     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5994     AllocaInst *FnCtx =
5995       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5996     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5997     MFI.setFunctionContextIndex(FI);
5998     return;
5999   }
6000   case Intrinsic::eh_sjlj_setjmp: {
6001     SDValue Ops[2];
6002     Ops[0] = getRoot();
6003     Ops[1] = getValue(I.getArgOperand(0));
6004     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6005                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6006     setValue(&I, Op.getValue(0));
6007     DAG.setRoot(Op.getValue(1));
6008     return;
6009   }
6010   case Intrinsic::eh_sjlj_longjmp:
6011     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6012                             getRoot(), getValue(I.getArgOperand(0))));
6013     return;
6014   case Intrinsic::eh_sjlj_setup_dispatch:
6015     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6016                             getRoot()));
6017     return;
6018   case Intrinsic::masked_gather:
6019     visitMaskedGather(I);
6020     return;
6021   case Intrinsic::masked_load:
6022     visitMaskedLoad(I);
6023     return;
6024   case Intrinsic::masked_scatter:
6025     visitMaskedScatter(I);
6026     return;
6027   case Intrinsic::masked_store:
6028     visitMaskedStore(I);
6029     return;
6030   case Intrinsic::masked_expandload:
6031     visitMaskedLoad(I, true /* IsExpanding */);
6032     return;
6033   case Intrinsic::masked_compressstore:
6034     visitMaskedStore(I, true /* IsCompressing */);
6035     return;
6036   case Intrinsic::powi:
6037     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6038                             getValue(I.getArgOperand(1)), DAG));
6039     return;
6040   case Intrinsic::log:
6041     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6042     return;
6043   case Intrinsic::log2:
6044     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6045     return;
6046   case Intrinsic::log10:
6047     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6048     return;
6049   case Intrinsic::exp:
6050     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6051     return;
6052   case Intrinsic::exp2:
6053     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
6054     return;
6055   case Intrinsic::pow:
6056     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6057                            getValue(I.getArgOperand(1)), DAG, TLI));
6058     return;
6059   case Intrinsic::sqrt:
6060   case Intrinsic::fabs:
6061   case Intrinsic::sin:
6062   case Intrinsic::cos:
6063   case Intrinsic::floor:
6064   case Intrinsic::ceil:
6065   case Intrinsic::trunc:
6066   case Intrinsic::rint:
6067   case Intrinsic::nearbyint:
6068   case Intrinsic::round:
6069   case Intrinsic::canonicalize: {
6070     unsigned Opcode;
6071     switch (Intrinsic) {
6072     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6073     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6074     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6075     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6076     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6077     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6078     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6079     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6080     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6081     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6082     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6083     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6084     }
6085 
6086     setValue(&I, DAG.getNode(Opcode, sdl,
6087                              getValue(I.getArgOperand(0)).getValueType(),
6088                              getValue(I.getArgOperand(0))));
6089     return;
6090   }
6091   case Intrinsic::lround:
6092   case Intrinsic::llround:
6093   case Intrinsic::lrint:
6094   case Intrinsic::llrint: {
6095     unsigned Opcode;
6096     switch (Intrinsic) {
6097     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6098     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6099     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6100     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6101     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6102     }
6103 
6104     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6105     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6106                              getValue(I.getArgOperand(0))));
6107     return;
6108   }
6109   case Intrinsic::minnum:
6110     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6111                              getValue(I.getArgOperand(0)).getValueType(),
6112                              getValue(I.getArgOperand(0)),
6113                              getValue(I.getArgOperand(1))));
6114     return;
6115   case Intrinsic::maxnum:
6116     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6117                              getValue(I.getArgOperand(0)).getValueType(),
6118                              getValue(I.getArgOperand(0)),
6119                              getValue(I.getArgOperand(1))));
6120     return;
6121   case Intrinsic::minimum:
6122     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6123                              getValue(I.getArgOperand(0)).getValueType(),
6124                              getValue(I.getArgOperand(0)),
6125                              getValue(I.getArgOperand(1))));
6126     return;
6127   case Intrinsic::maximum:
6128     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6129                              getValue(I.getArgOperand(0)).getValueType(),
6130                              getValue(I.getArgOperand(0)),
6131                              getValue(I.getArgOperand(1))));
6132     return;
6133   case Intrinsic::copysign:
6134     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6135                              getValue(I.getArgOperand(0)).getValueType(),
6136                              getValue(I.getArgOperand(0)),
6137                              getValue(I.getArgOperand(1))));
6138     return;
6139   case Intrinsic::fma:
6140     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6141                              getValue(I.getArgOperand(0)).getValueType(),
6142                              getValue(I.getArgOperand(0)),
6143                              getValue(I.getArgOperand(1)),
6144                              getValue(I.getArgOperand(2))));
6145     return;
6146 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6147   case Intrinsic::INTRINSIC:
6148 #include "llvm/IR/ConstrainedOps.def"
6149     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6150     return;
6151   case Intrinsic::fmuladd: {
6152     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6153     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6154         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6155       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6156                                getValue(I.getArgOperand(0)).getValueType(),
6157                                getValue(I.getArgOperand(0)),
6158                                getValue(I.getArgOperand(1)),
6159                                getValue(I.getArgOperand(2))));
6160     } else {
6161       // TODO: Intrinsic calls should have fast-math-flags.
6162       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6163                                 getValue(I.getArgOperand(0)).getValueType(),
6164                                 getValue(I.getArgOperand(0)),
6165                                 getValue(I.getArgOperand(1)));
6166       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6167                                 getValue(I.getArgOperand(0)).getValueType(),
6168                                 Mul,
6169                                 getValue(I.getArgOperand(2)));
6170       setValue(&I, Add);
6171     }
6172     return;
6173   }
6174   case Intrinsic::convert_to_fp16:
6175     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6176                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6177                                          getValue(I.getArgOperand(0)),
6178                                          DAG.getTargetConstant(0, sdl,
6179                                                                MVT::i32))));
6180     return;
6181   case Intrinsic::convert_from_fp16:
6182     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6183                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6184                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6185                                          getValue(I.getArgOperand(0)))));
6186     return;
6187   case Intrinsic::pcmarker: {
6188     SDValue Tmp = getValue(I.getArgOperand(0));
6189     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6190     return;
6191   }
6192   case Intrinsic::readcyclecounter: {
6193     SDValue Op = getRoot();
6194     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6195                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6196     setValue(&I, Res);
6197     DAG.setRoot(Res.getValue(1));
6198     return;
6199   }
6200   case Intrinsic::bitreverse:
6201     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6202                              getValue(I.getArgOperand(0)).getValueType(),
6203                              getValue(I.getArgOperand(0))));
6204     return;
6205   case Intrinsic::bswap:
6206     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6207                              getValue(I.getArgOperand(0)).getValueType(),
6208                              getValue(I.getArgOperand(0))));
6209     return;
6210   case Intrinsic::cttz: {
6211     SDValue Arg = getValue(I.getArgOperand(0));
6212     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6213     EVT Ty = Arg.getValueType();
6214     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6215                              sdl, Ty, Arg));
6216     return;
6217   }
6218   case Intrinsic::ctlz: {
6219     SDValue Arg = getValue(I.getArgOperand(0));
6220     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6221     EVT Ty = Arg.getValueType();
6222     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6223                              sdl, Ty, Arg));
6224     return;
6225   }
6226   case Intrinsic::ctpop: {
6227     SDValue Arg = getValue(I.getArgOperand(0));
6228     EVT Ty = Arg.getValueType();
6229     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6230     return;
6231   }
6232   case Intrinsic::fshl:
6233   case Intrinsic::fshr: {
6234     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6235     SDValue X = getValue(I.getArgOperand(0));
6236     SDValue Y = getValue(I.getArgOperand(1));
6237     SDValue Z = getValue(I.getArgOperand(2));
6238     EVT VT = X.getValueType();
6239     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6240     SDValue Zero = DAG.getConstant(0, sdl, VT);
6241     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6242 
6243     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6244     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6245       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6246       return;
6247     }
6248 
6249     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6250     // avoid the select that is necessary in the general case to filter out
6251     // the 0-shift possibility that leads to UB.
6252     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6253       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6254       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6255         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6256         return;
6257       }
6258 
6259       // Some targets only rotate one way. Try the opposite direction.
6260       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6261       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6262         // Negate the shift amount because it is safe to ignore the high bits.
6263         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6264         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6265         return;
6266       }
6267 
6268       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6269       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6270       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6271       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6272       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6273       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6274       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6275       return;
6276     }
6277 
6278     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6279     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6280     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6281     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6282     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6283     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6284 
6285     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6286     // and that is undefined. We must compare and select to avoid UB.
6287     EVT CCVT = MVT::i1;
6288     if (VT.isVector())
6289       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6290 
6291     // For fshl, 0-shift returns the 1st arg (X).
6292     // For fshr, 0-shift returns the 2nd arg (Y).
6293     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6294     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6295     return;
6296   }
6297   case Intrinsic::sadd_sat: {
6298     SDValue Op1 = getValue(I.getArgOperand(0));
6299     SDValue Op2 = getValue(I.getArgOperand(1));
6300     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6301     return;
6302   }
6303   case Intrinsic::uadd_sat: {
6304     SDValue Op1 = getValue(I.getArgOperand(0));
6305     SDValue Op2 = getValue(I.getArgOperand(1));
6306     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6307     return;
6308   }
6309   case Intrinsic::ssub_sat: {
6310     SDValue Op1 = getValue(I.getArgOperand(0));
6311     SDValue Op2 = getValue(I.getArgOperand(1));
6312     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6313     return;
6314   }
6315   case Intrinsic::usub_sat: {
6316     SDValue Op1 = getValue(I.getArgOperand(0));
6317     SDValue Op2 = getValue(I.getArgOperand(1));
6318     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6319     return;
6320   }
6321   case Intrinsic::smul_fix:
6322   case Intrinsic::umul_fix: {
6323     SDValue Op1 = getValue(I.getArgOperand(0));
6324     SDValue Op2 = getValue(I.getArgOperand(1));
6325     SDValue Op3 = getValue(I.getArgOperand(2));
6326     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6327                              Op1.getValueType(), Op1, Op2, Op3));
6328     return;
6329   }
6330   case Intrinsic::smul_fix_sat: {
6331     SDValue Op1 = getValue(I.getArgOperand(0));
6332     SDValue Op2 = getValue(I.getArgOperand(1));
6333     SDValue Op3 = getValue(I.getArgOperand(2));
6334     setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6335                              Op3));
6336     return;
6337   }
6338   case Intrinsic::umul_fix_sat: {
6339     SDValue Op1 = getValue(I.getArgOperand(0));
6340     SDValue Op2 = getValue(I.getArgOperand(1));
6341     SDValue Op3 = getValue(I.getArgOperand(2));
6342     setValue(&I, DAG.getNode(ISD::UMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6343                              Op3));
6344     return;
6345   }
6346   case Intrinsic::stacksave: {
6347     SDValue Op = getRoot();
6348     Res = DAG.getNode(
6349         ISD::STACKSAVE, sdl,
6350         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6351     setValue(&I, Res);
6352     DAG.setRoot(Res.getValue(1));
6353     return;
6354   }
6355   case Intrinsic::stackrestore:
6356     Res = getValue(I.getArgOperand(0));
6357     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6358     return;
6359   case Intrinsic::get_dynamic_area_offset: {
6360     SDValue Op = getRoot();
6361     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6362     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6363     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6364     // target.
6365     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6366       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6367                          " intrinsic!");
6368     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6369                       Op);
6370     DAG.setRoot(Op);
6371     setValue(&I, Res);
6372     return;
6373   }
6374   case Intrinsic::stackguard: {
6375     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6376     MachineFunction &MF = DAG.getMachineFunction();
6377     const Module &M = *MF.getFunction().getParent();
6378     SDValue Chain = getRoot();
6379     if (TLI.useLoadStackGuardNode()) {
6380       Res = getLoadStackGuard(DAG, sdl, Chain);
6381     } else {
6382       const Value *Global = TLI.getSDagStackGuard(M);
6383       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6384       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6385                         MachinePointerInfo(Global, 0), Align,
6386                         MachineMemOperand::MOVolatile);
6387     }
6388     if (TLI.useStackGuardXorFP())
6389       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6390     DAG.setRoot(Chain);
6391     setValue(&I, Res);
6392     return;
6393   }
6394   case Intrinsic::stackprotector: {
6395     // Emit code into the DAG to store the stack guard onto the stack.
6396     MachineFunction &MF = DAG.getMachineFunction();
6397     MachineFrameInfo &MFI = MF.getFrameInfo();
6398     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6399     SDValue Src, Chain = getRoot();
6400 
6401     if (TLI.useLoadStackGuardNode())
6402       Src = getLoadStackGuard(DAG, sdl, Chain);
6403     else
6404       Src = getValue(I.getArgOperand(0));   // The guard's value.
6405 
6406     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6407 
6408     int FI = FuncInfo.StaticAllocaMap[Slot];
6409     MFI.setStackProtectorIndex(FI);
6410 
6411     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6412 
6413     // Store the stack protector onto the stack.
6414     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6415                                                  DAG.getMachineFunction(), FI),
6416                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6417     setValue(&I, Res);
6418     DAG.setRoot(Res);
6419     return;
6420   }
6421   case Intrinsic::objectsize:
6422     llvm_unreachable("llvm.objectsize.* should have been lowered already");
6423 
6424   case Intrinsic::is_constant:
6425     llvm_unreachable("llvm.is.constant.* should have been lowered already");
6426 
6427   case Intrinsic::annotation:
6428   case Intrinsic::ptr_annotation:
6429   case Intrinsic::launder_invariant_group:
6430   case Intrinsic::strip_invariant_group:
6431     // Drop the intrinsic, but forward the value
6432     setValue(&I, getValue(I.getOperand(0)));
6433     return;
6434   case Intrinsic::assume:
6435   case Intrinsic::var_annotation:
6436   case Intrinsic::sideeffect:
6437     // Discard annotate attributes, assumptions, and artificial side-effects.
6438     return;
6439 
6440   case Intrinsic::codeview_annotation: {
6441     // Emit a label associated with this metadata.
6442     MachineFunction &MF = DAG.getMachineFunction();
6443     MCSymbol *Label =
6444         MF.getMMI().getContext().createTempSymbol("annotation", true);
6445     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6446     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6447     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6448     DAG.setRoot(Res);
6449     return;
6450   }
6451 
6452   case Intrinsic::init_trampoline: {
6453     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6454 
6455     SDValue Ops[6];
6456     Ops[0] = getRoot();
6457     Ops[1] = getValue(I.getArgOperand(0));
6458     Ops[2] = getValue(I.getArgOperand(1));
6459     Ops[3] = getValue(I.getArgOperand(2));
6460     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6461     Ops[5] = DAG.getSrcValue(F);
6462 
6463     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6464 
6465     DAG.setRoot(Res);
6466     return;
6467   }
6468   case Intrinsic::adjust_trampoline:
6469     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6470                              TLI.getPointerTy(DAG.getDataLayout()),
6471                              getValue(I.getArgOperand(0))));
6472     return;
6473   case Intrinsic::gcroot: {
6474     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6475            "only valid in functions with gc specified, enforced by Verifier");
6476     assert(GFI && "implied by previous");
6477     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6478     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6479 
6480     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6481     GFI->addStackRoot(FI->getIndex(), TypeMap);
6482     return;
6483   }
6484   case Intrinsic::gcread:
6485   case Intrinsic::gcwrite:
6486     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6487   case Intrinsic::flt_rounds:
6488     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6489     return;
6490 
6491   case Intrinsic::expect:
6492     // Just replace __builtin_expect(exp, c) with EXP.
6493     setValue(&I, getValue(I.getArgOperand(0)));
6494     return;
6495 
6496   case Intrinsic::debugtrap:
6497   case Intrinsic::trap: {
6498     StringRef TrapFuncName =
6499         I.getAttributes()
6500             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6501             .getValueAsString();
6502     if (TrapFuncName.empty()) {
6503       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6504         ISD::TRAP : ISD::DEBUGTRAP;
6505       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6506       return;
6507     }
6508     TargetLowering::ArgListTy Args;
6509 
6510     TargetLowering::CallLoweringInfo CLI(DAG);
6511     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6512         CallingConv::C, I.getType(),
6513         DAG.getExternalSymbol(TrapFuncName.data(),
6514                               TLI.getPointerTy(DAG.getDataLayout())),
6515         std::move(Args));
6516 
6517     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6518     DAG.setRoot(Result.second);
6519     return;
6520   }
6521 
6522   case Intrinsic::uadd_with_overflow:
6523   case Intrinsic::sadd_with_overflow:
6524   case Intrinsic::usub_with_overflow:
6525   case Intrinsic::ssub_with_overflow:
6526   case Intrinsic::umul_with_overflow:
6527   case Intrinsic::smul_with_overflow: {
6528     ISD::NodeType Op;
6529     switch (Intrinsic) {
6530     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6531     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6532     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6533     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6534     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6535     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6536     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6537     }
6538     SDValue Op1 = getValue(I.getArgOperand(0));
6539     SDValue Op2 = getValue(I.getArgOperand(1));
6540 
6541     EVT ResultVT = Op1.getValueType();
6542     EVT OverflowVT = MVT::i1;
6543     if (ResultVT.isVector())
6544       OverflowVT = EVT::getVectorVT(
6545           *Context, OverflowVT, ResultVT.getVectorNumElements());
6546 
6547     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6548     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6549     return;
6550   }
6551   case Intrinsic::prefetch: {
6552     SDValue Ops[5];
6553     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6554     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6555     Ops[0] = DAG.getRoot();
6556     Ops[1] = getValue(I.getArgOperand(0));
6557     Ops[2] = getValue(I.getArgOperand(1));
6558     Ops[3] = getValue(I.getArgOperand(2));
6559     Ops[4] = getValue(I.getArgOperand(3));
6560     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6561                                              DAG.getVTList(MVT::Other), Ops,
6562                                              EVT::getIntegerVT(*Context, 8),
6563                                              MachinePointerInfo(I.getArgOperand(0)),
6564                                              0, /* align */
6565                                              Flags);
6566 
6567     // Chain the prefetch in parallell with any pending loads, to stay out of
6568     // the way of later optimizations.
6569     PendingLoads.push_back(Result);
6570     Result = getRoot();
6571     DAG.setRoot(Result);
6572     return;
6573   }
6574   case Intrinsic::lifetime_start:
6575   case Intrinsic::lifetime_end: {
6576     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6577     // Stack coloring is not enabled in O0, discard region information.
6578     if (TM.getOptLevel() == CodeGenOpt::None)
6579       return;
6580 
6581     const int64_t ObjectSize =
6582         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6583     Value *const ObjectPtr = I.getArgOperand(1);
6584     SmallVector<const Value *, 4> Allocas;
6585     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6586 
6587     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6588            E = Allocas.end(); Object != E; ++Object) {
6589       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6590 
6591       // Could not find an Alloca.
6592       if (!LifetimeObject)
6593         continue;
6594 
6595       // First check that the Alloca is static, otherwise it won't have a
6596       // valid frame index.
6597       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6598       if (SI == FuncInfo.StaticAllocaMap.end())
6599         return;
6600 
6601       const int FrameIndex = SI->second;
6602       int64_t Offset;
6603       if (GetPointerBaseWithConstantOffset(
6604               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6605         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6606       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6607                                 Offset);
6608       DAG.setRoot(Res);
6609     }
6610     return;
6611   }
6612   case Intrinsic::invariant_start:
6613     // Discard region information.
6614     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6615     return;
6616   case Intrinsic::invariant_end:
6617     // Discard region information.
6618     return;
6619   case Intrinsic::clear_cache:
6620     /// FunctionName may be null.
6621     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6622       lowerCallToExternalSymbol(I, FunctionName);
6623     return;
6624   case Intrinsic::donothing:
6625     // ignore
6626     return;
6627   case Intrinsic::experimental_stackmap:
6628     visitStackmap(I);
6629     return;
6630   case Intrinsic::experimental_patchpoint_void:
6631   case Intrinsic::experimental_patchpoint_i64:
6632     visitPatchpoint(&I);
6633     return;
6634   case Intrinsic::experimental_gc_statepoint:
6635     LowerStatepoint(ImmutableStatepoint(&I));
6636     return;
6637   case Intrinsic::experimental_gc_result:
6638     visitGCResult(cast<GCResultInst>(I));
6639     return;
6640   case Intrinsic::experimental_gc_relocate:
6641     visitGCRelocate(cast<GCRelocateInst>(I));
6642     return;
6643   case Intrinsic::instrprof_increment:
6644     llvm_unreachable("instrprof failed to lower an increment");
6645   case Intrinsic::instrprof_value_profile:
6646     llvm_unreachable("instrprof failed to lower a value profiling call");
6647   case Intrinsic::localescape: {
6648     MachineFunction &MF = DAG.getMachineFunction();
6649     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6650 
6651     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6652     // is the same on all targets.
6653     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6654       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6655       if (isa<ConstantPointerNull>(Arg))
6656         continue; // Skip null pointers. They represent a hole in index space.
6657       AllocaInst *Slot = cast<AllocaInst>(Arg);
6658       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6659              "can only escape static allocas");
6660       int FI = FuncInfo.StaticAllocaMap[Slot];
6661       MCSymbol *FrameAllocSym =
6662           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6663               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6664       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6665               TII->get(TargetOpcode::LOCAL_ESCAPE))
6666           .addSym(FrameAllocSym)
6667           .addFrameIndex(FI);
6668     }
6669 
6670     return;
6671   }
6672 
6673   case Intrinsic::localrecover: {
6674     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6675     MachineFunction &MF = DAG.getMachineFunction();
6676     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6677 
6678     // Get the symbol that defines the frame offset.
6679     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6680     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6681     unsigned IdxVal =
6682         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6683     MCSymbol *FrameAllocSym =
6684         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6685             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6686 
6687     // Create a MCSymbol for the label to avoid any target lowering
6688     // that would make this PC relative.
6689     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6690     SDValue OffsetVal =
6691         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6692 
6693     // Add the offset to the FP.
6694     Value *FP = I.getArgOperand(1);
6695     SDValue FPVal = getValue(FP);
6696     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
6697     setValue(&I, Add);
6698 
6699     return;
6700   }
6701 
6702   case Intrinsic::eh_exceptionpointer:
6703   case Intrinsic::eh_exceptioncode: {
6704     // Get the exception pointer vreg, copy from it, and resize it to fit.
6705     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6706     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6707     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6708     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6709     SDValue N =
6710         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6711     if (Intrinsic == Intrinsic::eh_exceptioncode)
6712       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6713     setValue(&I, N);
6714     return;
6715   }
6716   case Intrinsic::xray_customevent: {
6717     // Here we want to make sure that the intrinsic behaves as if it has a
6718     // specific calling convention, and only for x86_64.
6719     // FIXME: Support other platforms later.
6720     const auto &Triple = DAG.getTarget().getTargetTriple();
6721     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6722       return;
6723 
6724     SDLoc DL = getCurSDLoc();
6725     SmallVector<SDValue, 8> Ops;
6726 
6727     // We want to say that we always want the arguments in registers.
6728     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6729     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6730     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6731     SDValue Chain = getRoot();
6732     Ops.push_back(LogEntryVal);
6733     Ops.push_back(StrSizeVal);
6734     Ops.push_back(Chain);
6735 
6736     // We need to enforce the calling convention for the callsite, so that
6737     // argument ordering is enforced correctly, and that register allocation can
6738     // see that some registers may be assumed clobbered and have to preserve
6739     // them across calls to the intrinsic.
6740     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6741                                            DL, NodeTys, Ops);
6742     SDValue patchableNode = SDValue(MN, 0);
6743     DAG.setRoot(patchableNode);
6744     setValue(&I, patchableNode);
6745     return;
6746   }
6747   case Intrinsic::xray_typedevent: {
6748     // Here we want to make sure that the intrinsic behaves as if it has a
6749     // specific calling convention, and only for x86_64.
6750     // FIXME: Support other platforms later.
6751     const auto &Triple = DAG.getTarget().getTargetTriple();
6752     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6753       return;
6754 
6755     SDLoc DL = getCurSDLoc();
6756     SmallVector<SDValue, 8> Ops;
6757 
6758     // We want to say that we always want the arguments in registers.
6759     // It's unclear to me how manipulating the selection DAG here forces callers
6760     // to provide arguments in registers instead of on the stack.
6761     SDValue LogTypeId = getValue(I.getArgOperand(0));
6762     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6763     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6764     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6765     SDValue Chain = getRoot();
6766     Ops.push_back(LogTypeId);
6767     Ops.push_back(LogEntryVal);
6768     Ops.push_back(StrSizeVal);
6769     Ops.push_back(Chain);
6770 
6771     // We need to enforce the calling convention for the callsite, so that
6772     // argument ordering is enforced correctly, and that register allocation can
6773     // see that some registers may be assumed clobbered and have to preserve
6774     // them across calls to the intrinsic.
6775     MachineSDNode *MN = DAG.getMachineNode(
6776         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6777     SDValue patchableNode = SDValue(MN, 0);
6778     DAG.setRoot(patchableNode);
6779     setValue(&I, patchableNode);
6780     return;
6781   }
6782   case Intrinsic::experimental_deoptimize:
6783     LowerDeoptimizeCall(&I);
6784     return;
6785 
6786   case Intrinsic::experimental_vector_reduce_v2_fadd:
6787   case Intrinsic::experimental_vector_reduce_v2_fmul:
6788   case Intrinsic::experimental_vector_reduce_add:
6789   case Intrinsic::experimental_vector_reduce_mul:
6790   case Intrinsic::experimental_vector_reduce_and:
6791   case Intrinsic::experimental_vector_reduce_or:
6792   case Intrinsic::experimental_vector_reduce_xor:
6793   case Intrinsic::experimental_vector_reduce_smax:
6794   case Intrinsic::experimental_vector_reduce_smin:
6795   case Intrinsic::experimental_vector_reduce_umax:
6796   case Intrinsic::experimental_vector_reduce_umin:
6797   case Intrinsic::experimental_vector_reduce_fmax:
6798   case Intrinsic::experimental_vector_reduce_fmin:
6799     visitVectorReduce(I, Intrinsic);
6800     return;
6801 
6802   case Intrinsic::icall_branch_funnel: {
6803     SmallVector<SDValue, 16> Ops;
6804     Ops.push_back(getValue(I.getArgOperand(0)));
6805 
6806     int64_t Offset;
6807     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6808         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6809     if (!Base)
6810       report_fatal_error(
6811           "llvm.icall.branch.funnel operand must be a GlobalValue");
6812     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6813 
6814     struct BranchFunnelTarget {
6815       int64_t Offset;
6816       SDValue Target;
6817     };
6818     SmallVector<BranchFunnelTarget, 8> Targets;
6819 
6820     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6821       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6822           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6823       if (ElemBase != Base)
6824         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6825                            "to the same GlobalValue");
6826 
6827       SDValue Val = getValue(I.getArgOperand(Op + 1));
6828       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6829       if (!GA)
6830         report_fatal_error(
6831             "llvm.icall.branch.funnel operand must be a GlobalValue");
6832       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6833                                      GA->getGlobal(), getCurSDLoc(),
6834                                      Val.getValueType(), GA->getOffset())});
6835     }
6836     llvm::sort(Targets,
6837                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6838                  return T1.Offset < T2.Offset;
6839                });
6840 
6841     for (auto &T : Targets) {
6842       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6843       Ops.push_back(T.Target);
6844     }
6845 
6846     Ops.push_back(DAG.getRoot()); // Chain
6847     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6848                                  getCurSDLoc(), MVT::Other, Ops),
6849               0);
6850     DAG.setRoot(N);
6851     setValue(&I, N);
6852     HasTailCall = true;
6853     return;
6854   }
6855 
6856   case Intrinsic::wasm_landingpad_index:
6857     // Information this intrinsic contained has been transferred to
6858     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6859     // delete it now.
6860     return;
6861 
6862   case Intrinsic::aarch64_settag:
6863   case Intrinsic::aarch64_settag_zero: {
6864     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6865     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
6866     SDValue Val = TSI.EmitTargetCodeForSetTag(
6867         DAG, getCurSDLoc(), getRoot(), getValue(I.getArgOperand(0)),
6868         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
6869         ZeroMemory);
6870     DAG.setRoot(Val);
6871     setValue(&I, Val);
6872     return;
6873   }
6874   case Intrinsic::ptrmask: {
6875     SDValue Ptr = getValue(I.getOperand(0));
6876     SDValue Const = getValue(I.getOperand(1));
6877 
6878     EVT DestVT =
6879         EVT(DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6880 
6881     setValue(&I, DAG.getNode(ISD::AND, getCurSDLoc(), DestVT, Ptr,
6882                              DAG.getZExtOrTrunc(Const, getCurSDLoc(), DestVT)));
6883     return;
6884   }
6885   }
6886 }
6887 
6888 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6889     const ConstrainedFPIntrinsic &FPI) {
6890   SDLoc sdl = getCurSDLoc();
6891 
6892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6893   SmallVector<EVT, 4> ValueVTs;
6894   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6895   ValueVTs.push_back(MVT::Other); // Out chain
6896 
6897   // We do not need to serialize constrained FP intrinsics against
6898   // each other or against (nonvolatile) loads, so they can be
6899   // chained like loads.
6900   SDValue Chain = DAG.getRoot();
6901   SmallVector<SDValue, 4> Opers;
6902   Opers.push_back(Chain);
6903   if (FPI.isUnaryOp()) {
6904     Opers.push_back(getValue(FPI.getArgOperand(0)));
6905   } else if (FPI.isTernaryOp()) {
6906     Opers.push_back(getValue(FPI.getArgOperand(0)));
6907     Opers.push_back(getValue(FPI.getArgOperand(1)));
6908     Opers.push_back(getValue(FPI.getArgOperand(2)));
6909   } else {
6910     Opers.push_back(getValue(FPI.getArgOperand(0)));
6911     Opers.push_back(getValue(FPI.getArgOperand(1)));
6912   }
6913 
6914   unsigned Opcode;
6915   switch (FPI.getIntrinsicID()) {
6916   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6917 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)                   \
6918   case Intrinsic::INTRINSIC:                                                   \
6919     Opcode = ISD::STRICT_##DAGN;                                               \
6920     break;
6921 #include "llvm/IR/ConstrainedOps.def"
6922   }
6923 
6924   // A few strict DAG nodes carry additional operands that are not
6925   // set up by the default code above.
6926   switch (Opcode) {
6927   default: break;
6928   case ISD::STRICT_FP_ROUND:
6929     Opers.push_back(
6930         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
6931     break;
6932   case ISD::STRICT_FSETCC:
6933   case ISD::STRICT_FSETCCS: {
6934     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
6935     Opers.push_back(DAG.getCondCode(getFCmpCondCode(FPCmp->getPredicate())));
6936     break;
6937   }
6938   }
6939 
6940   SDVTList VTs = DAG.getVTList(ValueVTs);
6941   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers);
6942 
6943   if (FPI.getExceptionBehavior() != fp::ExceptionBehavior::ebIgnore) {
6944     SDNodeFlags Flags;
6945     Flags.setFPExcept(true);
6946     Result->setFlags(Flags);
6947   }
6948 
6949   assert(Result.getNode()->getNumValues() == 2);
6950   // See above -- chain is handled like for loads here.
6951   SDValue OutChain = Result.getValue(1);
6952   PendingLoads.push_back(OutChain);
6953   SDValue FPResult = Result.getValue(0);
6954   setValue(&FPI, FPResult);
6955 }
6956 
6957 std::pair<SDValue, SDValue>
6958 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6959                                     const BasicBlock *EHPadBB) {
6960   MachineFunction &MF = DAG.getMachineFunction();
6961   MachineModuleInfo &MMI = MF.getMMI();
6962   MCSymbol *BeginLabel = nullptr;
6963 
6964   if (EHPadBB) {
6965     // Insert a label before the invoke call to mark the try range.  This can be
6966     // used to detect deletion of the invoke via the MachineModuleInfo.
6967     BeginLabel = MMI.getContext().createTempSymbol();
6968 
6969     // For SjLj, keep track of which landing pads go with which invokes
6970     // so as to maintain the ordering of pads in the LSDA.
6971     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6972     if (CallSiteIndex) {
6973       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6974       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6975 
6976       // Now that the call site is handled, stop tracking it.
6977       MMI.setCurrentCallSite(0);
6978     }
6979 
6980     // Both PendingLoads and PendingExports must be flushed here;
6981     // this call might not return.
6982     (void)getRoot();
6983     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6984 
6985     CLI.setChain(getRoot());
6986   }
6987   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6988   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6989 
6990   assert((CLI.IsTailCall || Result.second.getNode()) &&
6991          "Non-null chain expected with non-tail call!");
6992   assert((Result.second.getNode() || !Result.first.getNode()) &&
6993          "Null value expected with tail call!");
6994 
6995   if (!Result.second.getNode()) {
6996     // As a special case, a null chain means that a tail call has been emitted
6997     // and the DAG root is already updated.
6998     HasTailCall = true;
6999 
7000     // Since there's no actual continuation from this block, nothing can be
7001     // relying on us setting vregs for them.
7002     PendingExports.clear();
7003   } else {
7004     DAG.setRoot(Result.second);
7005   }
7006 
7007   if (EHPadBB) {
7008     // Insert a label at the end of the invoke call to mark the try range.  This
7009     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7010     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7011     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7012 
7013     // Inform MachineModuleInfo of range.
7014     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7015     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7016     // actually use outlined funclets and their LSDA info style.
7017     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7018       assert(CLI.CS);
7019       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7020       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7021                                 BeginLabel, EndLabel);
7022     } else if (!isScopedEHPersonality(Pers)) {
7023       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7024     }
7025   }
7026 
7027   return Result;
7028 }
7029 
7030 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7031                                       bool isTailCall,
7032                                       const BasicBlock *EHPadBB) {
7033   auto &DL = DAG.getDataLayout();
7034   FunctionType *FTy = CS.getFunctionType();
7035   Type *RetTy = CS.getType();
7036 
7037   TargetLowering::ArgListTy Args;
7038   Args.reserve(CS.arg_size());
7039 
7040   const Value *SwiftErrorVal = nullptr;
7041   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7042 
7043   // We can't tail call inside a function with a swifterror argument. Lowering
7044   // does not support this yet. It would have to move into the swifterror
7045   // register before the call.
7046   auto *Caller = CS.getInstruction()->getParent()->getParent();
7047   if (TLI.supportSwiftError() &&
7048       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7049     isTailCall = false;
7050 
7051   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7052        i != e; ++i) {
7053     TargetLowering::ArgListEntry Entry;
7054     const Value *V = *i;
7055 
7056     // Skip empty types
7057     if (V->getType()->isEmptyTy())
7058       continue;
7059 
7060     SDValue ArgNode = getValue(V);
7061     Entry.Node = ArgNode; Entry.Ty = V->getType();
7062 
7063     Entry.setAttributes(&CS, i - CS.arg_begin());
7064 
7065     // Use swifterror virtual register as input to the call.
7066     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7067       SwiftErrorVal = V;
7068       // We find the virtual register for the actual swifterror argument.
7069       // Instead of using the Value, we use the virtual register instead.
7070       Entry.Node = DAG.getRegister(
7071           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7072           EVT(TLI.getPointerTy(DL)));
7073     }
7074 
7075     Args.push_back(Entry);
7076 
7077     // If we have an explicit sret argument that is an Instruction, (i.e., it
7078     // might point to function-local memory), we can't meaningfully tail-call.
7079     if (Entry.IsSRet && isa<Instruction>(V))
7080       isTailCall = false;
7081   }
7082 
7083   // If call site has a cfguardtarget operand bundle, create and add an
7084   // additional ArgListEntry.
7085   if (auto Bundle = CS.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
7086     TargetLowering::ArgListEntry Entry;
7087     Value *V = Bundle->Inputs[0];
7088     SDValue ArgNode = getValue(V);
7089     Entry.Node = ArgNode;
7090     Entry.Ty = V->getType();
7091     Entry.IsCFGuardTarget = true;
7092     Args.push_back(Entry);
7093   }
7094 
7095   // Check if target-independent constraints permit a tail call here.
7096   // Target-dependent constraints are checked within TLI->LowerCallTo.
7097   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7098     isTailCall = false;
7099 
7100   // Disable tail calls if there is an swifterror argument. Targets have not
7101   // been updated to support tail calls.
7102   if (TLI.supportSwiftError() && SwiftErrorVal)
7103     isTailCall = false;
7104 
7105   TargetLowering::CallLoweringInfo CLI(DAG);
7106   CLI.setDebugLoc(getCurSDLoc())
7107       .setChain(getRoot())
7108       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7109       .setTailCall(isTailCall)
7110       .setConvergent(CS.isConvergent());
7111   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7112 
7113   if (Result.first.getNode()) {
7114     const Instruction *Inst = CS.getInstruction();
7115     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7116     setValue(Inst, Result.first);
7117   }
7118 
7119   // The last element of CLI.InVals has the SDValue for swifterror return.
7120   // Here we copy it to a virtual register and update SwiftErrorMap for
7121   // book-keeping.
7122   if (SwiftErrorVal && TLI.supportSwiftError()) {
7123     // Get the last element of InVals.
7124     SDValue Src = CLI.InVals.back();
7125     Register VReg = SwiftError.getOrCreateVRegDefAt(
7126         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7127     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7128     DAG.setRoot(CopyNode);
7129   }
7130 }
7131 
7132 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7133                              SelectionDAGBuilder &Builder) {
7134   // Check to see if this load can be trivially constant folded, e.g. if the
7135   // input is from a string literal.
7136   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7137     // Cast pointer to the type we really want to load.
7138     Type *LoadTy =
7139         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7140     if (LoadVT.isVector())
7141       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7142 
7143     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7144                                          PointerType::getUnqual(LoadTy));
7145 
7146     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7147             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7148       return Builder.getValue(LoadCst);
7149   }
7150 
7151   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7152   // still constant memory, the input chain can be the entry node.
7153   SDValue Root;
7154   bool ConstantMemory = false;
7155 
7156   // Do not serialize (non-volatile) loads of constant memory with anything.
7157   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7158     Root = Builder.DAG.getEntryNode();
7159     ConstantMemory = true;
7160   } else {
7161     // Do not serialize non-volatile loads against each other.
7162     Root = Builder.DAG.getRoot();
7163   }
7164 
7165   SDValue Ptr = Builder.getValue(PtrVal);
7166   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7167                                         Ptr, MachinePointerInfo(PtrVal),
7168                                         /* Alignment = */ 1);
7169 
7170   if (!ConstantMemory)
7171     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7172   return LoadVal;
7173 }
7174 
7175 /// Record the value for an instruction that produces an integer result,
7176 /// converting the type where necessary.
7177 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7178                                                   SDValue Value,
7179                                                   bool IsSigned) {
7180   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7181                                                     I.getType(), true);
7182   if (IsSigned)
7183     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7184   else
7185     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7186   setValue(&I, Value);
7187 }
7188 
7189 /// See if we can lower a memcmp call into an optimized form. If so, return
7190 /// true and lower it. Otherwise return false, and it will be lowered like a
7191 /// normal call.
7192 /// The caller already checked that \p I calls the appropriate LibFunc with a
7193 /// correct prototype.
7194 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7195   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7196   const Value *Size = I.getArgOperand(2);
7197   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7198   if (CSize && CSize->getZExtValue() == 0) {
7199     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7200                                                           I.getType(), true);
7201     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7202     return true;
7203   }
7204 
7205   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7206   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7207       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7208       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7209   if (Res.first.getNode()) {
7210     processIntegerCallValue(I, Res.first, true);
7211     PendingLoads.push_back(Res.second);
7212     return true;
7213   }
7214 
7215   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7216   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7217   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7218     return false;
7219 
7220   // If the target has a fast compare for the given size, it will return a
7221   // preferred load type for that size. Require that the load VT is legal and
7222   // that the target supports unaligned loads of that type. Otherwise, return
7223   // INVALID.
7224   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7225     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7226     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7227     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7228       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7229       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7230       // TODO: Check alignment of src and dest ptrs.
7231       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7232       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7233       if (!TLI.isTypeLegal(LVT) ||
7234           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7235           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7236         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7237     }
7238 
7239     return LVT;
7240   };
7241 
7242   // This turns into unaligned loads. We only do this if the target natively
7243   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7244   // we'll only produce a small number of byte loads.
7245   MVT LoadVT;
7246   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7247   switch (NumBitsToCompare) {
7248   default:
7249     return false;
7250   case 16:
7251     LoadVT = MVT::i16;
7252     break;
7253   case 32:
7254     LoadVT = MVT::i32;
7255     break;
7256   case 64:
7257   case 128:
7258   case 256:
7259     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7260     break;
7261   }
7262 
7263   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7264     return false;
7265 
7266   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7267   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7268 
7269   // Bitcast to a wide integer type if the loads are vectors.
7270   if (LoadVT.isVector()) {
7271     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7272     LoadL = DAG.getBitcast(CmpVT, LoadL);
7273     LoadR = DAG.getBitcast(CmpVT, LoadR);
7274   }
7275 
7276   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7277   processIntegerCallValue(I, Cmp, false);
7278   return true;
7279 }
7280 
7281 /// See if we can lower a memchr call into an optimized form. If so, return
7282 /// true and lower it. Otherwise return false, and it will be lowered like a
7283 /// normal call.
7284 /// The caller already checked that \p I calls the appropriate LibFunc with a
7285 /// correct prototype.
7286 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7287   const Value *Src = I.getArgOperand(0);
7288   const Value *Char = I.getArgOperand(1);
7289   const Value *Length = I.getArgOperand(2);
7290 
7291   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7292   std::pair<SDValue, SDValue> Res =
7293     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7294                                 getValue(Src), getValue(Char), getValue(Length),
7295                                 MachinePointerInfo(Src));
7296   if (Res.first.getNode()) {
7297     setValue(&I, Res.first);
7298     PendingLoads.push_back(Res.second);
7299     return true;
7300   }
7301 
7302   return false;
7303 }
7304 
7305 /// See if we can lower a mempcpy call into an optimized form. If so, return
7306 /// true and lower it. Otherwise return false, and it will be lowered like a
7307 /// normal call.
7308 /// The caller already checked that \p I calls the appropriate LibFunc with a
7309 /// correct prototype.
7310 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7311   SDValue Dst = getValue(I.getArgOperand(0));
7312   SDValue Src = getValue(I.getArgOperand(1));
7313   SDValue Size = getValue(I.getArgOperand(2));
7314 
7315   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7316   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7317   unsigned Align = std::min(DstAlign, SrcAlign);
7318   if (Align == 0) // Alignment of one or both could not be inferred.
7319     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7320 
7321   bool isVol = false;
7322   SDLoc sdl = getCurSDLoc();
7323 
7324   // In the mempcpy context we need to pass in a false value for isTailCall
7325   // because the return pointer needs to be adjusted by the size of
7326   // the copied memory.
7327   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7328                              false, /*isTailCall=*/false,
7329                              MachinePointerInfo(I.getArgOperand(0)),
7330                              MachinePointerInfo(I.getArgOperand(1)));
7331   assert(MC.getNode() != nullptr &&
7332          "** memcpy should not be lowered as TailCall in mempcpy context **");
7333   DAG.setRoot(MC);
7334 
7335   // Check if Size needs to be truncated or extended.
7336   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7337 
7338   // Adjust return pointer to point just past the last dst byte.
7339   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7340                                     Dst, Size);
7341   setValue(&I, DstPlusSize);
7342   return true;
7343 }
7344 
7345 /// See if we can lower a strcpy call into an optimized form.  If so, return
7346 /// true and lower it, otherwise return false and it will be lowered like a
7347 /// normal call.
7348 /// The caller already checked that \p I calls the appropriate LibFunc with a
7349 /// correct prototype.
7350 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7351   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7352 
7353   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7354   std::pair<SDValue, SDValue> Res =
7355     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7356                                 getValue(Arg0), getValue(Arg1),
7357                                 MachinePointerInfo(Arg0),
7358                                 MachinePointerInfo(Arg1), isStpcpy);
7359   if (Res.first.getNode()) {
7360     setValue(&I, Res.first);
7361     DAG.setRoot(Res.second);
7362     return true;
7363   }
7364 
7365   return false;
7366 }
7367 
7368 /// See if we can lower a strcmp call into an optimized form.  If so, return
7369 /// true and lower it, otherwise return false and it will be lowered like a
7370 /// normal call.
7371 /// The caller already checked that \p I calls the appropriate LibFunc with a
7372 /// correct prototype.
7373 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7374   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7375 
7376   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7377   std::pair<SDValue, SDValue> Res =
7378     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7379                                 getValue(Arg0), getValue(Arg1),
7380                                 MachinePointerInfo(Arg0),
7381                                 MachinePointerInfo(Arg1));
7382   if (Res.first.getNode()) {
7383     processIntegerCallValue(I, Res.first, true);
7384     PendingLoads.push_back(Res.second);
7385     return true;
7386   }
7387 
7388   return false;
7389 }
7390 
7391 /// See if we can lower a strlen call into an optimized form.  If so, return
7392 /// true and lower it, otherwise return false and it will be lowered like a
7393 /// normal call.
7394 /// The caller already checked that \p I calls the appropriate LibFunc with a
7395 /// correct prototype.
7396 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7397   const Value *Arg0 = I.getArgOperand(0);
7398 
7399   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7400   std::pair<SDValue, SDValue> Res =
7401     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7402                                 getValue(Arg0), MachinePointerInfo(Arg0));
7403   if (Res.first.getNode()) {
7404     processIntegerCallValue(I, Res.first, false);
7405     PendingLoads.push_back(Res.second);
7406     return true;
7407   }
7408 
7409   return false;
7410 }
7411 
7412 /// See if we can lower a strnlen call into an optimized form.  If so, return
7413 /// true and lower it, otherwise return false and it will be lowered like a
7414 /// normal call.
7415 /// The caller already checked that \p I calls the appropriate LibFunc with a
7416 /// correct prototype.
7417 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7418   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7419 
7420   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7421   std::pair<SDValue, SDValue> Res =
7422     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7423                                  getValue(Arg0), getValue(Arg1),
7424                                  MachinePointerInfo(Arg0));
7425   if (Res.first.getNode()) {
7426     processIntegerCallValue(I, Res.first, false);
7427     PendingLoads.push_back(Res.second);
7428     return true;
7429   }
7430 
7431   return false;
7432 }
7433 
7434 /// See if we can lower a unary floating-point operation into an SDNode with
7435 /// the specified Opcode.  If so, return true and lower it, otherwise return
7436 /// false and it will be lowered like a normal call.
7437 /// The caller already checked that \p I calls the appropriate LibFunc with a
7438 /// correct prototype.
7439 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7440                                               unsigned Opcode) {
7441   // We already checked this call's prototype; verify it doesn't modify errno.
7442   if (!I.onlyReadsMemory())
7443     return false;
7444 
7445   SDValue Tmp = getValue(I.getArgOperand(0));
7446   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7447   return true;
7448 }
7449 
7450 /// See if we can lower a binary floating-point operation into an SDNode with
7451 /// the specified Opcode. If so, return true and lower it. Otherwise return
7452 /// false, and it will be lowered like a normal call.
7453 /// The caller already checked that \p I calls the appropriate LibFunc with a
7454 /// correct prototype.
7455 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7456                                                unsigned Opcode) {
7457   // We already checked this call's prototype; verify it doesn't modify errno.
7458   if (!I.onlyReadsMemory())
7459     return false;
7460 
7461   SDValue Tmp0 = getValue(I.getArgOperand(0));
7462   SDValue Tmp1 = getValue(I.getArgOperand(1));
7463   EVT VT = Tmp0.getValueType();
7464   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7465   return true;
7466 }
7467 
7468 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7469   // Handle inline assembly differently.
7470   if (isa<InlineAsm>(I.getCalledValue())) {
7471     visitInlineAsm(&I);
7472     return;
7473   }
7474 
7475   if (Function *F = I.getCalledFunction()) {
7476     if (F->isDeclaration()) {
7477       // Is this an LLVM intrinsic or a target-specific intrinsic?
7478       unsigned IID = F->getIntrinsicID();
7479       if (!IID)
7480         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7481           IID = II->getIntrinsicID(F);
7482 
7483       if (IID) {
7484         visitIntrinsicCall(I, IID);
7485         return;
7486       }
7487     }
7488 
7489     // Check for well-known libc/libm calls.  If the function is internal, it
7490     // can't be a library call.  Don't do the check if marked as nobuiltin for
7491     // some reason or the call site requires strict floating point semantics.
7492     LibFunc Func;
7493     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7494         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7495         LibInfo->hasOptimizedCodeGen(Func)) {
7496       switch (Func) {
7497       default: break;
7498       case LibFunc_copysign:
7499       case LibFunc_copysignf:
7500       case LibFunc_copysignl:
7501         // We already checked this call's prototype; verify it doesn't modify
7502         // errno.
7503         if (I.onlyReadsMemory()) {
7504           SDValue LHS = getValue(I.getArgOperand(0));
7505           SDValue RHS = getValue(I.getArgOperand(1));
7506           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7507                                    LHS.getValueType(), LHS, RHS));
7508           return;
7509         }
7510         break;
7511       case LibFunc_fabs:
7512       case LibFunc_fabsf:
7513       case LibFunc_fabsl:
7514         if (visitUnaryFloatCall(I, ISD::FABS))
7515           return;
7516         break;
7517       case LibFunc_fmin:
7518       case LibFunc_fminf:
7519       case LibFunc_fminl:
7520         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7521           return;
7522         break;
7523       case LibFunc_fmax:
7524       case LibFunc_fmaxf:
7525       case LibFunc_fmaxl:
7526         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7527           return;
7528         break;
7529       case LibFunc_sin:
7530       case LibFunc_sinf:
7531       case LibFunc_sinl:
7532         if (visitUnaryFloatCall(I, ISD::FSIN))
7533           return;
7534         break;
7535       case LibFunc_cos:
7536       case LibFunc_cosf:
7537       case LibFunc_cosl:
7538         if (visitUnaryFloatCall(I, ISD::FCOS))
7539           return;
7540         break;
7541       case LibFunc_sqrt:
7542       case LibFunc_sqrtf:
7543       case LibFunc_sqrtl:
7544       case LibFunc_sqrt_finite:
7545       case LibFunc_sqrtf_finite:
7546       case LibFunc_sqrtl_finite:
7547         if (visitUnaryFloatCall(I, ISD::FSQRT))
7548           return;
7549         break;
7550       case LibFunc_floor:
7551       case LibFunc_floorf:
7552       case LibFunc_floorl:
7553         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7554           return;
7555         break;
7556       case LibFunc_nearbyint:
7557       case LibFunc_nearbyintf:
7558       case LibFunc_nearbyintl:
7559         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7560           return;
7561         break;
7562       case LibFunc_ceil:
7563       case LibFunc_ceilf:
7564       case LibFunc_ceill:
7565         if (visitUnaryFloatCall(I, ISD::FCEIL))
7566           return;
7567         break;
7568       case LibFunc_rint:
7569       case LibFunc_rintf:
7570       case LibFunc_rintl:
7571         if (visitUnaryFloatCall(I, ISD::FRINT))
7572           return;
7573         break;
7574       case LibFunc_round:
7575       case LibFunc_roundf:
7576       case LibFunc_roundl:
7577         if (visitUnaryFloatCall(I, ISD::FROUND))
7578           return;
7579         break;
7580       case LibFunc_trunc:
7581       case LibFunc_truncf:
7582       case LibFunc_truncl:
7583         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7584           return;
7585         break;
7586       case LibFunc_log2:
7587       case LibFunc_log2f:
7588       case LibFunc_log2l:
7589         if (visitUnaryFloatCall(I, ISD::FLOG2))
7590           return;
7591         break;
7592       case LibFunc_exp2:
7593       case LibFunc_exp2f:
7594       case LibFunc_exp2l:
7595         if (visitUnaryFloatCall(I, ISD::FEXP2))
7596           return;
7597         break;
7598       case LibFunc_memcmp:
7599         if (visitMemCmpCall(I))
7600           return;
7601         break;
7602       case LibFunc_mempcpy:
7603         if (visitMemPCpyCall(I))
7604           return;
7605         break;
7606       case LibFunc_memchr:
7607         if (visitMemChrCall(I))
7608           return;
7609         break;
7610       case LibFunc_strcpy:
7611         if (visitStrCpyCall(I, false))
7612           return;
7613         break;
7614       case LibFunc_stpcpy:
7615         if (visitStrCpyCall(I, true))
7616           return;
7617         break;
7618       case LibFunc_strcmp:
7619         if (visitStrCmpCall(I))
7620           return;
7621         break;
7622       case LibFunc_strlen:
7623         if (visitStrLenCall(I))
7624           return;
7625         break;
7626       case LibFunc_strnlen:
7627         if (visitStrNLenCall(I))
7628           return;
7629         break;
7630       }
7631     }
7632   }
7633 
7634   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7635   // have to do anything here to lower funclet bundles.
7636   // CFGuardTarget bundles are lowered in LowerCallTo.
7637   assert(!I.hasOperandBundlesOtherThan({LLVMContext::OB_deopt,
7638                                         LLVMContext::OB_funclet,
7639                                         LLVMContext::OB_cfguardtarget}) &&
7640          "Cannot lower calls with arbitrary operand bundles!");
7641 
7642   SDValue Callee = getValue(I.getCalledValue());
7643 
7644   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7645     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7646   else
7647     // Check if we can potentially perform a tail call. More detailed checking
7648     // is be done within LowerCallTo, after more information about the call is
7649     // known.
7650     LowerCallTo(&I, Callee, I.isTailCall());
7651 }
7652 
7653 namespace {
7654 
7655 /// AsmOperandInfo - This contains information for each constraint that we are
7656 /// lowering.
7657 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7658 public:
7659   /// CallOperand - If this is the result output operand or a clobber
7660   /// this is null, otherwise it is the incoming operand to the CallInst.
7661   /// This gets modified as the asm is processed.
7662   SDValue CallOperand;
7663 
7664   /// AssignedRegs - If this is a register or register class operand, this
7665   /// contains the set of register corresponding to the operand.
7666   RegsForValue AssignedRegs;
7667 
7668   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7669     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7670   }
7671 
7672   /// Whether or not this operand accesses memory
7673   bool hasMemory(const TargetLowering &TLI) const {
7674     // Indirect operand accesses access memory.
7675     if (isIndirect)
7676       return true;
7677 
7678     for (const auto &Code : Codes)
7679       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7680         return true;
7681 
7682     return false;
7683   }
7684 
7685   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7686   /// corresponds to.  If there is no Value* for this operand, it returns
7687   /// MVT::Other.
7688   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7689                            const DataLayout &DL) const {
7690     if (!CallOperandVal) return MVT::Other;
7691 
7692     if (isa<BasicBlock>(CallOperandVal))
7693       return TLI.getPointerTy(DL);
7694 
7695     llvm::Type *OpTy = CallOperandVal->getType();
7696 
7697     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7698     // If this is an indirect operand, the operand is a pointer to the
7699     // accessed type.
7700     if (isIndirect) {
7701       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7702       if (!PtrTy)
7703         report_fatal_error("Indirect operand for inline asm not a pointer!");
7704       OpTy = PtrTy->getElementType();
7705     }
7706 
7707     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7708     if (StructType *STy = dyn_cast<StructType>(OpTy))
7709       if (STy->getNumElements() == 1)
7710         OpTy = STy->getElementType(0);
7711 
7712     // If OpTy is not a single value, it may be a struct/union that we
7713     // can tile with integers.
7714     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7715       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7716       switch (BitSize) {
7717       default: break;
7718       case 1:
7719       case 8:
7720       case 16:
7721       case 32:
7722       case 64:
7723       case 128:
7724         OpTy = IntegerType::get(Context, BitSize);
7725         break;
7726       }
7727     }
7728 
7729     return TLI.getValueType(DL, OpTy, true);
7730   }
7731 };
7732 
7733 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7734 
7735 } // end anonymous namespace
7736 
7737 /// Make sure that the output operand \p OpInfo and its corresponding input
7738 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7739 /// out).
7740 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7741                                SDISelAsmOperandInfo &MatchingOpInfo,
7742                                SelectionDAG &DAG) {
7743   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7744     return;
7745 
7746   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7747   const auto &TLI = DAG.getTargetLoweringInfo();
7748 
7749   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7750       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7751                                        OpInfo.ConstraintVT);
7752   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7753       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7754                                        MatchingOpInfo.ConstraintVT);
7755   if ((OpInfo.ConstraintVT.isInteger() !=
7756        MatchingOpInfo.ConstraintVT.isInteger()) ||
7757       (MatchRC.second != InputRC.second)) {
7758     // FIXME: error out in a more elegant fashion
7759     report_fatal_error("Unsupported asm: input constraint"
7760                        " with a matching output constraint of"
7761                        " incompatible type!");
7762   }
7763   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7764 }
7765 
7766 /// Get a direct memory input to behave well as an indirect operand.
7767 /// This may introduce stores, hence the need for a \p Chain.
7768 /// \return The (possibly updated) chain.
7769 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7770                                         SDISelAsmOperandInfo &OpInfo,
7771                                         SelectionDAG &DAG) {
7772   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7773 
7774   // If we don't have an indirect input, put it in the constpool if we can,
7775   // otherwise spill it to a stack slot.
7776   // TODO: This isn't quite right. We need to handle these according to
7777   // the addressing mode that the constraint wants. Also, this may take
7778   // an additional register for the computation and we don't want that
7779   // either.
7780 
7781   // If the operand is a float, integer, or vector constant, spill to a
7782   // constant pool entry to get its address.
7783   const Value *OpVal = OpInfo.CallOperandVal;
7784   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7785       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7786     OpInfo.CallOperand = DAG.getConstantPool(
7787         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7788     return Chain;
7789   }
7790 
7791   // Otherwise, create a stack slot and emit a store to it before the asm.
7792   Type *Ty = OpVal->getType();
7793   auto &DL = DAG.getDataLayout();
7794   uint64_t TySize = DL.getTypeAllocSize(Ty);
7795   unsigned Align = DL.getPrefTypeAlignment(Ty);
7796   MachineFunction &MF = DAG.getMachineFunction();
7797   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7798   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7799   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7800                             MachinePointerInfo::getFixedStack(MF, SSFI),
7801                             TLI.getMemValueType(DL, Ty));
7802   OpInfo.CallOperand = StackSlot;
7803 
7804   return Chain;
7805 }
7806 
7807 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7808 /// specified operand.  We prefer to assign virtual registers, to allow the
7809 /// register allocator to handle the assignment process.  However, if the asm
7810 /// uses features that we can't model on machineinstrs, we have SDISel do the
7811 /// allocation.  This produces generally horrible, but correct, code.
7812 ///
7813 ///   OpInfo describes the operand
7814 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7815 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7816                                  SDISelAsmOperandInfo &OpInfo,
7817                                  SDISelAsmOperandInfo &RefOpInfo) {
7818   LLVMContext &Context = *DAG.getContext();
7819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7820 
7821   MachineFunction &MF = DAG.getMachineFunction();
7822   SmallVector<unsigned, 4> Regs;
7823   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7824 
7825   // No work to do for memory operations.
7826   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7827     return;
7828 
7829   // If this is a constraint for a single physreg, or a constraint for a
7830   // register class, find it.
7831   unsigned AssignedReg;
7832   const TargetRegisterClass *RC;
7833   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7834       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7835   // RC is unset only on failure. Return immediately.
7836   if (!RC)
7837     return;
7838 
7839   // Get the actual register value type.  This is important, because the user
7840   // may have asked for (e.g.) the AX register in i32 type.  We need to
7841   // remember that AX is actually i16 to get the right extension.
7842   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7843 
7844   if (OpInfo.ConstraintVT != MVT::Other) {
7845     // If this is an FP operand in an integer register (or visa versa), or more
7846     // generally if the operand value disagrees with the register class we plan
7847     // to stick it in, fix the operand type.
7848     //
7849     // If this is an input value, the bitcast to the new type is done now.
7850     // Bitcast for output value is done at the end of visitInlineAsm().
7851     if ((OpInfo.Type == InlineAsm::isOutput ||
7852          OpInfo.Type == InlineAsm::isInput) &&
7853         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7854       // Try to convert to the first EVT that the reg class contains.  If the
7855       // types are identical size, use a bitcast to convert (e.g. two differing
7856       // vector types).  Note: output bitcast is done at the end of
7857       // visitInlineAsm().
7858       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7859         // Exclude indirect inputs while they are unsupported because the code
7860         // to perform the load is missing and thus OpInfo.CallOperand still
7861         // refers to the input address rather than the pointed-to value.
7862         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7863           OpInfo.CallOperand =
7864               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7865         OpInfo.ConstraintVT = RegVT;
7866         // If the operand is an FP value and we want it in integer registers,
7867         // use the corresponding integer type. This turns an f64 value into
7868         // i64, which can be passed with two i32 values on a 32-bit machine.
7869       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7870         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7871         if (OpInfo.Type == InlineAsm::isInput)
7872           OpInfo.CallOperand =
7873               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7874         OpInfo.ConstraintVT = VT;
7875       }
7876     }
7877   }
7878 
7879   // No need to allocate a matching input constraint since the constraint it's
7880   // matching to has already been allocated.
7881   if (OpInfo.isMatchingInputConstraint())
7882     return;
7883 
7884   EVT ValueVT = OpInfo.ConstraintVT;
7885   if (OpInfo.ConstraintVT == MVT::Other)
7886     ValueVT = RegVT;
7887 
7888   // Initialize NumRegs.
7889   unsigned NumRegs = 1;
7890   if (OpInfo.ConstraintVT != MVT::Other)
7891     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7892 
7893   // If this is a constraint for a specific physical register, like {r17},
7894   // assign it now.
7895 
7896   // If this associated to a specific register, initialize iterator to correct
7897   // place. If virtual, make sure we have enough registers
7898 
7899   // Initialize iterator if necessary
7900   TargetRegisterClass::iterator I = RC->begin();
7901   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7902 
7903   // Do not check for single registers.
7904   if (AssignedReg) {
7905       for (; *I != AssignedReg; ++I)
7906         assert(I != RC->end() && "AssignedReg should be member of RC");
7907   }
7908 
7909   for (; NumRegs; --NumRegs, ++I) {
7910     assert(I != RC->end() && "Ran out of registers to allocate!");
7911     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
7912     Regs.push_back(R);
7913   }
7914 
7915   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7916 }
7917 
7918 static unsigned
7919 findMatchingInlineAsmOperand(unsigned OperandNo,
7920                              const std::vector<SDValue> &AsmNodeOperands) {
7921   // Scan until we find the definition we already emitted of this operand.
7922   unsigned CurOp = InlineAsm::Op_FirstOperand;
7923   for (; OperandNo; --OperandNo) {
7924     // Advance to the next operand.
7925     unsigned OpFlag =
7926         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7927     assert((InlineAsm::isRegDefKind(OpFlag) ||
7928             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7929             InlineAsm::isMemKind(OpFlag)) &&
7930            "Skipped past definitions?");
7931     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7932   }
7933   return CurOp;
7934 }
7935 
7936 namespace {
7937 
7938 class ExtraFlags {
7939   unsigned Flags = 0;
7940 
7941 public:
7942   explicit ExtraFlags(ImmutableCallSite CS) {
7943     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7944     if (IA->hasSideEffects())
7945       Flags |= InlineAsm::Extra_HasSideEffects;
7946     if (IA->isAlignStack())
7947       Flags |= InlineAsm::Extra_IsAlignStack;
7948     if (CS.isConvergent())
7949       Flags |= InlineAsm::Extra_IsConvergent;
7950     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7951   }
7952 
7953   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7954     // Ideally, we would only check against memory constraints.  However, the
7955     // meaning of an Other constraint can be target-specific and we can't easily
7956     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7957     // for Other constraints as well.
7958     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7959         OpInfo.ConstraintType == TargetLowering::C_Other) {
7960       if (OpInfo.Type == InlineAsm::isInput)
7961         Flags |= InlineAsm::Extra_MayLoad;
7962       else if (OpInfo.Type == InlineAsm::isOutput)
7963         Flags |= InlineAsm::Extra_MayStore;
7964       else if (OpInfo.Type == InlineAsm::isClobber)
7965         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7966     }
7967   }
7968 
7969   unsigned get() const { return Flags; }
7970 };
7971 
7972 } // end anonymous namespace
7973 
7974 /// visitInlineAsm - Handle a call to an InlineAsm object.
7975 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7976   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7977 
7978   /// ConstraintOperands - Information about all of the constraints.
7979   SDISelAsmOperandInfoVector ConstraintOperands;
7980 
7981   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7982   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7983       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7984 
7985   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7986   // AsmDialect, MayLoad, MayStore).
7987   bool HasSideEffect = IA->hasSideEffects();
7988   ExtraFlags ExtraInfo(CS);
7989 
7990   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7991   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7992   for (auto &T : TargetConstraints) {
7993     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7994     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7995 
7996     // Compute the value type for each operand.
7997     if (OpInfo.Type == InlineAsm::isInput ||
7998         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7999       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
8000 
8001       // Process the call argument. BasicBlocks are labels, currently appearing
8002       // only in asm's.
8003       const Instruction *I = CS.getInstruction();
8004       if (isa<CallBrInst>(I) &&
8005           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
8006                           cast<CallBrInst>(I)->getNumIndirectDests())) {
8007         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
8008         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
8009         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8010       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8011         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8012       } else {
8013         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8014       }
8015 
8016       OpInfo.ConstraintVT =
8017           OpInfo
8018               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8019               .getSimpleVT();
8020     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8021       // The return value of the call is this value.  As such, there is no
8022       // corresponding argument.
8023       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8024       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8025         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8026             DAG.getDataLayout(), STy->getElementType(ResNo));
8027       } else {
8028         assert(ResNo == 0 && "Asm only has one result!");
8029         OpInfo.ConstraintVT =
8030             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8031       }
8032       ++ResNo;
8033     } else {
8034       OpInfo.ConstraintVT = MVT::Other;
8035     }
8036 
8037     if (!HasSideEffect)
8038       HasSideEffect = OpInfo.hasMemory(TLI);
8039 
8040     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8041     // FIXME: Could we compute this on OpInfo rather than T?
8042 
8043     // Compute the constraint code and ConstraintType to use.
8044     TLI.ComputeConstraintToUse(T, SDValue());
8045 
8046     if (T.ConstraintType == TargetLowering::C_Immediate &&
8047         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
8048       // We've delayed emitting a diagnostic like the "n" constraint because
8049       // inlining could cause an integer showing up.
8050       return emitInlineAsmError(
8051           CS, "constraint '" + Twine(T.ConstraintCode) + "' expects an "
8052                   "integer constant expression");
8053 
8054     ExtraInfo.update(T);
8055   }
8056 
8057 
8058   // We won't need to flush pending loads if this asm doesn't touch
8059   // memory and is nonvolatile.
8060   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8061 
8062   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8063   if (IsCallBr) {
8064     // If this is a callbr we need to flush pending exports since inlineasm_br
8065     // is a terminator. We need to do this before nodes are glued to
8066     // the inlineasm_br node.
8067     Chain = getControlRoot();
8068   }
8069 
8070   // Second pass over the constraints: compute which constraint option to use.
8071   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8072     // If this is an output operand with a matching input operand, look up the
8073     // matching input. If their types mismatch, e.g. one is an integer, the
8074     // other is floating point, or their sizes are different, flag it as an
8075     // error.
8076     if (OpInfo.hasMatchingInput()) {
8077       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8078       patchMatchingInput(OpInfo, Input, DAG);
8079     }
8080 
8081     // Compute the constraint code and ConstraintType to use.
8082     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8083 
8084     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8085         OpInfo.Type == InlineAsm::isClobber)
8086       continue;
8087 
8088     // If this is a memory input, and if the operand is not indirect, do what we
8089     // need to provide an address for the memory input.
8090     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8091         !OpInfo.isIndirect) {
8092       assert((OpInfo.isMultipleAlternative ||
8093               (OpInfo.Type == InlineAsm::isInput)) &&
8094              "Can only indirectify direct input operands!");
8095 
8096       // Memory operands really want the address of the value.
8097       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8098 
8099       // There is no longer a Value* corresponding to this operand.
8100       OpInfo.CallOperandVal = nullptr;
8101 
8102       // It is now an indirect operand.
8103       OpInfo.isIndirect = true;
8104     }
8105 
8106   }
8107 
8108   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8109   std::vector<SDValue> AsmNodeOperands;
8110   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8111   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8112       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8113 
8114   // If we have a !srcloc metadata node associated with it, we want to attach
8115   // this to the ultimately generated inline asm machineinstr.  To do this, we
8116   // pass in the third operand as this (potentially null) inline asm MDNode.
8117   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8118   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8119 
8120   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8121   // bits as operand 3.
8122   AsmNodeOperands.push_back(DAG.getTargetConstant(
8123       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8124 
8125   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8126   // this, assign virtual and physical registers for inputs and otput.
8127   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8128     // Assign Registers.
8129     SDISelAsmOperandInfo &RefOpInfo =
8130         OpInfo.isMatchingInputConstraint()
8131             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8132             : OpInfo;
8133     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8134 
8135     switch (OpInfo.Type) {
8136     case InlineAsm::isOutput:
8137       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8138           ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8139             OpInfo.ConstraintType == TargetLowering::C_Other) &&
8140            OpInfo.isIndirect)) {
8141         unsigned ConstraintID =
8142             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8143         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8144                "Failed to convert memory constraint code to constraint id.");
8145 
8146         // Add information to the INLINEASM node to know about this output.
8147         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8148         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8149         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8150                                                         MVT::i32));
8151         AsmNodeOperands.push_back(OpInfo.CallOperand);
8152         break;
8153       } else if (((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8154                    OpInfo.ConstraintType == TargetLowering::C_Other) &&
8155                   !OpInfo.isIndirect) ||
8156                  OpInfo.ConstraintType == TargetLowering::C_Register ||
8157                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8158         // Otherwise, this outputs to a register (directly for C_Register /
8159         // C_RegisterClass, and a target-defined fashion for
8160         // C_Immediate/C_Other). Find a register that we can use.
8161         if (OpInfo.AssignedRegs.Regs.empty()) {
8162           emitInlineAsmError(
8163               CS, "couldn't allocate output register for constraint '" +
8164                       Twine(OpInfo.ConstraintCode) + "'");
8165           return;
8166         }
8167 
8168         // Add information to the INLINEASM node to know that this register is
8169         // set.
8170         OpInfo.AssignedRegs.AddInlineAsmOperands(
8171             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8172                                   : InlineAsm::Kind_RegDef,
8173             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8174       }
8175       break;
8176 
8177     case InlineAsm::isInput: {
8178       SDValue InOperandVal = OpInfo.CallOperand;
8179 
8180       if (OpInfo.isMatchingInputConstraint()) {
8181         // If this is required to match an output register we have already set,
8182         // just use its register.
8183         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8184                                                   AsmNodeOperands);
8185         unsigned OpFlag =
8186           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8187         if (InlineAsm::isRegDefKind(OpFlag) ||
8188             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8189           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8190           if (OpInfo.isIndirect) {
8191             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8192             emitInlineAsmError(CS, "inline asm not supported yet:"
8193                                    " don't know how to handle tied "
8194                                    "indirect register inputs");
8195             return;
8196           }
8197 
8198           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8199           SmallVector<unsigned, 4> Regs;
8200 
8201           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8202             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8203             MachineRegisterInfo &RegInfo =
8204                 DAG.getMachineFunction().getRegInfo();
8205             for (unsigned i = 0; i != NumRegs; ++i)
8206               Regs.push_back(RegInfo.createVirtualRegister(RC));
8207           } else {
8208             emitInlineAsmError(CS, "inline asm error: This value type register "
8209                                    "class is not natively supported!");
8210             return;
8211           }
8212 
8213           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8214 
8215           SDLoc dl = getCurSDLoc();
8216           // Use the produced MatchedRegs object to
8217           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8218                                     CS.getInstruction());
8219           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8220                                            true, OpInfo.getMatchedOperand(), dl,
8221                                            DAG, AsmNodeOperands);
8222           break;
8223         }
8224 
8225         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8226         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8227                "Unexpected number of operands");
8228         // Add information to the INLINEASM node to know about this input.
8229         // See InlineAsm.h isUseOperandTiedToDef.
8230         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8231         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8232                                                     OpInfo.getMatchedOperand());
8233         AsmNodeOperands.push_back(DAG.getTargetConstant(
8234             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8235         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8236         break;
8237       }
8238 
8239       // Treat indirect 'X' constraint as memory.
8240       if ((OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8241            OpInfo.ConstraintType == TargetLowering::C_Other) &&
8242           OpInfo.isIndirect)
8243         OpInfo.ConstraintType = TargetLowering::C_Memory;
8244 
8245       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
8246           OpInfo.ConstraintType == TargetLowering::C_Other) {
8247         std::vector<SDValue> Ops;
8248         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8249                                           Ops, DAG);
8250         if (Ops.empty()) {
8251           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
8252             if (isa<ConstantSDNode>(InOperandVal)) {
8253               emitInlineAsmError(CS, "value out of range for constraint '" +
8254                                  Twine(OpInfo.ConstraintCode) + "'");
8255               return;
8256             }
8257 
8258           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8259                                      Twine(OpInfo.ConstraintCode) + "'");
8260           return;
8261         }
8262 
8263         // Add information to the INLINEASM node to know about this input.
8264         unsigned ResOpType =
8265           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8266         AsmNodeOperands.push_back(DAG.getTargetConstant(
8267             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8268         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8269         break;
8270       }
8271 
8272       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8273         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8274         assert(InOperandVal.getValueType() ==
8275                    TLI.getPointerTy(DAG.getDataLayout()) &&
8276                "Memory operands expect pointer values");
8277 
8278         unsigned ConstraintID =
8279             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8280         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8281                "Failed to convert memory constraint code to constraint id.");
8282 
8283         // Add information to the INLINEASM node to know about this input.
8284         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8285         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8286         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8287                                                         getCurSDLoc(),
8288                                                         MVT::i32));
8289         AsmNodeOperands.push_back(InOperandVal);
8290         break;
8291       }
8292 
8293       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8294               OpInfo.ConstraintType == TargetLowering::C_Register ||
8295               OpInfo.ConstraintType == TargetLowering::C_Immediate) &&
8296              "Unknown constraint type!");
8297 
8298       // TODO: Support this.
8299       if (OpInfo.isIndirect) {
8300         emitInlineAsmError(
8301             CS, "Don't know how to handle indirect register inputs yet "
8302                 "for constraint '" +
8303                     Twine(OpInfo.ConstraintCode) + "'");
8304         return;
8305       }
8306 
8307       // Copy the input into the appropriate registers.
8308       if (OpInfo.AssignedRegs.Regs.empty()) {
8309         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8310                                    Twine(OpInfo.ConstraintCode) + "'");
8311         return;
8312       }
8313 
8314       SDLoc dl = getCurSDLoc();
8315 
8316       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8317                                         Chain, &Flag, CS.getInstruction());
8318 
8319       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8320                                                dl, DAG, AsmNodeOperands);
8321       break;
8322     }
8323     case InlineAsm::isClobber:
8324       // Add the clobbered value to the operand list, so that the register
8325       // allocator is aware that the physreg got clobbered.
8326       if (!OpInfo.AssignedRegs.Regs.empty())
8327         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8328                                                  false, 0, getCurSDLoc(), DAG,
8329                                                  AsmNodeOperands);
8330       break;
8331     }
8332   }
8333 
8334   // Finish up input operands.  Set the input chain and add the flag last.
8335   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8336   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8337 
8338   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8339   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8340                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8341   Flag = Chain.getValue(1);
8342 
8343   // Do additional work to generate outputs.
8344 
8345   SmallVector<EVT, 1> ResultVTs;
8346   SmallVector<SDValue, 1> ResultValues;
8347   SmallVector<SDValue, 8> OutChains;
8348 
8349   llvm::Type *CSResultType = CS.getType();
8350   ArrayRef<Type *> ResultTypes;
8351   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8352     ResultTypes = StructResult->elements();
8353   else if (!CSResultType->isVoidTy())
8354     ResultTypes = makeArrayRef(CSResultType);
8355 
8356   auto CurResultType = ResultTypes.begin();
8357   auto handleRegAssign = [&](SDValue V) {
8358     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8359     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8360     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8361     ++CurResultType;
8362     // If the type of the inline asm call site return value is different but has
8363     // same size as the type of the asm output bitcast it.  One example of this
8364     // is for vectors with different width / number of elements.  This can
8365     // happen for register classes that can contain multiple different value
8366     // types.  The preg or vreg allocated may not have the same VT as was
8367     // expected.
8368     //
8369     // This can also happen for a return value that disagrees with the register
8370     // class it is put in, eg. a double in a general-purpose register on a
8371     // 32-bit machine.
8372     if (ResultVT != V.getValueType() &&
8373         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8374       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8375     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8376              V.getValueType().isInteger()) {
8377       // If a result value was tied to an input value, the computed result
8378       // may have a wider width than the expected result.  Extract the
8379       // relevant portion.
8380       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8381     }
8382     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8383     ResultVTs.push_back(ResultVT);
8384     ResultValues.push_back(V);
8385   };
8386 
8387   // Deal with output operands.
8388   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8389     if (OpInfo.Type == InlineAsm::isOutput) {
8390       SDValue Val;
8391       // Skip trivial output operands.
8392       if (OpInfo.AssignedRegs.Regs.empty())
8393         continue;
8394 
8395       switch (OpInfo.ConstraintType) {
8396       case TargetLowering::C_Register:
8397       case TargetLowering::C_RegisterClass:
8398         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8399             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8400         break;
8401       case TargetLowering::C_Immediate:
8402       case TargetLowering::C_Other:
8403         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8404                                               OpInfo, DAG);
8405         break;
8406       case TargetLowering::C_Memory:
8407         break; // Already handled.
8408       case TargetLowering::C_Unknown:
8409         assert(false && "Unexpected unknown constraint");
8410       }
8411 
8412       // Indirect output manifest as stores. Record output chains.
8413       if (OpInfo.isIndirect) {
8414         const Value *Ptr = OpInfo.CallOperandVal;
8415         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8416         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8417                                      MachinePointerInfo(Ptr));
8418         OutChains.push_back(Store);
8419       } else {
8420         // generate CopyFromRegs to associated registers.
8421         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8422         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8423           for (const SDValue &V : Val->op_values())
8424             handleRegAssign(V);
8425         } else
8426           handleRegAssign(Val);
8427       }
8428     }
8429   }
8430 
8431   // Set results.
8432   if (!ResultValues.empty()) {
8433     assert(CurResultType == ResultTypes.end() &&
8434            "Mismatch in number of ResultTypes");
8435     assert(ResultValues.size() == ResultTypes.size() &&
8436            "Mismatch in number of output operands in asm result");
8437 
8438     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8439                             DAG.getVTList(ResultVTs), ResultValues);
8440     setValue(CS.getInstruction(), V);
8441   }
8442 
8443   // Collect store chains.
8444   if (!OutChains.empty())
8445     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8446 
8447   // Only Update Root if inline assembly has a memory effect.
8448   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8449     DAG.setRoot(Chain);
8450 }
8451 
8452 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8453                                              const Twine &Message) {
8454   LLVMContext &Ctx = *DAG.getContext();
8455   Ctx.emitError(CS.getInstruction(), Message);
8456 
8457   // Make sure we leave the DAG in a valid state
8458   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8459   SmallVector<EVT, 1> ValueVTs;
8460   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8461 
8462   if (ValueVTs.empty())
8463     return;
8464 
8465   SmallVector<SDValue, 1> Ops;
8466   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8467     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8468 
8469   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8470 }
8471 
8472 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8473   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8474                           MVT::Other, getRoot(),
8475                           getValue(I.getArgOperand(0)),
8476                           DAG.getSrcValue(I.getArgOperand(0))));
8477 }
8478 
8479 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8480   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8481   const DataLayout &DL = DAG.getDataLayout();
8482   SDValue V = DAG.getVAArg(
8483       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8484       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8485       DL.getABITypeAlignment(I.getType()));
8486   DAG.setRoot(V.getValue(1));
8487 
8488   if (I.getType()->isPointerTy())
8489     V = DAG.getPtrExtOrTrunc(
8490         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8491   setValue(&I, V);
8492 }
8493 
8494 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8495   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8496                           MVT::Other, getRoot(),
8497                           getValue(I.getArgOperand(0)),
8498                           DAG.getSrcValue(I.getArgOperand(0))));
8499 }
8500 
8501 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8502   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8503                           MVT::Other, getRoot(),
8504                           getValue(I.getArgOperand(0)),
8505                           getValue(I.getArgOperand(1)),
8506                           DAG.getSrcValue(I.getArgOperand(0)),
8507                           DAG.getSrcValue(I.getArgOperand(1))));
8508 }
8509 
8510 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8511                                                     const Instruction &I,
8512                                                     SDValue Op) {
8513   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8514   if (!Range)
8515     return Op;
8516 
8517   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8518   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8519     return Op;
8520 
8521   APInt Lo = CR.getUnsignedMin();
8522   if (!Lo.isMinValue())
8523     return Op;
8524 
8525   APInt Hi = CR.getUnsignedMax();
8526   unsigned Bits = std::max(Hi.getActiveBits(),
8527                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8528 
8529   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8530 
8531   SDLoc SL = getCurSDLoc();
8532 
8533   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8534                              DAG.getValueType(SmallVT));
8535   unsigned NumVals = Op.getNode()->getNumValues();
8536   if (NumVals == 1)
8537     return ZExt;
8538 
8539   SmallVector<SDValue, 4> Ops;
8540 
8541   Ops.push_back(ZExt);
8542   for (unsigned I = 1; I != NumVals; ++I)
8543     Ops.push_back(Op.getValue(I));
8544 
8545   return DAG.getMergeValues(Ops, SL);
8546 }
8547 
8548 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8549 /// the call being lowered.
8550 ///
8551 /// This is a helper for lowering intrinsics that follow a target calling
8552 /// convention or require stack pointer adjustment. Only a subset of the
8553 /// intrinsic's operands need to participate in the calling convention.
8554 void SelectionDAGBuilder::populateCallLoweringInfo(
8555     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8556     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8557     bool IsPatchPoint) {
8558   TargetLowering::ArgListTy Args;
8559   Args.reserve(NumArgs);
8560 
8561   // Populate the argument list.
8562   // Attributes for args start at offset 1, after the return attribute.
8563   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8564        ArgI != ArgE; ++ArgI) {
8565     const Value *V = Call->getOperand(ArgI);
8566 
8567     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8568 
8569     TargetLowering::ArgListEntry Entry;
8570     Entry.Node = getValue(V);
8571     Entry.Ty = V->getType();
8572     Entry.setAttributes(Call, ArgI);
8573     Args.push_back(Entry);
8574   }
8575 
8576   CLI.setDebugLoc(getCurSDLoc())
8577       .setChain(getRoot())
8578       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8579       .setDiscardResult(Call->use_empty())
8580       .setIsPatchPoint(IsPatchPoint);
8581 }
8582 
8583 /// Add a stack map intrinsic call's live variable operands to a stackmap
8584 /// or patchpoint target node's operand list.
8585 ///
8586 /// Constants are converted to TargetConstants purely as an optimization to
8587 /// avoid constant materialization and register allocation.
8588 ///
8589 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8590 /// generate addess computation nodes, and so FinalizeISel can convert the
8591 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8592 /// address materialization and register allocation, but may also be required
8593 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8594 /// alloca in the entry block, then the runtime may assume that the alloca's
8595 /// StackMap location can be read immediately after compilation and that the
8596 /// location is valid at any point during execution (this is similar to the
8597 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8598 /// only available in a register, then the runtime would need to trap when
8599 /// execution reaches the StackMap in order to read the alloca's location.
8600 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8601                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8602                                 SelectionDAGBuilder &Builder) {
8603   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8604     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8605     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8606       Ops.push_back(
8607         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8608       Ops.push_back(
8609         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8610     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8611       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8612       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8613           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8614     } else
8615       Ops.push_back(OpVal);
8616   }
8617 }
8618 
8619 /// Lower llvm.experimental.stackmap directly to its target opcode.
8620 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8621   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8622   //                                  [live variables...])
8623 
8624   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8625 
8626   SDValue Chain, InFlag, Callee, NullPtr;
8627   SmallVector<SDValue, 32> Ops;
8628 
8629   SDLoc DL = getCurSDLoc();
8630   Callee = getValue(CI.getCalledValue());
8631   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8632 
8633   // The stackmap intrinsic only records the live variables (the arguments
8634   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8635   // intrinsic, this won't be lowered to a function call. This means we don't
8636   // have to worry about calling conventions and target specific lowering code.
8637   // Instead we perform the call lowering right here.
8638   //
8639   // chain, flag = CALLSEQ_START(chain, 0, 0)
8640   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8641   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8642   //
8643   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8644   InFlag = Chain.getValue(1);
8645 
8646   // Add the <id> and <numBytes> constants.
8647   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8648   Ops.push_back(DAG.getTargetConstant(
8649                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8650   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8651   Ops.push_back(DAG.getTargetConstant(
8652                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8653                   MVT::i32));
8654 
8655   // Push live variables for the stack map.
8656   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8657 
8658   // We are not pushing any register mask info here on the operands list,
8659   // because the stackmap doesn't clobber anything.
8660 
8661   // Push the chain and the glue flag.
8662   Ops.push_back(Chain);
8663   Ops.push_back(InFlag);
8664 
8665   // Create the STACKMAP node.
8666   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8667   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8668   Chain = SDValue(SM, 0);
8669   InFlag = Chain.getValue(1);
8670 
8671   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8672 
8673   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8674 
8675   // Set the root to the target-lowered call chain.
8676   DAG.setRoot(Chain);
8677 
8678   // Inform the Frame Information that we have a stackmap in this function.
8679   FuncInfo.MF->getFrameInfo().setHasStackMap();
8680 }
8681 
8682 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8683 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8684                                           const BasicBlock *EHPadBB) {
8685   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8686   //                                                 i32 <numBytes>,
8687   //                                                 i8* <target>,
8688   //                                                 i32 <numArgs>,
8689   //                                                 [Args...],
8690   //                                                 [live variables...])
8691 
8692   CallingConv::ID CC = CS.getCallingConv();
8693   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8694   bool HasDef = !CS->getType()->isVoidTy();
8695   SDLoc dl = getCurSDLoc();
8696   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8697 
8698   // Handle immediate and symbolic callees.
8699   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8700     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8701                                    /*isTarget=*/true);
8702   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8703     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8704                                          SDLoc(SymbolicCallee),
8705                                          SymbolicCallee->getValueType(0));
8706 
8707   // Get the real number of arguments participating in the call <numArgs>
8708   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8709   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8710 
8711   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8712   // Intrinsics include all meta-operands up to but not including CC.
8713   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8714   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8715          "Not enough arguments provided to the patchpoint intrinsic");
8716 
8717   // For AnyRegCC the arguments are lowered later on manually.
8718   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8719   Type *ReturnTy =
8720     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8721 
8722   TargetLowering::CallLoweringInfo CLI(DAG);
8723   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8724                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8725   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8726 
8727   SDNode *CallEnd = Result.second.getNode();
8728   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8729     CallEnd = CallEnd->getOperand(0).getNode();
8730 
8731   /// Get a call instruction from the call sequence chain.
8732   /// Tail calls are not allowed.
8733   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8734          "Expected a callseq node.");
8735   SDNode *Call = CallEnd->getOperand(0).getNode();
8736   bool HasGlue = Call->getGluedNode();
8737 
8738   // Replace the target specific call node with the patchable intrinsic.
8739   SmallVector<SDValue, 8> Ops;
8740 
8741   // Add the <id> and <numBytes> constants.
8742   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8743   Ops.push_back(DAG.getTargetConstant(
8744                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8745   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8746   Ops.push_back(DAG.getTargetConstant(
8747                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8748                   MVT::i32));
8749 
8750   // Add the callee.
8751   Ops.push_back(Callee);
8752 
8753   // Adjust <numArgs> to account for any arguments that have been passed on the
8754   // stack instead.
8755   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8756   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8757   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8758   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8759 
8760   // Add the calling convention
8761   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8762 
8763   // Add the arguments we omitted previously. The register allocator should
8764   // place these in any free register.
8765   if (IsAnyRegCC)
8766     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8767       Ops.push_back(getValue(CS.getArgument(i)));
8768 
8769   // Push the arguments from the call instruction up to the register mask.
8770   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8771   Ops.append(Call->op_begin() + 2, e);
8772 
8773   // Push live variables for the stack map.
8774   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8775 
8776   // Push the register mask info.
8777   if (HasGlue)
8778     Ops.push_back(*(Call->op_end()-2));
8779   else
8780     Ops.push_back(*(Call->op_end()-1));
8781 
8782   // Push the chain (this is originally the first operand of the call, but
8783   // becomes now the last or second to last operand).
8784   Ops.push_back(*(Call->op_begin()));
8785 
8786   // Push the glue flag (last operand).
8787   if (HasGlue)
8788     Ops.push_back(*(Call->op_end()-1));
8789 
8790   SDVTList NodeTys;
8791   if (IsAnyRegCC && HasDef) {
8792     // Create the return types based on the intrinsic definition
8793     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8794     SmallVector<EVT, 3> ValueVTs;
8795     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8796     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8797 
8798     // There is always a chain and a glue type at the end
8799     ValueVTs.push_back(MVT::Other);
8800     ValueVTs.push_back(MVT::Glue);
8801     NodeTys = DAG.getVTList(ValueVTs);
8802   } else
8803     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8804 
8805   // Replace the target specific call node with a PATCHPOINT node.
8806   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8807                                          dl, NodeTys, Ops);
8808 
8809   // Update the NodeMap.
8810   if (HasDef) {
8811     if (IsAnyRegCC)
8812       setValue(CS.getInstruction(), SDValue(MN, 0));
8813     else
8814       setValue(CS.getInstruction(), Result.first);
8815   }
8816 
8817   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8818   // call sequence. Furthermore the location of the chain and glue can change
8819   // when the AnyReg calling convention is used and the intrinsic returns a
8820   // value.
8821   if (IsAnyRegCC && HasDef) {
8822     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8823     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8824     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8825   } else
8826     DAG.ReplaceAllUsesWith(Call, MN);
8827   DAG.DeleteNode(Call);
8828 
8829   // Inform the Frame Information that we have a patchpoint in this function.
8830   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8831 }
8832 
8833 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8834                                             unsigned Intrinsic) {
8835   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8836   SDValue Op1 = getValue(I.getArgOperand(0));
8837   SDValue Op2;
8838   if (I.getNumArgOperands() > 1)
8839     Op2 = getValue(I.getArgOperand(1));
8840   SDLoc dl = getCurSDLoc();
8841   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8842   SDValue Res;
8843   FastMathFlags FMF;
8844   if (isa<FPMathOperator>(I))
8845     FMF = I.getFastMathFlags();
8846 
8847   switch (Intrinsic) {
8848   case Intrinsic::experimental_vector_reduce_v2_fadd:
8849     if (FMF.allowReassoc())
8850       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
8851                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2));
8852     else
8853       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8854     break;
8855   case Intrinsic::experimental_vector_reduce_v2_fmul:
8856     if (FMF.allowReassoc())
8857       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
8858                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2));
8859     else
8860       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8861     break;
8862   case Intrinsic::experimental_vector_reduce_add:
8863     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8864     break;
8865   case Intrinsic::experimental_vector_reduce_mul:
8866     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8867     break;
8868   case Intrinsic::experimental_vector_reduce_and:
8869     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8870     break;
8871   case Intrinsic::experimental_vector_reduce_or:
8872     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8873     break;
8874   case Intrinsic::experimental_vector_reduce_xor:
8875     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8876     break;
8877   case Intrinsic::experimental_vector_reduce_smax:
8878     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8879     break;
8880   case Intrinsic::experimental_vector_reduce_smin:
8881     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8882     break;
8883   case Intrinsic::experimental_vector_reduce_umax:
8884     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8885     break;
8886   case Intrinsic::experimental_vector_reduce_umin:
8887     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8888     break;
8889   case Intrinsic::experimental_vector_reduce_fmax:
8890     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8891     break;
8892   case Intrinsic::experimental_vector_reduce_fmin:
8893     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8894     break;
8895   default:
8896     llvm_unreachable("Unhandled vector reduce intrinsic");
8897   }
8898   setValue(&I, Res);
8899 }
8900 
8901 /// Returns an AttributeList representing the attributes applied to the return
8902 /// value of the given call.
8903 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8904   SmallVector<Attribute::AttrKind, 2> Attrs;
8905   if (CLI.RetSExt)
8906     Attrs.push_back(Attribute::SExt);
8907   if (CLI.RetZExt)
8908     Attrs.push_back(Attribute::ZExt);
8909   if (CLI.IsInReg)
8910     Attrs.push_back(Attribute::InReg);
8911 
8912   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8913                             Attrs);
8914 }
8915 
8916 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8917 /// implementation, which just calls LowerCall.
8918 /// FIXME: When all targets are
8919 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8920 std::pair<SDValue, SDValue>
8921 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8922   // Handle the incoming return values from the call.
8923   CLI.Ins.clear();
8924   Type *OrigRetTy = CLI.RetTy;
8925   SmallVector<EVT, 4> RetTys;
8926   SmallVector<uint64_t, 4> Offsets;
8927   auto &DL = CLI.DAG.getDataLayout();
8928   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8929 
8930   if (CLI.IsPostTypeLegalization) {
8931     // If we are lowering a libcall after legalization, split the return type.
8932     SmallVector<EVT, 4> OldRetTys;
8933     SmallVector<uint64_t, 4> OldOffsets;
8934     RetTys.swap(OldRetTys);
8935     Offsets.swap(OldOffsets);
8936 
8937     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8938       EVT RetVT = OldRetTys[i];
8939       uint64_t Offset = OldOffsets[i];
8940       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8941       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8942       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8943       RetTys.append(NumRegs, RegisterVT);
8944       for (unsigned j = 0; j != NumRegs; ++j)
8945         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8946     }
8947   }
8948 
8949   SmallVector<ISD::OutputArg, 4> Outs;
8950   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8951 
8952   bool CanLowerReturn =
8953       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8954                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8955 
8956   SDValue DemoteStackSlot;
8957   int DemoteStackIdx = -100;
8958   if (!CanLowerReturn) {
8959     // FIXME: equivalent assert?
8960     // assert(!CS.hasInAllocaArgument() &&
8961     //        "sret demotion is incompatible with inalloca");
8962     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8963     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8964     MachineFunction &MF = CLI.DAG.getMachineFunction();
8965     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8966     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8967                                               DL.getAllocaAddrSpace());
8968 
8969     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8970     ArgListEntry Entry;
8971     Entry.Node = DemoteStackSlot;
8972     Entry.Ty = StackSlotPtrType;
8973     Entry.IsSExt = false;
8974     Entry.IsZExt = false;
8975     Entry.IsInReg = false;
8976     Entry.IsSRet = true;
8977     Entry.IsNest = false;
8978     Entry.IsByVal = false;
8979     Entry.IsReturned = false;
8980     Entry.IsSwiftSelf = false;
8981     Entry.IsSwiftError = false;
8982     Entry.IsCFGuardTarget = false;
8983     Entry.Alignment = Align;
8984     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8985     CLI.NumFixedArgs += 1;
8986     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8987 
8988     // sret demotion isn't compatible with tail-calls, since the sret argument
8989     // points into the callers stack frame.
8990     CLI.IsTailCall = false;
8991   } else {
8992     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8993         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
8994     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8995       ISD::ArgFlagsTy Flags;
8996       if (NeedsRegBlock) {
8997         Flags.setInConsecutiveRegs();
8998         if (I == RetTys.size() - 1)
8999           Flags.setInConsecutiveRegsLast();
9000       }
9001       EVT VT = RetTys[I];
9002       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9003                                                      CLI.CallConv, VT);
9004       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9005                                                        CLI.CallConv, VT);
9006       for (unsigned i = 0; i != NumRegs; ++i) {
9007         ISD::InputArg MyFlags;
9008         MyFlags.Flags = Flags;
9009         MyFlags.VT = RegisterVT;
9010         MyFlags.ArgVT = VT;
9011         MyFlags.Used = CLI.IsReturnValueUsed;
9012         if (CLI.RetTy->isPointerTy()) {
9013           MyFlags.Flags.setPointer();
9014           MyFlags.Flags.setPointerAddrSpace(
9015               cast<PointerType>(CLI.RetTy)->getAddressSpace());
9016         }
9017         if (CLI.RetSExt)
9018           MyFlags.Flags.setSExt();
9019         if (CLI.RetZExt)
9020           MyFlags.Flags.setZExt();
9021         if (CLI.IsInReg)
9022           MyFlags.Flags.setInReg();
9023         CLI.Ins.push_back(MyFlags);
9024       }
9025     }
9026   }
9027 
9028   // We push in swifterror return as the last element of CLI.Ins.
9029   ArgListTy &Args = CLI.getArgs();
9030   if (supportSwiftError()) {
9031     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9032       if (Args[i].IsSwiftError) {
9033         ISD::InputArg MyFlags;
9034         MyFlags.VT = getPointerTy(DL);
9035         MyFlags.ArgVT = EVT(getPointerTy(DL));
9036         MyFlags.Flags.setSwiftError();
9037         CLI.Ins.push_back(MyFlags);
9038       }
9039     }
9040   }
9041 
9042   // Handle all of the outgoing arguments.
9043   CLI.Outs.clear();
9044   CLI.OutVals.clear();
9045   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9046     SmallVector<EVT, 4> ValueVTs;
9047     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9048     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9049     Type *FinalType = Args[i].Ty;
9050     if (Args[i].IsByVal)
9051       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9052     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9053         FinalType, CLI.CallConv, CLI.IsVarArg);
9054     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9055          ++Value) {
9056       EVT VT = ValueVTs[Value];
9057       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9058       SDValue Op = SDValue(Args[i].Node.getNode(),
9059                            Args[i].Node.getResNo() + Value);
9060       ISD::ArgFlagsTy Flags;
9061 
9062       // Certain targets (such as MIPS), may have a different ABI alignment
9063       // for a type depending on the context. Give the target a chance to
9064       // specify the alignment it wants.
9065       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
9066 
9067       if (Args[i].Ty->isPointerTy()) {
9068         Flags.setPointer();
9069         Flags.setPointerAddrSpace(
9070             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9071       }
9072       if (Args[i].IsZExt)
9073         Flags.setZExt();
9074       if (Args[i].IsSExt)
9075         Flags.setSExt();
9076       if (Args[i].IsInReg) {
9077         // If we are using vectorcall calling convention, a structure that is
9078         // passed InReg - is surely an HVA
9079         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9080             isa<StructType>(FinalType)) {
9081           // The first value of a structure is marked
9082           if (0 == Value)
9083             Flags.setHvaStart();
9084           Flags.setHva();
9085         }
9086         // Set InReg Flag
9087         Flags.setInReg();
9088       }
9089       if (Args[i].IsSRet)
9090         Flags.setSRet();
9091       if (Args[i].IsSwiftSelf)
9092         Flags.setSwiftSelf();
9093       if (Args[i].IsSwiftError)
9094         Flags.setSwiftError();
9095       if (Args[i].IsCFGuardTarget)
9096         Flags.setCFGuardTarget();
9097       if (Args[i].IsByVal)
9098         Flags.setByVal();
9099       if (Args[i].IsInAlloca) {
9100         Flags.setInAlloca();
9101         // Set the byval flag for CCAssignFn callbacks that don't know about
9102         // inalloca.  This way we can know how many bytes we should've allocated
9103         // and how many bytes a callee cleanup function will pop.  If we port
9104         // inalloca to more targets, we'll have to add custom inalloca handling
9105         // in the various CC lowering callbacks.
9106         Flags.setByVal();
9107       }
9108       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9109         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9110         Type *ElementTy = Ty->getElementType();
9111 
9112         unsigned FrameSize = DL.getTypeAllocSize(
9113             Args[i].ByValType ? Args[i].ByValType : ElementTy);
9114         Flags.setByValSize(FrameSize);
9115 
9116         // info is not there but there are cases it cannot get right.
9117         unsigned FrameAlign;
9118         if (Args[i].Alignment)
9119           FrameAlign = Args[i].Alignment;
9120         else
9121           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9122         Flags.setByValAlign(Align(FrameAlign));
9123       }
9124       if (Args[i].IsNest)
9125         Flags.setNest();
9126       if (NeedsRegBlock)
9127         Flags.setInConsecutiveRegs();
9128       Flags.setOrigAlign(OriginalAlignment);
9129 
9130       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9131                                                  CLI.CallConv, VT);
9132       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9133                                                         CLI.CallConv, VT);
9134       SmallVector<SDValue, 4> Parts(NumParts);
9135       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9136 
9137       if (Args[i].IsSExt)
9138         ExtendKind = ISD::SIGN_EXTEND;
9139       else if (Args[i].IsZExt)
9140         ExtendKind = ISD::ZERO_EXTEND;
9141 
9142       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9143       // for now.
9144       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9145           CanLowerReturn) {
9146         assert((CLI.RetTy == Args[i].Ty ||
9147                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
9148                  CLI.RetTy->getPointerAddressSpace() ==
9149                      Args[i].Ty->getPointerAddressSpace())) &&
9150                RetTys.size() == NumValues && "unexpected use of 'returned'");
9151         // Before passing 'returned' to the target lowering code, ensure that
9152         // either the register MVT and the actual EVT are the same size or that
9153         // the return value and argument are extended in the same way; in these
9154         // cases it's safe to pass the argument register value unchanged as the
9155         // return register value (although it's at the target's option whether
9156         // to do so)
9157         // TODO: allow code generation to take advantage of partially preserved
9158         // registers rather than clobbering the entire register when the
9159         // parameter extension method is not compatible with the return
9160         // extension method
9161         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9162             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9163              CLI.RetZExt == Args[i].IsZExt))
9164           Flags.setReturned();
9165       }
9166 
9167       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9168                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9169 
9170       for (unsigned j = 0; j != NumParts; ++j) {
9171         // if it isn't first piece, alignment must be 1
9172         // For scalable vectors the scalable part is currently handled
9173         // by individual targets, so we just use the known minimum size here.
9174         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9175                     i < CLI.NumFixedArgs, i,
9176                     j*Parts[j].getValueType().getStoreSize().getKnownMinSize());
9177         if (NumParts > 1 && j == 0)
9178           MyFlags.Flags.setSplit();
9179         else if (j != 0) {
9180           MyFlags.Flags.setOrigAlign(Align::None());
9181           if (j == NumParts - 1)
9182             MyFlags.Flags.setSplitEnd();
9183         }
9184 
9185         CLI.Outs.push_back(MyFlags);
9186         CLI.OutVals.push_back(Parts[j]);
9187       }
9188 
9189       if (NeedsRegBlock && Value == NumValues - 1)
9190         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9191     }
9192   }
9193 
9194   SmallVector<SDValue, 4> InVals;
9195   CLI.Chain = LowerCall(CLI, InVals);
9196 
9197   // Update CLI.InVals to use outside of this function.
9198   CLI.InVals = InVals;
9199 
9200   // Verify that the target's LowerCall behaved as expected.
9201   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9202          "LowerCall didn't return a valid chain!");
9203   assert((!CLI.IsTailCall || InVals.empty()) &&
9204          "LowerCall emitted a return value for a tail call!");
9205   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9206          "LowerCall didn't emit the correct number of values!");
9207 
9208   // For a tail call, the return value is merely live-out and there aren't
9209   // any nodes in the DAG representing it. Return a special value to
9210   // indicate that a tail call has been emitted and no more Instructions
9211   // should be processed in the current block.
9212   if (CLI.IsTailCall) {
9213     CLI.DAG.setRoot(CLI.Chain);
9214     return std::make_pair(SDValue(), SDValue());
9215   }
9216 
9217 #ifndef NDEBUG
9218   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9219     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9220     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9221            "LowerCall emitted a value with the wrong type!");
9222   }
9223 #endif
9224 
9225   SmallVector<SDValue, 4> ReturnValues;
9226   if (!CanLowerReturn) {
9227     // The instruction result is the result of loading from the
9228     // hidden sret parameter.
9229     SmallVector<EVT, 1> PVTs;
9230     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9231 
9232     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9233     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9234     EVT PtrVT = PVTs[0];
9235 
9236     unsigned NumValues = RetTys.size();
9237     ReturnValues.resize(NumValues);
9238     SmallVector<SDValue, 4> Chains(NumValues);
9239 
9240     // An aggregate return value cannot wrap around the address space, so
9241     // offsets to its parts don't wrap either.
9242     SDNodeFlags Flags;
9243     Flags.setNoUnsignedWrap(true);
9244 
9245     for (unsigned i = 0; i < NumValues; ++i) {
9246       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9247                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9248                                                         PtrVT), Flags);
9249       SDValue L = CLI.DAG.getLoad(
9250           RetTys[i], CLI.DL, CLI.Chain, Add,
9251           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9252                                             DemoteStackIdx, Offsets[i]),
9253           /* Alignment = */ 1);
9254       ReturnValues[i] = L;
9255       Chains[i] = L.getValue(1);
9256     }
9257 
9258     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9259   } else {
9260     // Collect the legal value parts into potentially illegal values
9261     // that correspond to the original function's return values.
9262     Optional<ISD::NodeType> AssertOp;
9263     if (CLI.RetSExt)
9264       AssertOp = ISD::AssertSext;
9265     else if (CLI.RetZExt)
9266       AssertOp = ISD::AssertZext;
9267     unsigned CurReg = 0;
9268     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9269       EVT VT = RetTys[I];
9270       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9271                                                      CLI.CallConv, VT);
9272       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9273                                                        CLI.CallConv, VT);
9274 
9275       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9276                                               NumRegs, RegisterVT, VT, nullptr,
9277                                               CLI.CallConv, AssertOp));
9278       CurReg += NumRegs;
9279     }
9280 
9281     // For a function returning void, there is no return value. We can't create
9282     // such a node, so we just return a null return value in that case. In
9283     // that case, nothing will actually look at the value.
9284     if (ReturnValues.empty())
9285       return std::make_pair(SDValue(), CLI.Chain);
9286   }
9287 
9288   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9289                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9290   return std::make_pair(Res, CLI.Chain);
9291 }
9292 
9293 void TargetLowering::LowerOperationWrapper(SDNode *N,
9294                                            SmallVectorImpl<SDValue> &Results,
9295                                            SelectionDAG &DAG) const {
9296   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9297     Results.push_back(Res);
9298 }
9299 
9300 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9301   llvm_unreachable("LowerOperation not implemented for this target!");
9302 }
9303 
9304 void
9305 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9306   SDValue Op = getNonRegisterValue(V);
9307   assert((Op.getOpcode() != ISD::CopyFromReg ||
9308           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9309          "Copy from a reg to the same reg!");
9310   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
9311 
9312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9313   // If this is an InlineAsm we have to match the registers required, not the
9314   // notional registers required by the type.
9315 
9316   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9317                    None); // This is not an ABI copy.
9318   SDValue Chain = DAG.getEntryNode();
9319 
9320   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9321                               FuncInfo.PreferredExtendType.end())
9322                                  ? ISD::ANY_EXTEND
9323                                  : FuncInfo.PreferredExtendType[V];
9324   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9325   PendingExports.push_back(Chain);
9326 }
9327 
9328 #include "llvm/CodeGen/SelectionDAGISel.h"
9329 
9330 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9331 /// entry block, return true.  This includes arguments used by switches, since
9332 /// the switch may expand into multiple basic blocks.
9333 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9334   // With FastISel active, we may be splitting blocks, so force creation
9335   // of virtual registers for all non-dead arguments.
9336   if (FastISel)
9337     return A->use_empty();
9338 
9339   const BasicBlock &Entry = A->getParent()->front();
9340   for (const User *U : A->users())
9341     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9342       return false;  // Use not in entry block.
9343 
9344   return true;
9345 }
9346 
9347 using ArgCopyElisionMapTy =
9348     DenseMap<const Argument *,
9349              std::pair<const AllocaInst *, const StoreInst *>>;
9350 
9351 /// Scan the entry block of the function in FuncInfo for arguments that look
9352 /// like copies into a local alloca. Record any copied arguments in
9353 /// ArgCopyElisionCandidates.
9354 static void
9355 findArgumentCopyElisionCandidates(const DataLayout &DL,
9356                                   FunctionLoweringInfo *FuncInfo,
9357                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9358   // Record the state of every static alloca used in the entry block. Argument
9359   // allocas are all used in the entry block, so we need approximately as many
9360   // entries as we have arguments.
9361   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9362   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9363   unsigned NumArgs = FuncInfo->Fn->arg_size();
9364   StaticAllocas.reserve(NumArgs * 2);
9365 
9366   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9367     if (!V)
9368       return nullptr;
9369     V = V->stripPointerCasts();
9370     const auto *AI = dyn_cast<AllocaInst>(V);
9371     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9372       return nullptr;
9373     auto Iter = StaticAllocas.insert({AI, Unknown});
9374     return &Iter.first->second;
9375   };
9376 
9377   // Look for stores of arguments to static allocas. Look through bitcasts and
9378   // GEPs to handle type coercions, as long as the alloca is fully initialized
9379   // by the store. Any non-store use of an alloca escapes it and any subsequent
9380   // unanalyzed store might write it.
9381   // FIXME: Handle structs initialized with multiple stores.
9382   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9383     // Look for stores, and handle non-store uses conservatively.
9384     const auto *SI = dyn_cast<StoreInst>(&I);
9385     if (!SI) {
9386       // We will look through cast uses, so ignore them completely.
9387       if (I.isCast())
9388         continue;
9389       // Ignore debug info intrinsics, they don't escape or store to allocas.
9390       if (isa<DbgInfoIntrinsic>(I))
9391         continue;
9392       // This is an unknown instruction. Assume it escapes or writes to all
9393       // static alloca operands.
9394       for (const Use &U : I.operands()) {
9395         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9396           *Info = StaticAllocaInfo::Clobbered;
9397       }
9398       continue;
9399     }
9400 
9401     // If the stored value is a static alloca, mark it as escaped.
9402     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9403       *Info = StaticAllocaInfo::Clobbered;
9404 
9405     // Check if the destination is a static alloca.
9406     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9407     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9408     if (!Info)
9409       continue;
9410     const AllocaInst *AI = cast<AllocaInst>(Dst);
9411 
9412     // Skip allocas that have been initialized or clobbered.
9413     if (*Info != StaticAllocaInfo::Unknown)
9414       continue;
9415 
9416     // Check if the stored value is an argument, and that this store fully
9417     // initializes the alloca. Don't elide copies from the same argument twice.
9418     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9419     const auto *Arg = dyn_cast<Argument>(Val);
9420     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9421         Arg->getType()->isEmptyTy() ||
9422         DL.getTypeStoreSize(Arg->getType()) !=
9423             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9424         ArgCopyElisionCandidates.count(Arg)) {
9425       *Info = StaticAllocaInfo::Clobbered;
9426       continue;
9427     }
9428 
9429     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9430                       << '\n');
9431 
9432     // Mark this alloca and store for argument copy elision.
9433     *Info = StaticAllocaInfo::Elidable;
9434     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9435 
9436     // Stop scanning if we've seen all arguments. This will happen early in -O0
9437     // builds, which is useful, because -O0 builds have large entry blocks and
9438     // many allocas.
9439     if (ArgCopyElisionCandidates.size() == NumArgs)
9440       break;
9441   }
9442 }
9443 
9444 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9445 /// ArgVal is a load from a suitable fixed stack object.
9446 static void tryToElideArgumentCopy(
9447     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9448     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9449     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9450     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9451     SDValue ArgVal, bool &ArgHasUses) {
9452   // Check if this is a load from a fixed stack object.
9453   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9454   if (!LNode)
9455     return;
9456   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9457   if (!FINode)
9458     return;
9459 
9460   // Check that the fixed stack object is the right size and alignment.
9461   // Look at the alignment that the user wrote on the alloca instead of looking
9462   // at the stack object.
9463   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9464   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9465   const AllocaInst *AI = ArgCopyIter->second.first;
9466   int FixedIndex = FINode->getIndex();
9467   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9468   int OldIndex = AllocaIndex;
9469   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9470   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9471     LLVM_DEBUG(
9472         dbgs() << "  argument copy elision failed due to bad fixed stack "
9473                   "object size\n");
9474     return;
9475   }
9476   unsigned RequiredAlignment = AI->getAlignment();
9477   if (!RequiredAlignment) {
9478     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9479         AI->getAllocatedType());
9480   }
9481   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9482     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9483                          "greater than stack argument alignment ("
9484                       << RequiredAlignment << " vs "
9485                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9486     return;
9487   }
9488 
9489   // Perform the elision. Delete the old stack object and replace its only use
9490   // in the variable info map. Mark the stack object as mutable.
9491   LLVM_DEBUG({
9492     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9493            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9494            << '\n';
9495   });
9496   MFI.RemoveStackObject(OldIndex);
9497   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9498   AllocaIndex = FixedIndex;
9499   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9500   Chains.push_back(ArgVal.getValue(1));
9501 
9502   // Avoid emitting code for the store implementing the copy.
9503   const StoreInst *SI = ArgCopyIter->second.second;
9504   ElidedArgCopyInstrs.insert(SI);
9505 
9506   // Check for uses of the argument again so that we can avoid exporting ArgVal
9507   // if it is't used by anything other than the store.
9508   for (const Value *U : Arg.users()) {
9509     if (U != SI) {
9510       ArgHasUses = true;
9511       break;
9512     }
9513   }
9514 }
9515 
9516 void SelectionDAGISel::LowerArguments(const Function &F) {
9517   SelectionDAG &DAG = SDB->DAG;
9518   SDLoc dl = SDB->getCurSDLoc();
9519   const DataLayout &DL = DAG.getDataLayout();
9520   SmallVector<ISD::InputArg, 16> Ins;
9521 
9522   if (!FuncInfo->CanLowerReturn) {
9523     // Put in an sret pointer parameter before all the other parameters.
9524     SmallVector<EVT, 1> ValueVTs;
9525     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9526                     F.getReturnType()->getPointerTo(
9527                         DAG.getDataLayout().getAllocaAddrSpace()),
9528                     ValueVTs);
9529 
9530     // NOTE: Assuming that a pointer will never break down to more than one VT
9531     // or one register.
9532     ISD::ArgFlagsTy Flags;
9533     Flags.setSRet();
9534     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9535     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9536                          ISD::InputArg::NoArgIndex, 0);
9537     Ins.push_back(RetArg);
9538   }
9539 
9540   // Look for stores of arguments to static allocas. Mark such arguments with a
9541   // flag to ask the target to give us the memory location of that argument if
9542   // available.
9543   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9544   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9545 
9546   // Set up the incoming argument description vector.
9547   for (const Argument &Arg : F.args()) {
9548     unsigned ArgNo = Arg.getArgNo();
9549     SmallVector<EVT, 4> ValueVTs;
9550     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9551     bool isArgValueUsed = !Arg.use_empty();
9552     unsigned PartBase = 0;
9553     Type *FinalType = Arg.getType();
9554     if (Arg.hasAttribute(Attribute::ByVal))
9555       FinalType = Arg.getParamByValType();
9556     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9557         FinalType, F.getCallingConv(), F.isVarArg());
9558     for (unsigned Value = 0, NumValues = ValueVTs.size();
9559          Value != NumValues; ++Value) {
9560       EVT VT = ValueVTs[Value];
9561       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9562       ISD::ArgFlagsTy Flags;
9563 
9564       // Certain targets (such as MIPS), may have a different ABI alignment
9565       // for a type depending on the context. Give the target a chance to
9566       // specify the alignment it wants.
9567       const Align OriginalAlignment(
9568           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
9569 
9570       if (Arg.getType()->isPointerTy()) {
9571         Flags.setPointer();
9572         Flags.setPointerAddrSpace(
9573             cast<PointerType>(Arg.getType())->getAddressSpace());
9574       }
9575       if (Arg.hasAttribute(Attribute::ZExt))
9576         Flags.setZExt();
9577       if (Arg.hasAttribute(Attribute::SExt))
9578         Flags.setSExt();
9579       if (Arg.hasAttribute(Attribute::InReg)) {
9580         // If we are using vectorcall calling convention, a structure that is
9581         // passed InReg - is surely an HVA
9582         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9583             isa<StructType>(Arg.getType())) {
9584           // The first value of a structure is marked
9585           if (0 == Value)
9586             Flags.setHvaStart();
9587           Flags.setHva();
9588         }
9589         // Set InReg Flag
9590         Flags.setInReg();
9591       }
9592       if (Arg.hasAttribute(Attribute::StructRet))
9593         Flags.setSRet();
9594       if (Arg.hasAttribute(Attribute::SwiftSelf))
9595         Flags.setSwiftSelf();
9596       if (Arg.hasAttribute(Attribute::SwiftError))
9597         Flags.setSwiftError();
9598       if (Arg.hasAttribute(Attribute::ByVal))
9599         Flags.setByVal();
9600       if (Arg.hasAttribute(Attribute::InAlloca)) {
9601         Flags.setInAlloca();
9602         // Set the byval flag for CCAssignFn callbacks that don't know about
9603         // inalloca.  This way we can know how many bytes we should've allocated
9604         // and how many bytes a callee cleanup function will pop.  If we port
9605         // inalloca to more targets, we'll have to add custom inalloca handling
9606         // in the various CC lowering callbacks.
9607         Flags.setByVal();
9608       }
9609       if (F.getCallingConv() == CallingConv::X86_INTR) {
9610         // IA Interrupt passes frame (1st parameter) by value in the stack.
9611         if (ArgNo == 0)
9612           Flags.setByVal();
9613       }
9614       if (Flags.isByVal() || Flags.isInAlloca()) {
9615         Type *ElementTy = Arg.getParamByValType();
9616 
9617         // For ByVal, size and alignment should be passed from FE.  BE will
9618         // guess if this info is not there but there are cases it cannot get
9619         // right.
9620         unsigned FrameSize = DL.getTypeAllocSize(Arg.getParamByValType());
9621         Flags.setByValSize(FrameSize);
9622 
9623         unsigned FrameAlign;
9624         if (Arg.getParamAlignment())
9625           FrameAlign = Arg.getParamAlignment();
9626         else
9627           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9628         Flags.setByValAlign(Align(FrameAlign));
9629       }
9630       if (Arg.hasAttribute(Attribute::Nest))
9631         Flags.setNest();
9632       if (NeedsRegBlock)
9633         Flags.setInConsecutiveRegs();
9634       Flags.setOrigAlign(OriginalAlignment);
9635       if (ArgCopyElisionCandidates.count(&Arg))
9636         Flags.setCopyElisionCandidate();
9637       if (Arg.hasAttribute(Attribute::Returned))
9638         Flags.setReturned();
9639 
9640       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9641           *CurDAG->getContext(), F.getCallingConv(), VT);
9642       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9643           *CurDAG->getContext(), F.getCallingConv(), VT);
9644       for (unsigned i = 0; i != NumRegs; ++i) {
9645         // For scalable vectors, use the minimum size; individual targets
9646         // are responsible for handling scalable vector arguments and
9647         // return values.
9648         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9649                  ArgNo, PartBase+i*RegisterVT.getStoreSize().getKnownMinSize());
9650         if (NumRegs > 1 && i == 0)
9651           MyFlags.Flags.setSplit();
9652         // if it isn't first piece, alignment must be 1
9653         else if (i > 0) {
9654           MyFlags.Flags.setOrigAlign(Align::None());
9655           if (i == NumRegs - 1)
9656             MyFlags.Flags.setSplitEnd();
9657         }
9658         Ins.push_back(MyFlags);
9659       }
9660       if (NeedsRegBlock && Value == NumValues - 1)
9661         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9662       PartBase += VT.getStoreSize().getKnownMinSize();
9663     }
9664   }
9665 
9666   // Call the target to set up the argument values.
9667   SmallVector<SDValue, 8> InVals;
9668   SDValue NewRoot = TLI->LowerFormalArguments(
9669       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9670 
9671   // Verify that the target's LowerFormalArguments behaved as expected.
9672   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9673          "LowerFormalArguments didn't return a valid chain!");
9674   assert(InVals.size() == Ins.size() &&
9675          "LowerFormalArguments didn't emit the correct number of values!");
9676   LLVM_DEBUG({
9677     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9678       assert(InVals[i].getNode() &&
9679              "LowerFormalArguments emitted a null value!");
9680       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9681              "LowerFormalArguments emitted a value with the wrong type!");
9682     }
9683   });
9684 
9685   // Update the DAG with the new chain value resulting from argument lowering.
9686   DAG.setRoot(NewRoot);
9687 
9688   // Set up the argument values.
9689   unsigned i = 0;
9690   if (!FuncInfo->CanLowerReturn) {
9691     // Create a virtual register for the sret pointer, and put in a copy
9692     // from the sret argument into it.
9693     SmallVector<EVT, 1> ValueVTs;
9694     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9695                     F.getReturnType()->getPointerTo(
9696                         DAG.getDataLayout().getAllocaAddrSpace()),
9697                     ValueVTs);
9698     MVT VT = ValueVTs[0].getSimpleVT();
9699     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9700     Optional<ISD::NodeType> AssertOp = None;
9701     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9702                                         nullptr, F.getCallingConv(), AssertOp);
9703 
9704     MachineFunction& MF = SDB->DAG.getMachineFunction();
9705     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9706     Register SRetReg =
9707         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9708     FuncInfo->DemoteRegister = SRetReg;
9709     NewRoot =
9710         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9711     DAG.setRoot(NewRoot);
9712 
9713     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9714     ++i;
9715   }
9716 
9717   SmallVector<SDValue, 4> Chains;
9718   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9719   for (const Argument &Arg : F.args()) {
9720     SmallVector<SDValue, 4> ArgValues;
9721     SmallVector<EVT, 4> ValueVTs;
9722     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9723     unsigned NumValues = ValueVTs.size();
9724     if (NumValues == 0)
9725       continue;
9726 
9727     bool ArgHasUses = !Arg.use_empty();
9728 
9729     // Elide the copying store if the target loaded this argument from a
9730     // suitable fixed stack object.
9731     if (Ins[i].Flags.isCopyElisionCandidate()) {
9732       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9733                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9734                              InVals[i], ArgHasUses);
9735     }
9736 
9737     // If this argument is unused then remember its value. It is used to generate
9738     // debugging information.
9739     bool isSwiftErrorArg =
9740         TLI->supportSwiftError() &&
9741         Arg.hasAttribute(Attribute::SwiftError);
9742     if (!ArgHasUses && !isSwiftErrorArg) {
9743       SDB->setUnusedArgValue(&Arg, InVals[i]);
9744 
9745       // Also remember any frame index for use in FastISel.
9746       if (FrameIndexSDNode *FI =
9747           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9748         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9749     }
9750 
9751     for (unsigned Val = 0; Val != NumValues; ++Val) {
9752       EVT VT = ValueVTs[Val];
9753       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9754                                                       F.getCallingConv(), VT);
9755       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9756           *CurDAG->getContext(), F.getCallingConv(), VT);
9757 
9758       // Even an apparent 'unused' swifterror argument needs to be returned. So
9759       // we do generate a copy for it that can be used on return from the
9760       // function.
9761       if (ArgHasUses || isSwiftErrorArg) {
9762         Optional<ISD::NodeType> AssertOp;
9763         if (Arg.hasAttribute(Attribute::SExt))
9764           AssertOp = ISD::AssertSext;
9765         else if (Arg.hasAttribute(Attribute::ZExt))
9766           AssertOp = ISD::AssertZext;
9767 
9768         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9769                                              PartVT, VT, nullptr,
9770                                              F.getCallingConv(), AssertOp));
9771       }
9772 
9773       i += NumParts;
9774     }
9775 
9776     // We don't need to do anything else for unused arguments.
9777     if (ArgValues.empty())
9778       continue;
9779 
9780     // Note down frame index.
9781     if (FrameIndexSDNode *FI =
9782         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9783       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9784 
9785     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9786                                      SDB->getCurSDLoc());
9787 
9788     SDB->setValue(&Arg, Res);
9789     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9790       // We want to associate the argument with the frame index, among
9791       // involved operands, that correspond to the lowest address. The
9792       // getCopyFromParts function, called earlier, is swapping the order of
9793       // the operands to BUILD_PAIR depending on endianness. The result of
9794       // that swapping is that the least significant bits of the argument will
9795       // be in the first operand of the BUILD_PAIR node, and the most
9796       // significant bits will be in the second operand.
9797       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9798       if (LoadSDNode *LNode =
9799           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9800         if (FrameIndexSDNode *FI =
9801             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9802           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9803     }
9804 
9805     // Analyses past this point are naive and don't expect an assertion.
9806     if (Res.getOpcode() == ISD::AssertZext)
9807       Res = Res.getOperand(0);
9808 
9809     // Update the SwiftErrorVRegDefMap.
9810     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9811       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9812       if (Register::isVirtualRegister(Reg))
9813         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9814                                    Reg);
9815     }
9816 
9817     // If this argument is live outside of the entry block, insert a copy from
9818     // wherever we got it to the vreg that other BB's will reference it as.
9819     if (Res.getOpcode() == ISD::CopyFromReg) {
9820       // If we can, though, try to skip creating an unnecessary vreg.
9821       // FIXME: This isn't very clean... it would be nice to make this more
9822       // general.
9823       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9824       if (Register::isVirtualRegister(Reg)) {
9825         FuncInfo->ValueMap[&Arg] = Reg;
9826         continue;
9827       }
9828     }
9829     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9830       FuncInfo->InitializeRegForValue(&Arg);
9831       SDB->CopyToExportRegsIfNeeded(&Arg);
9832     }
9833   }
9834 
9835   if (!Chains.empty()) {
9836     Chains.push_back(NewRoot);
9837     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9838   }
9839 
9840   DAG.setRoot(NewRoot);
9841 
9842   assert(i == InVals.size() && "Argument register count mismatch!");
9843 
9844   // If any argument copy elisions occurred and we have debug info, update the
9845   // stale frame indices used in the dbg.declare variable info table.
9846   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9847   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9848     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9849       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9850       if (I != ArgCopyElisionFrameIndexMap.end())
9851         VI.Slot = I->second;
9852     }
9853   }
9854 
9855   // Finally, if the target has anything special to do, allow it to do so.
9856   EmitFunctionEntryCode();
9857 }
9858 
9859 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9860 /// ensure constants are generated when needed.  Remember the virtual registers
9861 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9862 /// directly add them, because expansion might result in multiple MBB's for one
9863 /// BB.  As such, the start of the BB might correspond to a different MBB than
9864 /// the end.
9865 void
9866 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9867   const Instruction *TI = LLVMBB->getTerminator();
9868 
9869   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9870 
9871   // Check PHI nodes in successors that expect a value to be available from this
9872   // block.
9873   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9874     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9875     if (!isa<PHINode>(SuccBB->begin())) continue;
9876     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9877 
9878     // If this terminator has multiple identical successors (common for
9879     // switches), only handle each succ once.
9880     if (!SuccsHandled.insert(SuccMBB).second)
9881       continue;
9882 
9883     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9884 
9885     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9886     // nodes and Machine PHI nodes, but the incoming operands have not been
9887     // emitted yet.
9888     for (const PHINode &PN : SuccBB->phis()) {
9889       // Ignore dead phi's.
9890       if (PN.use_empty())
9891         continue;
9892 
9893       // Skip empty types
9894       if (PN.getType()->isEmptyTy())
9895         continue;
9896 
9897       unsigned Reg;
9898       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9899 
9900       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9901         unsigned &RegOut = ConstantsOut[C];
9902         if (RegOut == 0) {
9903           RegOut = FuncInfo.CreateRegs(C);
9904           CopyValueToVirtualRegister(C, RegOut);
9905         }
9906         Reg = RegOut;
9907       } else {
9908         DenseMap<const Value *, unsigned>::iterator I =
9909           FuncInfo.ValueMap.find(PHIOp);
9910         if (I != FuncInfo.ValueMap.end())
9911           Reg = I->second;
9912         else {
9913           assert(isa<AllocaInst>(PHIOp) &&
9914                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9915                  "Didn't codegen value into a register!??");
9916           Reg = FuncInfo.CreateRegs(PHIOp);
9917           CopyValueToVirtualRegister(PHIOp, Reg);
9918         }
9919       }
9920 
9921       // Remember that this register needs to added to the machine PHI node as
9922       // the input for this MBB.
9923       SmallVector<EVT, 4> ValueVTs;
9924       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9925       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9926       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9927         EVT VT = ValueVTs[vti];
9928         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9929         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9930           FuncInfo.PHINodesToUpdate.push_back(
9931               std::make_pair(&*MBBI++, Reg + i));
9932         Reg += NumRegisters;
9933       }
9934     }
9935   }
9936 
9937   ConstantsOut.clear();
9938 }
9939 
9940 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9941 /// is 0.
9942 MachineBasicBlock *
9943 SelectionDAGBuilder::StackProtectorDescriptor::
9944 AddSuccessorMBB(const BasicBlock *BB,
9945                 MachineBasicBlock *ParentMBB,
9946                 bool IsLikely,
9947                 MachineBasicBlock *SuccMBB) {
9948   // If SuccBB has not been created yet, create it.
9949   if (!SuccMBB) {
9950     MachineFunction *MF = ParentMBB->getParent();
9951     MachineFunction::iterator BBI(ParentMBB);
9952     SuccMBB = MF->CreateMachineBasicBlock(BB);
9953     MF->insert(++BBI, SuccMBB);
9954   }
9955   // Add it as a successor of ParentMBB.
9956   ParentMBB->addSuccessor(
9957       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9958   return SuccMBB;
9959 }
9960 
9961 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9962   MachineFunction::iterator I(MBB);
9963   if (++I == FuncInfo.MF->end())
9964     return nullptr;
9965   return &*I;
9966 }
9967 
9968 /// During lowering new call nodes can be created (such as memset, etc.).
9969 /// Those will become new roots of the current DAG, but complications arise
9970 /// when they are tail calls. In such cases, the call lowering will update
9971 /// the root, but the builder still needs to know that a tail call has been
9972 /// lowered in order to avoid generating an additional return.
9973 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9974   // If the node is null, we do have a tail call.
9975   if (MaybeTC.getNode() != nullptr)
9976     DAG.setRoot(MaybeTC);
9977   else
9978     HasTailCall = true;
9979 }
9980 
9981 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9982                                         MachineBasicBlock *SwitchMBB,
9983                                         MachineBasicBlock *DefaultMBB) {
9984   MachineFunction *CurMF = FuncInfo.MF;
9985   MachineBasicBlock *NextMBB = nullptr;
9986   MachineFunction::iterator BBI(W.MBB);
9987   if (++BBI != FuncInfo.MF->end())
9988     NextMBB = &*BBI;
9989 
9990   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9991 
9992   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9993 
9994   if (Size == 2 && W.MBB == SwitchMBB) {
9995     // If any two of the cases has the same destination, and if one value
9996     // is the same as the other, but has one bit unset that the other has set,
9997     // use bit manipulation to do two compares at once.  For example:
9998     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9999     // TODO: This could be extended to merge any 2 cases in switches with 3
10000     // cases.
10001     // TODO: Handle cases where W.CaseBB != SwitchBB.
10002     CaseCluster &Small = *W.FirstCluster;
10003     CaseCluster &Big = *W.LastCluster;
10004 
10005     if (Small.Low == Small.High && Big.Low == Big.High &&
10006         Small.MBB == Big.MBB) {
10007       const APInt &SmallValue = Small.Low->getValue();
10008       const APInt &BigValue = Big.Low->getValue();
10009 
10010       // Check that there is only one bit different.
10011       APInt CommonBit = BigValue ^ SmallValue;
10012       if (CommonBit.isPowerOf2()) {
10013         SDValue CondLHS = getValue(Cond);
10014         EVT VT = CondLHS.getValueType();
10015         SDLoc DL = getCurSDLoc();
10016 
10017         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10018                                  DAG.getConstant(CommonBit, DL, VT));
10019         SDValue Cond = DAG.getSetCC(
10020             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10021             ISD::SETEQ);
10022 
10023         // Update successor info.
10024         // Both Small and Big will jump to Small.BB, so we sum up the
10025         // probabilities.
10026         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10027         if (BPI)
10028           addSuccessorWithProb(
10029               SwitchMBB, DefaultMBB,
10030               // The default destination is the first successor in IR.
10031               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10032         else
10033           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10034 
10035         // Insert the true branch.
10036         SDValue BrCond =
10037             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10038                         DAG.getBasicBlock(Small.MBB));
10039         // Insert the false branch.
10040         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10041                              DAG.getBasicBlock(DefaultMBB));
10042 
10043         DAG.setRoot(BrCond);
10044         return;
10045       }
10046     }
10047   }
10048 
10049   if (TM.getOptLevel() != CodeGenOpt::None) {
10050     // Here, we order cases by probability so the most likely case will be
10051     // checked first. However, two clusters can have the same probability in
10052     // which case their relative ordering is non-deterministic. So we use Low
10053     // as a tie-breaker as clusters are guaranteed to never overlap.
10054     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10055                [](const CaseCluster &a, const CaseCluster &b) {
10056       return a.Prob != b.Prob ?
10057              a.Prob > b.Prob :
10058              a.Low->getValue().slt(b.Low->getValue());
10059     });
10060 
10061     // Rearrange the case blocks so that the last one falls through if possible
10062     // without changing the order of probabilities.
10063     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10064       --I;
10065       if (I->Prob > W.LastCluster->Prob)
10066         break;
10067       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10068         std::swap(*I, *W.LastCluster);
10069         break;
10070       }
10071     }
10072   }
10073 
10074   // Compute total probability.
10075   BranchProbability DefaultProb = W.DefaultProb;
10076   BranchProbability UnhandledProbs = DefaultProb;
10077   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10078     UnhandledProbs += I->Prob;
10079 
10080   MachineBasicBlock *CurMBB = W.MBB;
10081   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10082     bool FallthroughUnreachable = false;
10083     MachineBasicBlock *Fallthrough;
10084     if (I == W.LastCluster) {
10085       // For the last cluster, fall through to the default destination.
10086       Fallthrough = DefaultMBB;
10087       FallthroughUnreachable = isa<UnreachableInst>(
10088           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10089     } else {
10090       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10091       CurMF->insert(BBI, Fallthrough);
10092       // Put Cond in a virtual register to make it available from the new blocks.
10093       ExportFromCurrentBlock(Cond);
10094     }
10095     UnhandledProbs -= I->Prob;
10096 
10097     switch (I->Kind) {
10098       case CC_JumpTable: {
10099         // FIXME: Optimize away range check based on pivot comparisons.
10100         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
10101         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
10102 
10103         // The jump block hasn't been inserted yet; insert it here.
10104         MachineBasicBlock *JumpMBB = JT->MBB;
10105         CurMF->insert(BBI, JumpMBB);
10106 
10107         auto JumpProb = I->Prob;
10108         auto FallthroughProb = UnhandledProbs;
10109 
10110         // If the default statement is a target of the jump table, we evenly
10111         // distribute the default probability to successors of CurMBB. Also
10112         // update the probability on the edge from JumpMBB to Fallthrough.
10113         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10114                                               SE = JumpMBB->succ_end();
10115              SI != SE; ++SI) {
10116           if (*SI == DefaultMBB) {
10117             JumpProb += DefaultProb / 2;
10118             FallthroughProb -= DefaultProb / 2;
10119             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10120             JumpMBB->normalizeSuccProbs();
10121             break;
10122           }
10123         }
10124 
10125         if (FallthroughUnreachable) {
10126           // Skip the range check if the fallthrough block is unreachable.
10127           JTH->OmitRangeCheck = true;
10128         }
10129 
10130         if (!JTH->OmitRangeCheck)
10131           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10132         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10133         CurMBB->normalizeSuccProbs();
10134 
10135         // The jump table header will be inserted in our current block, do the
10136         // range check, and fall through to our fallthrough block.
10137         JTH->HeaderBB = CurMBB;
10138         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10139 
10140         // If we're in the right place, emit the jump table header right now.
10141         if (CurMBB == SwitchMBB) {
10142           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10143           JTH->Emitted = true;
10144         }
10145         break;
10146       }
10147       case CC_BitTests: {
10148         // FIXME: Optimize away range check based on pivot comparisons.
10149         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
10150 
10151         // The bit test blocks haven't been inserted yet; insert them here.
10152         for (BitTestCase &BTC : BTB->Cases)
10153           CurMF->insert(BBI, BTC.ThisBB);
10154 
10155         // Fill in fields of the BitTestBlock.
10156         BTB->Parent = CurMBB;
10157         BTB->Default = Fallthrough;
10158 
10159         BTB->DefaultProb = UnhandledProbs;
10160         // If the cases in bit test don't form a contiguous range, we evenly
10161         // distribute the probability on the edge to Fallthrough to two
10162         // successors of CurMBB.
10163         if (!BTB->ContiguousRange) {
10164           BTB->Prob += DefaultProb / 2;
10165           BTB->DefaultProb -= DefaultProb / 2;
10166         }
10167 
10168         if (FallthroughUnreachable) {
10169           // Skip the range check if the fallthrough block is unreachable.
10170           BTB->OmitRangeCheck = true;
10171         }
10172 
10173         // If we're in the right place, emit the bit test header right now.
10174         if (CurMBB == SwitchMBB) {
10175           visitBitTestHeader(*BTB, SwitchMBB);
10176           BTB->Emitted = true;
10177         }
10178         break;
10179       }
10180       case CC_Range: {
10181         const Value *RHS, *LHS, *MHS;
10182         ISD::CondCode CC;
10183         if (I->Low == I->High) {
10184           // Check Cond == I->Low.
10185           CC = ISD::SETEQ;
10186           LHS = Cond;
10187           RHS=I->Low;
10188           MHS = nullptr;
10189         } else {
10190           // Check I->Low <= Cond <= I->High.
10191           CC = ISD::SETLE;
10192           LHS = I->Low;
10193           MHS = Cond;
10194           RHS = I->High;
10195         }
10196 
10197         // If Fallthrough is unreachable, fold away the comparison.
10198         if (FallthroughUnreachable)
10199           CC = ISD::SETTRUE;
10200 
10201         // The false probability is the sum of all unhandled cases.
10202         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10203                      getCurSDLoc(), I->Prob, UnhandledProbs);
10204 
10205         if (CurMBB == SwitchMBB)
10206           visitSwitchCase(CB, SwitchMBB);
10207         else
10208           SL->SwitchCases.push_back(CB);
10209 
10210         break;
10211       }
10212     }
10213     CurMBB = Fallthrough;
10214   }
10215 }
10216 
10217 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10218                                               CaseClusterIt First,
10219                                               CaseClusterIt Last) {
10220   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10221     if (X.Prob != CC.Prob)
10222       return X.Prob > CC.Prob;
10223 
10224     // Ties are broken by comparing the case value.
10225     return X.Low->getValue().slt(CC.Low->getValue());
10226   });
10227 }
10228 
10229 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10230                                         const SwitchWorkListItem &W,
10231                                         Value *Cond,
10232                                         MachineBasicBlock *SwitchMBB) {
10233   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10234          "Clusters not sorted?");
10235 
10236   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10237 
10238   // Balance the tree based on branch probabilities to create a near-optimal (in
10239   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10240   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10241   CaseClusterIt LastLeft = W.FirstCluster;
10242   CaseClusterIt FirstRight = W.LastCluster;
10243   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10244   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10245 
10246   // Move LastLeft and FirstRight towards each other from opposite directions to
10247   // find a partitioning of the clusters which balances the probability on both
10248   // sides. If LeftProb and RightProb are equal, alternate which side is
10249   // taken to ensure 0-probability nodes are distributed evenly.
10250   unsigned I = 0;
10251   while (LastLeft + 1 < FirstRight) {
10252     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10253       LeftProb += (++LastLeft)->Prob;
10254     else
10255       RightProb += (--FirstRight)->Prob;
10256     I++;
10257   }
10258 
10259   while (true) {
10260     // Our binary search tree differs from a typical BST in that ours can have up
10261     // to three values in each leaf. The pivot selection above doesn't take that
10262     // into account, which means the tree might require more nodes and be less
10263     // efficient. We compensate for this here.
10264 
10265     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10266     unsigned NumRight = W.LastCluster - FirstRight + 1;
10267 
10268     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10269       // If one side has less than 3 clusters, and the other has more than 3,
10270       // consider taking a cluster from the other side.
10271 
10272       if (NumLeft < NumRight) {
10273         // Consider moving the first cluster on the right to the left side.
10274         CaseCluster &CC = *FirstRight;
10275         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10276         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10277         if (LeftSideRank <= RightSideRank) {
10278           // Moving the cluster to the left does not demote it.
10279           ++LastLeft;
10280           ++FirstRight;
10281           continue;
10282         }
10283       } else {
10284         assert(NumRight < NumLeft);
10285         // Consider moving the last element on the left to the right side.
10286         CaseCluster &CC = *LastLeft;
10287         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10288         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10289         if (RightSideRank <= LeftSideRank) {
10290           // Moving the cluster to the right does not demot it.
10291           --LastLeft;
10292           --FirstRight;
10293           continue;
10294         }
10295       }
10296     }
10297     break;
10298   }
10299 
10300   assert(LastLeft + 1 == FirstRight);
10301   assert(LastLeft >= W.FirstCluster);
10302   assert(FirstRight <= W.LastCluster);
10303 
10304   // Use the first element on the right as pivot since we will make less-than
10305   // comparisons against it.
10306   CaseClusterIt PivotCluster = FirstRight;
10307   assert(PivotCluster > W.FirstCluster);
10308   assert(PivotCluster <= W.LastCluster);
10309 
10310   CaseClusterIt FirstLeft = W.FirstCluster;
10311   CaseClusterIt LastRight = W.LastCluster;
10312 
10313   const ConstantInt *Pivot = PivotCluster->Low;
10314 
10315   // New blocks will be inserted immediately after the current one.
10316   MachineFunction::iterator BBI(W.MBB);
10317   ++BBI;
10318 
10319   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10320   // we can branch to its destination directly if it's squeezed exactly in
10321   // between the known lower bound and Pivot - 1.
10322   MachineBasicBlock *LeftMBB;
10323   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10324       FirstLeft->Low == W.GE &&
10325       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10326     LeftMBB = FirstLeft->MBB;
10327   } else {
10328     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10329     FuncInfo.MF->insert(BBI, LeftMBB);
10330     WorkList.push_back(
10331         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10332     // Put Cond in a virtual register to make it available from the new blocks.
10333     ExportFromCurrentBlock(Cond);
10334   }
10335 
10336   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10337   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10338   // directly if RHS.High equals the current upper bound.
10339   MachineBasicBlock *RightMBB;
10340   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10341       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10342     RightMBB = FirstRight->MBB;
10343   } else {
10344     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10345     FuncInfo.MF->insert(BBI, RightMBB);
10346     WorkList.push_back(
10347         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10348     // Put Cond in a virtual register to make it available from the new blocks.
10349     ExportFromCurrentBlock(Cond);
10350   }
10351 
10352   // Create the CaseBlock record that will be used to lower the branch.
10353   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10354                getCurSDLoc(), LeftProb, RightProb);
10355 
10356   if (W.MBB == SwitchMBB)
10357     visitSwitchCase(CB, SwitchMBB);
10358   else
10359     SL->SwitchCases.push_back(CB);
10360 }
10361 
10362 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10363 // from the swith statement.
10364 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10365                                             BranchProbability PeeledCaseProb) {
10366   if (PeeledCaseProb == BranchProbability::getOne())
10367     return BranchProbability::getZero();
10368   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10369 
10370   uint32_t Numerator = CaseProb.getNumerator();
10371   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10372   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10373 }
10374 
10375 // Try to peel the top probability case if it exceeds the threshold.
10376 // Return current MachineBasicBlock for the switch statement if the peeling
10377 // does not occur.
10378 // If the peeling is performed, return the newly created MachineBasicBlock
10379 // for the peeled switch statement. Also update Clusters to remove the peeled
10380 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10381 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10382     const SwitchInst &SI, CaseClusterVector &Clusters,
10383     BranchProbability &PeeledCaseProb) {
10384   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10385   // Don't perform if there is only one cluster or optimizing for size.
10386   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10387       TM.getOptLevel() == CodeGenOpt::None ||
10388       SwitchMBB->getParent()->getFunction().hasMinSize())
10389     return SwitchMBB;
10390 
10391   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10392   unsigned PeeledCaseIndex = 0;
10393   bool SwitchPeeled = false;
10394   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10395     CaseCluster &CC = Clusters[Index];
10396     if (CC.Prob < TopCaseProb)
10397       continue;
10398     TopCaseProb = CC.Prob;
10399     PeeledCaseIndex = Index;
10400     SwitchPeeled = true;
10401   }
10402   if (!SwitchPeeled)
10403     return SwitchMBB;
10404 
10405   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10406                     << TopCaseProb << "\n");
10407 
10408   // Record the MBB for the peeled switch statement.
10409   MachineFunction::iterator BBI(SwitchMBB);
10410   ++BBI;
10411   MachineBasicBlock *PeeledSwitchMBB =
10412       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10413   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10414 
10415   ExportFromCurrentBlock(SI.getCondition());
10416   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10417   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10418                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10419   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10420 
10421   Clusters.erase(PeeledCaseIt);
10422   for (CaseCluster &CC : Clusters) {
10423     LLVM_DEBUG(
10424         dbgs() << "Scale the probablity for one cluster, before scaling: "
10425                << CC.Prob << "\n");
10426     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10427     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10428   }
10429   PeeledCaseProb = TopCaseProb;
10430   return PeeledSwitchMBB;
10431 }
10432 
10433 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10434   // Extract cases from the switch.
10435   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10436   CaseClusterVector Clusters;
10437   Clusters.reserve(SI.getNumCases());
10438   for (auto I : SI.cases()) {
10439     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10440     const ConstantInt *CaseVal = I.getCaseValue();
10441     BranchProbability Prob =
10442         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10443             : BranchProbability(1, SI.getNumCases() + 1);
10444     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10445   }
10446 
10447   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10448 
10449   // Cluster adjacent cases with the same destination. We do this at all
10450   // optimization levels because it's cheap to do and will make codegen faster
10451   // if there are many clusters.
10452   sortAndRangeify(Clusters);
10453 
10454   // The branch probablity of the peeled case.
10455   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10456   MachineBasicBlock *PeeledSwitchMBB =
10457       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10458 
10459   // If there is only the default destination, jump there directly.
10460   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10461   if (Clusters.empty()) {
10462     assert(PeeledSwitchMBB == SwitchMBB);
10463     SwitchMBB->addSuccessor(DefaultMBB);
10464     if (DefaultMBB != NextBlock(SwitchMBB)) {
10465       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10466                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10467     }
10468     return;
10469   }
10470 
10471   SL->findJumpTables(Clusters, &SI, DefaultMBB, DAG.getPSI(), DAG.getBFI());
10472   SL->findBitTestClusters(Clusters, &SI);
10473 
10474   LLVM_DEBUG({
10475     dbgs() << "Case clusters: ";
10476     for (const CaseCluster &C : Clusters) {
10477       if (C.Kind == CC_JumpTable)
10478         dbgs() << "JT:";
10479       if (C.Kind == CC_BitTests)
10480         dbgs() << "BT:";
10481 
10482       C.Low->getValue().print(dbgs(), true);
10483       if (C.Low != C.High) {
10484         dbgs() << '-';
10485         C.High->getValue().print(dbgs(), true);
10486       }
10487       dbgs() << ' ';
10488     }
10489     dbgs() << '\n';
10490   });
10491 
10492   assert(!Clusters.empty());
10493   SwitchWorkList WorkList;
10494   CaseClusterIt First = Clusters.begin();
10495   CaseClusterIt Last = Clusters.end() - 1;
10496   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10497   // Scale the branchprobability for DefaultMBB if the peel occurs and
10498   // DefaultMBB is not replaced.
10499   if (PeeledCaseProb != BranchProbability::getZero() &&
10500       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10501     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10502   WorkList.push_back(
10503       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10504 
10505   while (!WorkList.empty()) {
10506     SwitchWorkListItem W = WorkList.back();
10507     WorkList.pop_back();
10508     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10509 
10510     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10511         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10512       // For optimized builds, lower large range as a balanced binary tree.
10513       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10514       continue;
10515     }
10516 
10517     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10518   }
10519 }
10520 
10521 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
10522   SDValue N = getValue(I.getOperand(0));
10523   setValue(&I, N);
10524 }
10525