xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision ba447bae7448435c9986eece0811da1423972fdd)
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/BranchProbabilityInfo.h"
31 #include "llvm/Analysis/ConstantFolding.h"
32 #include "llvm/Analysis/EHPersonalities.h"
33 #include "llvm/Analysis/Loads.h"
34 #include "llvm/Analysis/MemoryLocation.h"
35 #include "llvm/Analysis/TargetLibraryInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/Analysis/VectorUtils.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/FunctionLoweringInfo.h"
40 #include "llvm/CodeGen/GCMetadata.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineJumpTableInfo.h"
48 #include "llvm/CodeGen/MachineMemOperand.h"
49 #include "llvm/CodeGen/MachineModuleInfo.h"
50 #include "llvm/CodeGen/MachineOperand.h"
51 #include "llvm/CodeGen/MachineRegisterInfo.h"
52 #include "llvm/CodeGen/RuntimeLibcalls.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
56 #include "llvm/CodeGen/StackMaps.h"
57 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
58 #include "llvm/CodeGen/TargetFrameLowering.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/CodeGen/WinEHFuncInfo.h"
66 #include "llvm/IR/Argument.h"
67 #include "llvm/IR/Attributes.h"
68 #include "llvm/IR/BasicBlock.h"
69 #include "llvm/IR/CFG.h"
70 #include "llvm/IR/CallSite.h"
71 #include "llvm/IR/CallingConv.h"
72 #include "llvm/IR/Constant.h"
73 #include "llvm/IR/ConstantRange.h"
74 #include "llvm/IR/Constants.h"
75 #include "llvm/IR/DataLayout.h"
76 #include "llvm/IR/DebugInfoMetadata.h"
77 #include "llvm/IR/DebugLoc.h"
78 #include "llvm/IR/DerivedTypes.h"
79 #include "llvm/IR/Function.h"
80 #include "llvm/IR/GetElementPtrTypeIterator.h"
81 #include "llvm/IR/InlineAsm.h"
82 #include "llvm/IR/InstrTypes.h"
83 #include "llvm/IR/Instruction.h"
84 #include "llvm/IR/Instructions.h"
85 #include "llvm/IR/IntrinsicInst.h"
86 #include "llvm/IR/Intrinsics.h"
87 #include "llvm/IR/LLVMContext.h"
88 #include "llvm/IR/Metadata.h"
89 #include "llvm/IR/Module.h"
90 #include "llvm/IR/Operator.h"
91 #include "llvm/IR/PatternMatch.h"
92 #include "llvm/IR/Statepoint.h"
93 #include "llvm/IR/Type.h"
94 #include "llvm/IR/User.h"
95 #include "llvm/IR/Value.h"
96 #include "llvm/MC/MCContext.h"
97 #include "llvm/MC/MCSymbol.h"
98 #include "llvm/Support/AtomicOrdering.h"
99 #include "llvm/Support/BranchProbability.h"
100 #include "llvm/Support/Casting.h"
101 #include "llvm/Support/CodeGen.h"
102 #include "llvm/Support/CommandLine.h"
103 #include "llvm/Support/Compiler.h"
104 #include "llvm/Support/Debug.h"
105 #include "llvm/Support/ErrorHandling.h"
106 #include "llvm/Support/MachineValueType.h"
107 #include "llvm/Support/MathExtras.h"
108 #include "llvm/Support/raw_ostream.h"
109 #include "llvm/Target/TargetIntrinsicInfo.h"
110 #include "llvm/Target/TargetMachine.h"
111 #include "llvm/Target/TargetOptions.h"
112 #include "llvm/Transforms/Utils/Local.h"
113 #include <algorithm>
114 #include <cassert>
115 #include <cstddef>
116 #include <cstdint>
117 #include <cstring>
118 #include <iterator>
119 #include <limits>
120 #include <numeric>
121 #include <tuple>
122 #include <utility>
123 #include <vector>
124 
125 using namespace llvm;
126 using namespace PatternMatch;
127 
128 #define DEBUG_TYPE "isel"
129 
130 /// LimitFloatPrecision - Generate low-precision inline sequences for
131 /// some float libcalls (6, 8 or 12 bits).
132 static unsigned LimitFloatPrecision;
133 
134 static cl::opt<unsigned, true>
135     LimitFPPrecision("limit-float-precision",
136                      cl::desc("Generate low-precision inline sequences "
137                               "for some float libcalls"),
138                      cl::location(LimitFloatPrecision), cl::Hidden,
139                      cl::init(0));
140 
141 static cl::opt<unsigned> SwitchPeelThreshold(
142     "switch-peel-threshold", cl::Hidden, cl::init(66),
143     cl::desc("Set the case probability threshold for peeling the case from a "
144              "switch statement. A value greater than 100 will void this "
145              "optimization"));
146 
147 // Limit the width of DAG chains. This is important in general to prevent
148 // DAG-based analysis from blowing up. For example, alias analysis and
149 // load clustering may not complete in reasonable time. It is difficult to
150 // recognize and avoid this situation within each individual analysis, and
151 // future analyses are likely to have the same behavior. Limiting DAG width is
152 // the safe approach and will be especially important with global DAGs.
153 //
154 // MaxParallelChains default is arbitrarily high to avoid affecting
155 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
156 // sequence over this should have been converted to llvm.memcpy by the
157 // frontend. It is easy to induce this behavior with .ll code such as:
158 // %buffer = alloca [4096 x i8]
159 // %data = load [4096 x i8]* %argPtr
160 // store [4096 x i8] %data, [4096 x i8]* %buffer
161 static const unsigned MaxParallelChains = 64;
162 
163 // Return the calling convention if the Value passed requires ABI mangling as it
164 // is a parameter to a function or a return value from a function which is not
165 // an intrinsic.
166 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
167   if (auto *R = dyn_cast<ReturnInst>(V))
168     return R->getParent()->getParent()->getCallingConv();
169 
170   if (auto *CI = dyn_cast<CallInst>(V)) {
171     const bool IsInlineAsm = CI->isInlineAsm();
172     const bool IsIndirectFunctionCall =
173         !IsInlineAsm && !CI->getCalledFunction();
174 
175     // It is possible that the call instruction is an inline asm statement or an
176     // indirect function call in which case the return value of
177     // getCalledFunction() would be nullptr.
178     const bool IsInstrinsicCall =
179         !IsInlineAsm && !IsIndirectFunctionCall &&
180         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
181 
182     if (!IsInlineAsm && !IsInstrinsicCall)
183       return CI->getCallingConv();
184   }
185 
186   return None;
187 }
188 
189 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
190                                       const SDValue *Parts, unsigned NumParts,
191                                       MVT PartVT, EVT ValueVT, const Value *V,
192                                       Optional<CallingConv::ID> CC);
193 
194 /// getCopyFromParts - Create a value that contains the specified legal parts
195 /// combined into the value they represent.  If the parts combine to a type
196 /// larger than ValueVT then AssertOp can be used to specify whether the extra
197 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
198 /// (ISD::AssertSext).
199 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
200                                 const SDValue *Parts, unsigned NumParts,
201                                 MVT PartVT, EVT ValueVT, const Value *V,
202                                 Optional<CallingConv::ID> CC = None,
203                                 Optional<ISD::NodeType> AssertOp = None) {
204   if (ValueVT.isVector())
205     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
206                                   CC);
207 
208   assert(NumParts > 0 && "No parts to assemble!");
209   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
210   SDValue Val = Parts[0];
211 
212   if (NumParts > 1) {
213     // Assemble the value from multiple parts.
214     if (ValueVT.isInteger()) {
215       unsigned PartBits = PartVT.getSizeInBits();
216       unsigned ValueBits = ValueVT.getSizeInBits();
217 
218       // Assemble the power of 2 part.
219       unsigned RoundParts =
220           (NumParts & (NumParts - 1)) ? 1 << Log2_32(NumParts) : NumParts;
221       unsigned RoundBits = PartBits * RoundParts;
222       EVT RoundVT = RoundBits == ValueBits ?
223         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
224       SDValue Lo, Hi;
225 
226       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
227 
228       if (RoundParts > 2) {
229         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
230                               PartVT, HalfVT, V);
231         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
232                               RoundParts / 2, PartVT, HalfVT, V);
233       } else {
234         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
235         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
236       }
237 
238       if (DAG.getDataLayout().isBigEndian())
239         std::swap(Lo, Hi);
240 
241       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
242 
243       if (RoundParts < NumParts) {
244         // Assemble the trailing non-power-of-2 part.
245         unsigned OddParts = NumParts - RoundParts;
246         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
247         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
248                               OddVT, V, CC);
249 
250         // Combine the round and odd parts.
251         Lo = Val;
252         if (DAG.getDataLayout().isBigEndian())
253           std::swap(Lo, Hi);
254         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
255         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
256         Hi =
257             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
258                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
259                                         TLI.getPointerTy(DAG.getDataLayout())));
260         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
261         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
262       }
263     } else if (PartVT.isFloatingPoint()) {
264       // FP split into multiple FP parts (for ppcf128)
265       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
266              "Unexpected split");
267       SDValue Lo, Hi;
268       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
269       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
270       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
271         std::swap(Lo, Hi);
272       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
273     } else {
274       // FP split into integer parts (soft fp)
275       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
276              !PartVT.isVector() && "Unexpected split");
277       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
278       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
279     }
280   }
281 
282   // There is now one part, held in Val.  Correct it to match ValueVT.
283   // PartEVT is the type of the register class that holds the value.
284   // ValueVT is the type of the inline asm operation.
285   EVT PartEVT = Val.getValueType();
286 
287   if (PartEVT == ValueVT)
288     return Val;
289 
290   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
291       ValueVT.bitsLT(PartEVT)) {
292     // For an FP value in an integer part, we need to truncate to the right
293     // width first.
294     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
295     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
296   }
297 
298   // Handle types that have the same size.
299   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
300     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
301 
302   // Handle types with different sizes.
303   if (PartEVT.isInteger() && ValueVT.isInteger()) {
304     if (ValueVT.bitsLT(PartEVT)) {
305       // For a truncate, see if we have any information to
306       // indicate whether the truncated bits will always be
307       // zero or sign-extension.
308       if (AssertOp.hasValue())
309         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
310                           DAG.getValueType(ValueVT));
311       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
312     }
313     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
314   }
315 
316   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
317     // FP_ROUND's are always exact here.
318     if (ValueVT.bitsLT(Val.getValueType()))
319       return DAG.getNode(
320           ISD::FP_ROUND, DL, ValueVT, Val,
321           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
322 
323     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
324   }
325 
326   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
327   // then truncating.
328   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
329       ValueVT.bitsLT(PartEVT)) {
330     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
331     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
332   }
333 
334   report_fatal_error("Unknown mismatch in getCopyFromParts!");
335 }
336 
337 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
338                                               const Twine &ErrMsg) {
339   const Instruction *I = dyn_cast_or_null<Instruction>(V);
340   if (!V)
341     return Ctx.emitError(ErrMsg);
342 
343   const char *AsmError = ", possible invalid constraint for vector type";
344   if (const CallInst *CI = dyn_cast<CallInst>(I))
345     if (isa<InlineAsm>(CI->getCalledValue()))
346       return Ctx.emitError(I, ErrMsg + AsmError);
347 
348   return Ctx.emitError(I, ErrMsg);
349 }
350 
351 /// getCopyFromPartsVector - Create a value that contains the specified legal
352 /// parts combined into the value they represent.  If the parts combine to a
353 /// type larger than ValueVT then AssertOp can be used to specify whether the
354 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
355 /// ValueVT (ISD::AssertSext).
356 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
357                                       const SDValue *Parts, unsigned NumParts,
358                                       MVT PartVT, EVT ValueVT, const Value *V,
359                                       Optional<CallingConv::ID> CallConv) {
360   assert(ValueVT.isVector() && "Not a vector value");
361   assert(NumParts > 0 && "No parts to assemble!");
362   const bool IsABIRegCopy = CallConv.hasValue();
363 
364   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
365   SDValue Val = Parts[0];
366 
367   // Handle a multi-element vector.
368   if (NumParts > 1) {
369     EVT IntermediateVT;
370     MVT RegisterVT;
371     unsigned NumIntermediates;
372     unsigned NumRegs;
373 
374     if (IsABIRegCopy) {
375       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
376           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
377           NumIntermediates, RegisterVT);
378     } else {
379       NumRegs =
380           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
381                                      NumIntermediates, RegisterVT);
382     }
383 
384     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
385     NumParts = NumRegs; // Silence a compiler warning.
386     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
387     assert(RegisterVT.getSizeInBits() ==
388            Parts[0].getSimpleValueType().getSizeInBits() &&
389            "Part type sizes don't match!");
390 
391     // Assemble the parts into intermediate operands.
392     SmallVector<SDValue, 8> Ops(NumIntermediates);
393     if (NumIntermediates == NumParts) {
394       // If the register was not expanded, truncate or copy the value,
395       // as appropriate.
396       for (unsigned i = 0; i != NumParts; ++i)
397         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
398                                   PartVT, IntermediateVT, V);
399     } else if (NumParts > 0) {
400       // If the intermediate type was expanded, build the intermediate
401       // operands from the parts.
402       assert(NumParts % NumIntermediates == 0 &&
403              "Must expand into a divisible number of parts!");
404       unsigned Factor = NumParts / NumIntermediates;
405       for (unsigned i = 0; i != NumIntermediates; ++i)
406         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
407                                   PartVT, IntermediateVT, V);
408     }
409 
410     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
411     // intermediate operands.
412     EVT BuiltVectorTy =
413         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
414                          (IntermediateVT.isVector()
415                               ? IntermediateVT.getVectorNumElements() * NumParts
416                               : NumIntermediates));
417     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
418                                                 : ISD::BUILD_VECTOR,
419                       DL, BuiltVectorTy, Ops);
420   }
421 
422   // There is now one part, held in Val.  Correct it to match ValueVT.
423   EVT PartEVT = Val.getValueType();
424 
425   if (PartEVT == ValueVT)
426     return Val;
427 
428   if (PartEVT.isVector()) {
429     // If the element type of the source/dest vectors are the same, but the
430     // parts vector has more elements than the value vector, then we have a
431     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
432     // elements we want.
433     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
434       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
435              "Cannot narrow, it would be a lossy transformation");
436       return DAG.getNode(
437           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
438           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
439     }
440 
441     // Vector/Vector bitcast.
442     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
443       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
444 
445     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
446       "Cannot handle this kind of promotion");
447     // Promoted vector extract
448     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
449 
450   }
451 
452   // Trivial bitcast if the types are the same size and the destination
453   // vector type is legal.
454   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
455       TLI.isTypeLegal(ValueVT))
456     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
457 
458   if (ValueVT.getVectorNumElements() != 1) {
459      // Certain ABIs require that vectors are passed as integers. For vectors
460      // are the same size, this is an obvious bitcast.
461      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
462        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
463      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
464        // Bitcast Val back the original type and extract the corresponding
465        // vector we want.
466        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
467        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
468                                            ValueVT.getVectorElementType(), Elts);
469        Val = DAG.getBitcast(WiderVecType, Val);
470        return DAG.getNode(
471            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
472            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
473      }
474 
475      diagnosePossiblyInvalidConstraint(
476          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
477      return DAG.getUNDEF(ValueVT);
478   }
479 
480   // Handle cases such as i8 -> <1 x i1>
481   EVT ValueSVT = ValueVT.getVectorElementType();
482   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
483     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
484                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
485 
486   return DAG.getBuildVector(ValueVT, DL, Val);
487 }
488 
489 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
490                                  SDValue Val, SDValue *Parts, unsigned NumParts,
491                                  MVT PartVT, const Value *V,
492                                  Optional<CallingConv::ID> CallConv);
493 
494 /// getCopyToParts - Create a series of nodes that contain the specified value
495 /// split into legal parts.  If the parts contain more bits than Val, then, for
496 /// integers, ExtendKind can be used to specify how to generate the extra bits.
497 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
498                            SDValue *Parts, unsigned NumParts, MVT PartVT,
499                            const Value *V,
500                            Optional<CallingConv::ID> CallConv = None,
501                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
502   EVT ValueVT = Val.getValueType();
503 
504   // Handle the vector case separately.
505   if (ValueVT.isVector())
506     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
507                                 CallConv);
508 
509   unsigned PartBits = PartVT.getSizeInBits();
510   unsigned OrigNumParts = NumParts;
511   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
512          "Copying to an illegal type!");
513 
514   if (NumParts == 0)
515     return;
516 
517   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
518   EVT PartEVT = PartVT;
519   if (PartEVT == ValueVT) {
520     assert(NumParts == 1 && "No-op copy with multiple parts!");
521     Parts[0] = Val;
522     return;
523   }
524 
525   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
526     // If the parts cover more bits than the value has, promote the value.
527     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
528       assert(NumParts == 1 && "Do not know what to promote to!");
529       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
530     } else {
531       if (ValueVT.isFloatingPoint()) {
532         // FP values need to be bitcast, then extended if they are being put
533         // into a larger container.
534         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
535         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
536       }
537       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
538              ValueVT.isInteger() &&
539              "Unknown mismatch!");
540       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
541       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
542       if (PartVT == MVT::x86mmx)
543         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
544     }
545   } else if (PartBits == ValueVT.getSizeInBits()) {
546     // Different types of the same size.
547     assert(NumParts == 1 && PartEVT != ValueVT);
548     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
549   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
550     // If the parts cover less bits than value has, truncate the value.
551     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
552            ValueVT.isInteger() &&
553            "Unknown mismatch!");
554     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
555     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
556     if (PartVT == MVT::x86mmx)
557       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
558   }
559 
560   // The value may have changed - recompute ValueVT.
561   ValueVT = Val.getValueType();
562   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
563          "Failed to tile the value with PartVT!");
564 
565   if (NumParts == 1) {
566     if (PartEVT != ValueVT) {
567       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
568                                         "scalar-to-vector conversion failed");
569       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
570     }
571 
572     Parts[0] = Val;
573     return;
574   }
575 
576   // Expand the value into multiple parts.
577   if (NumParts & (NumParts - 1)) {
578     // The number of parts is not a power of 2.  Split off and copy the tail.
579     assert(PartVT.isInteger() && ValueVT.isInteger() &&
580            "Do not know what to expand to!");
581     unsigned RoundParts = 1 << Log2_32(NumParts);
582     unsigned RoundBits = RoundParts * PartBits;
583     unsigned OddParts = NumParts - RoundParts;
584     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
585       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL, /*LegalTypes*/false));
586 
587     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
588                    CallConv);
589 
590     if (DAG.getDataLayout().isBigEndian())
591       // The odd parts were reversed by getCopyToParts - unreverse them.
592       std::reverse(Parts + RoundParts, Parts + NumParts);
593 
594     NumParts = RoundParts;
595     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
596     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
597   }
598 
599   // The number of parts is a power of 2.  Repeatedly bisect the value using
600   // EXTRACT_ELEMENT.
601   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
602                          EVT::getIntegerVT(*DAG.getContext(),
603                                            ValueVT.getSizeInBits()),
604                          Val);
605 
606   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
607     for (unsigned i = 0; i < NumParts; i += StepSize) {
608       unsigned ThisBits = StepSize * PartBits / 2;
609       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
610       SDValue &Part0 = Parts[i];
611       SDValue &Part1 = Parts[i+StepSize/2];
612 
613       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
614                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
615       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
616                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
617 
618       if (ThisBits == PartBits && ThisVT != PartVT) {
619         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
620         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
621       }
622     }
623   }
624 
625   if (DAG.getDataLayout().isBigEndian())
626     std::reverse(Parts, Parts + OrigNumParts);
627 }
628 
629 static SDValue widenVectorToPartType(SelectionDAG &DAG,
630                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
631   if (!PartVT.isVector())
632     return SDValue();
633 
634   EVT ValueVT = Val.getValueType();
635   unsigned PartNumElts = PartVT.getVectorNumElements();
636   unsigned ValueNumElts = ValueVT.getVectorNumElements();
637   if (PartNumElts > ValueNumElts &&
638       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
639     EVT ElementVT = PartVT.getVectorElementType();
640     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
641     // undef elements.
642     SmallVector<SDValue, 16> Ops;
643     DAG.ExtractVectorElements(Val, Ops);
644     SDValue EltUndef = DAG.getUNDEF(ElementVT);
645     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
646       Ops.push_back(EltUndef);
647 
648     // FIXME: Use CONCAT for 2x -> 4x.
649     return DAG.getBuildVector(PartVT, DL, Ops);
650   }
651 
652   return SDValue();
653 }
654 
655 /// getCopyToPartsVector - Create a series of nodes that contain the specified
656 /// value split into legal parts.
657 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
658                                  SDValue Val, SDValue *Parts, unsigned NumParts,
659                                  MVT PartVT, const Value *V,
660                                  Optional<CallingConv::ID> CallConv) {
661   EVT ValueVT = Val.getValueType();
662   assert(ValueVT.isVector() && "Not a vector");
663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
664   const bool IsABIRegCopy = CallConv.hasValue();
665 
666   if (NumParts == 1) {
667     EVT PartEVT = PartVT;
668     if (PartEVT == ValueVT) {
669       // Nothing to do.
670     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
671       // Bitconvert vector->vector case.
672       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
673     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
674       Val = Widened;
675     } else if (PartVT.isVector() &&
676                PartEVT.getVectorElementType().bitsGE(
677                  ValueVT.getVectorElementType()) &&
678                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
679 
680       // Promoted vector extract
681       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
682     } else {
683       if (ValueVT.getVectorNumElements() == 1) {
684         Val = DAG.getNode(
685             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
686             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
687       } else {
688         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
689                "lossy conversion of vector to scalar type");
690         EVT IntermediateType =
691             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
692         Val = DAG.getBitcast(IntermediateType, Val);
693         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
694       }
695     }
696 
697     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
698     Parts[0] = Val;
699     return;
700   }
701 
702   // Handle a multi-element vector.
703   EVT IntermediateVT;
704   MVT RegisterVT;
705   unsigned NumIntermediates;
706   unsigned NumRegs;
707   if (IsABIRegCopy) {
708     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
709         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
710         NumIntermediates, RegisterVT);
711   } else {
712     NumRegs =
713         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
714                                    NumIntermediates, RegisterVT);
715   }
716 
717   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
718   NumParts = NumRegs; // Silence a compiler warning.
719   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
720 
721   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
722     IntermediateVT.getVectorNumElements() : 1;
723 
724   // Convert the vector to the appropiate type if necessary.
725   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
726 
727   EVT BuiltVectorTy = EVT::getVectorVT(
728       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
729   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
730   if (ValueVT != BuiltVectorTy) {
731     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
732       Val = Widened;
733 
734     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
735   }
736 
737   // Split the vector into intermediate operands.
738   SmallVector<SDValue, 8> Ops(NumIntermediates);
739   for (unsigned i = 0; i != NumIntermediates; ++i) {
740     if (IntermediateVT.isVector()) {
741       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
742                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
743     } else {
744       Ops[i] = DAG.getNode(
745           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
746           DAG.getConstant(i, DL, IdxVT));
747     }
748   }
749 
750   // Split the intermediate operands into legal parts.
751   if (NumParts == NumIntermediates) {
752     // If the register was not expanded, promote or copy the value,
753     // as appropriate.
754     for (unsigned i = 0; i != NumParts; ++i)
755       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
756   } else if (NumParts > 0) {
757     // If the intermediate type was expanded, split each the value into
758     // legal parts.
759     assert(NumIntermediates != 0 && "division by zero");
760     assert(NumParts % NumIntermediates == 0 &&
761            "Must expand into a divisible number of parts!");
762     unsigned Factor = NumParts / NumIntermediates;
763     for (unsigned i = 0; i != NumIntermediates; ++i)
764       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
765                      CallConv);
766   }
767 }
768 
769 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
770                            EVT valuevt, Optional<CallingConv::ID> CC)
771     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
772       RegCount(1, regs.size()), CallConv(CC) {}
773 
774 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
775                            const DataLayout &DL, unsigned Reg, Type *Ty,
776                            Optional<CallingConv::ID> CC) {
777   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
778 
779   CallConv = CC;
780 
781   for (EVT ValueVT : ValueVTs) {
782     unsigned NumRegs =
783         isABIMangled()
784             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
785             : TLI.getNumRegisters(Context, ValueVT);
786     MVT RegisterVT =
787         isABIMangled()
788             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
789             : TLI.getRegisterType(Context, ValueVT);
790     for (unsigned i = 0; i != NumRegs; ++i)
791       Regs.push_back(Reg + i);
792     RegVTs.push_back(RegisterVT);
793     RegCount.push_back(NumRegs);
794     Reg += NumRegs;
795   }
796 }
797 
798 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
799                                       FunctionLoweringInfo &FuncInfo,
800                                       const SDLoc &dl, SDValue &Chain,
801                                       SDValue *Flag, const Value *V) const {
802   // A Value with type {} or [0 x %t] needs no registers.
803   if (ValueVTs.empty())
804     return SDValue();
805 
806   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
807 
808   // Assemble the legal parts into the final values.
809   SmallVector<SDValue, 4> Values(ValueVTs.size());
810   SmallVector<SDValue, 8> Parts;
811   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
812     // Copy the legal parts from the registers.
813     EVT ValueVT = ValueVTs[Value];
814     unsigned NumRegs = RegCount[Value];
815     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
816                                           *DAG.getContext(),
817                                           CallConv.getValue(), RegVTs[Value])
818                                     : RegVTs[Value];
819 
820     Parts.resize(NumRegs);
821     for (unsigned i = 0; i != NumRegs; ++i) {
822       SDValue P;
823       if (!Flag) {
824         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
825       } else {
826         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
827         *Flag = P.getValue(2);
828       }
829 
830       Chain = P.getValue(1);
831       Parts[i] = P;
832 
833       // If the source register was virtual and if we know something about it,
834       // add an assert node.
835       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
836           !RegisterVT.isInteger())
837         continue;
838 
839       const FunctionLoweringInfo::LiveOutInfo *LOI =
840         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
841       if (!LOI)
842         continue;
843 
844       unsigned RegSize = RegisterVT.getScalarSizeInBits();
845       unsigned NumSignBits = LOI->NumSignBits;
846       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
847 
848       if (NumZeroBits == RegSize) {
849         // The current value is a zero.
850         // Explicitly express that as it would be easier for
851         // optimizations to kick in.
852         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
853         continue;
854       }
855 
856       // FIXME: We capture more information than the dag can represent.  For
857       // now, just use the tightest assertzext/assertsext possible.
858       bool isSExt;
859       EVT FromVT(MVT::Other);
860       if (NumZeroBits) {
861         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
862         isSExt = false;
863       } else if (NumSignBits > 1) {
864         FromVT =
865             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
866         isSExt = true;
867       } else {
868         continue;
869       }
870       // Add an assertion node.
871       assert(FromVT != MVT::Other);
872       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
873                              RegisterVT, P, DAG.getValueType(FromVT));
874     }
875 
876     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
877                                      RegisterVT, ValueVT, V, CallConv);
878     Part += NumRegs;
879     Parts.clear();
880   }
881 
882   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
883 }
884 
885 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
886                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
887                                  const Value *V,
888                                  ISD::NodeType PreferredExtendType) const {
889   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
890   ISD::NodeType ExtendKind = PreferredExtendType;
891 
892   // Get the list of the values's legal parts.
893   unsigned NumRegs = Regs.size();
894   SmallVector<SDValue, 8> Parts(NumRegs);
895   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
896     unsigned NumParts = RegCount[Value];
897 
898     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
899                                           *DAG.getContext(),
900                                           CallConv.getValue(), RegVTs[Value])
901                                     : RegVTs[Value];
902 
903     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
904       ExtendKind = ISD::ZERO_EXTEND;
905 
906     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
907                    NumParts, RegisterVT, V, CallConv, ExtendKind);
908     Part += NumParts;
909   }
910 
911   // Copy the parts into the registers.
912   SmallVector<SDValue, 8> Chains(NumRegs);
913   for (unsigned i = 0; i != NumRegs; ++i) {
914     SDValue Part;
915     if (!Flag) {
916       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
917     } else {
918       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
919       *Flag = Part.getValue(1);
920     }
921 
922     Chains[i] = Part.getValue(0);
923   }
924 
925   if (NumRegs == 1 || Flag)
926     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
927     // flagged to it. That is the CopyToReg nodes and the user are considered
928     // a single scheduling unit. If we create a TokenFactor and return it as
929     // chain, then the TokenFactor is both a predecessor (operand) of the
930     // user as well as a successor (the TF operands are flagged to the user).
931     // c1, f1 = CopyToReg
932     // c2, f2 = CopyToReg
933     // c3     = TokenFactor c1, c2
934     // ...
935     //        = op c3, ..., f2
936     Chain = Chains[NumRegs-1];
937   else
938     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
939 }
940 
941 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
942                                         unsigned MatchingIdx, const SDLoc &dl,
943                                         SelectionDAG &DAG,
944                                         std::vector<SDValue> &Ops) const {
945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
946 
947   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
948   if (HasMatching)
949     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
950   else if (!Regs.empty() &&
951            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
952     // Put the register class of the virtual registers in the flag word.  That
953     // way, later passes can recompute register class constraints for inline
954     // assembly as well as normal instructions.
955     // Don't do this for tied operands that can use the regclass information
956     // from the def.
957     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
958     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
959     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
960   }
961 
962   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
963   Ops.push_back(Res);
964 
965   if (Code == InlineAsm::Kind_Clobber) {
966     // Clobbers should always have a 1:1 mapping with registers, and may
967     // reference registers that have illegal (e.g. vector) types. Hence, we
968     // shouldn't try to apply any sort of splitting logic to them.
969     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
970            "No 1:1 mapping from clobbers to regs?");
971     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
972     (void)SP;
973     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
974       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
975       assert(
976           (Regs[I] != SP ||
977            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
978           "If we clobbered the stack pointer, MFI should know about it.");
979     }
980     return;
981   }
982 
983   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
984     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
985     MVT RegisterVT = RegVTs[Value];
986     for (unsigned i = 0; i != NumRegs; ++i) {
987       assert(Reg < Regs.size() && "Mismatch in # registers expected");
988       unsigned TheReg = Regs[Reg++];
989       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
990     }
991   }
992 }
993 
994 SmallVector<std::pair<unsigned, unsigned>, 4>
995 RegsForValue::getRegsAndSizes() const {
996   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
997   unsigned I = 0;
998   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
999     unsigned RegCount = std::get<0>(CountAndVT);
1000     MVT RegisterVT = std::get<1>(CountAndVT);
1001     unsigned RegisterSize = RegisterVT.getSizeInBits();
1002     for (unsigned E = I + RegCount; I != E; ++I)
1003       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1004   }
1005   return OutVec;
1006 }
1007 
1008 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1009                                const TargetLibraryInfo *li) {
1010   AA = aa;
1011   GFI = gfi;
1012   LibInfo = li;
1013   DL = &DAG.getDataLayout();
1014   Context = DAG.getContext();
1015   LPadToCallSiteMap.clear();
1016 }
1017 
1018 void SelectionDAGBuilder::clear() {
1019   NodeMap.clear();
1020   UnusedArgNodeMap.clear();
1021   PendingLoads.clear();
1022   PendingExports.clear();
1023   CurInst = nullptr;
1024   HasTailCall = false;
1025   SDNodeOrder = LowestSDNodeOrder;
1026   StatepointLowering.clear();
1027 }
1028 
1029 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1030   DanglingDebugInfoMap.clear();
1031 }
1032 
1033 SDValue SelectionDAGBuilder::getRoot() {
1034   if (PendingLoads.empty())
1035     return DAG.getRoot();
1036 
1037   if (PendingLoads.size() == 1) {
1038     SDValue Root = PendingLoads[0];
1039     DAG.setRoot(Root);
1040     PendingLoads.clear();
1041     return Root;
1042   }
1043 
1044   // Otherwise, we have to make a token factor node.
1045   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1046   PendingLoads.clear();
1047   DAG.setRoot(Root);
1048   return Root;
1049 }
1050 
1051 SDValue SelectionDAGBuilder::getControlRoot() {
1052   SDValue Root = DAG.getRoot();
1053 
1054   if (PendingExports.empty())
1055     return Root;
1056 
1057   // Turn all of the CopyToReg chains into one factored node.
1058   if (Root.getOpcode() != ISD::EntryToken) {
1059     unsigned i = 0, e = PendingExports.size();
1060     for (; i != e; ++i) {
1061       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1062       if (PendingExports[i].getNode()->getOperand(0) == Root)
1063         break;  // Don't add the root if we already indirectly depend on it.
1064     }
1065 
1066     if (i == e)
1067       PendingExports.push_back(Root);
1068   }
1069 
1070   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1071                      PendingExports);
1072   PendingExports.clear();
1073   DAG.setRoot(Root);
1074   return Root;
1075 }
1076 
1077 void SelectionDAGBuilder::visit(const Instruction &I) {
1078   // Set up outgoing PHI node register values before emitting the terminator.
1079   if (I.isTerminator()) {
1080     HandlePHINodesInSuccessorBlocks(I.getParent());
1081   }
1082 
1083   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1084   if (!isa<DbgInfoIntrinsic>(I))
1085     ++SDNodeOrder;
1086 
1087   CurInst = &I;
1088 
1089   visit(I.getOpcode(), I);
1090 
1091   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1092     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1093     // maps to this instruction.
1094     // TODO: We could handle all flags (nsw, etc) here.
1095     // TODO: If an IR instruction maps to >1 node, only the final node will have
1096     //       flags set.
1097     if (SDNode *Node = getNodeForIRValue(&I)) {
1098       SDNodeFlags IncomingFlags;
1099       IncomingFlags.copyFMF(*FPMO);
1100       if (!Node->getFlags().isDefined())
1101         Node->setFlags(IncomingFlags);
1102       else
1103         Node->intersectFlagsWith(IncomingFlags);
1104     }
1105   }
1106 
1107   if (!I.isTerminator() && !HasTailCall &&
1108       !isStatepoint(&I)) // statepoints handle their exports internally
1109     CopyToExportRegsIfNeeded(&I);
1110 
1111   CurInst = nullptr;
1112 }
1113 
1114 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1115   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1116 }
1117 
1118 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1119   // Note: this doesn't use InstVisitor, because it has to work with
1120   // ConstantExpr's in addition to instructions.
1121   switch (Opcode) {
1122   default: llvm_unreachable("Unknown instruction type encountered!");
1123     // Build the switch statement using the Instruction.def file.
1124 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1125     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1126 #include "llvm/IR/Instruction.def"
1127   }
1128 }
1129 
1130 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1131                                                 const DIExpression *Expr) {
1132   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1133     const DbgValueInst *DI = DDI.getDI();
1134     DIVariable *DanglingVariable = DI->getVariable();
1135     DIExpression *DanglingExpr = DI->getExpression();
1136     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1137       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1138       return true;
1139     }
1140     return false;
1141   };
1142 
1143   for (auto &DDIMI : DanglingDebugInfoMap) {
1144     DanglingDebugInfoVector &DDIV = DDIMI.second;
1145 
1146     // If debug info is to be dropped, run it through final checks to see
1147     // whether it can be salvaged.
1148     for (auto &DDI : DDIV)
1149       if (isMatchingDbgValue(DDI))
1150         salvageUnresolvedDbgValue(DDI);
1151 
1152     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1153   }
1154 }
1155 
1156 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1157 // generate the debug data structures now that we've seen its definition.
1158 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1159                                                    SDValue Val) {
1160   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1161   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1162     return;
1163 
1164   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1165   for (auto &DDI : DDIV) {
1166     const DbgValueInst *DI = DDI.getDI();
1167     assert(DI && "Ill-formed DanglingDebugInfo");
1168     DebugLoc dl = DDI.getdl();
1169     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1170     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1171     DILocalVariable *Variable = DI->getVariable();
1172     DIExpression *Expr = DI->getExpression();
1173     assert(Variable->isValidLocationForIntrinsic(dl) &&
1174            "Expected inlined-at fields to agree");
1175     SDDbgValue *SDV;
1176     if (Val.getNode()) {
1177       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1178       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1179       // we couldn't resolve it directly when examining the DbgValue intrinsic
1180       // in the first place we should not be more successful here). Unless we
1181       // have some test case that prove this to be correct we should avoid
1182       // calling EmitFuncArgumentDbgValue here.
1183       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1184         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1185                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1186         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1187         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1188         // inserted after the definition of Val when emitting the instructions
1189         // after ISel. An alternative could be to teach
1190         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1191         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1192                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1193                    << ValSDNodeOrder << "\n");
1194         SDV = getDbgValue(Val, Variable, Expr, dl,
1195                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1196         DAG.AddDbgValue(SDV, Val.getNode(), false);
1197       } else
1198         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1199                           << "in EmitFuncArgumentDbgValue\n");
1200     } else {
1201       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1202       auto Undef =
1203           UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1204       auto SDV =
1205           DAG.getConstantDbgValue(Variable, Expr, Undef, dl, DbgSDNodeOrder);
1206       DAG.AddDbgValue(SDV, nullptr, false);
1207     }
1208   }
1209   DDIV.clear();
1210 }
1211 
1212 void SelectionDAGBuilder::salvageUnresolvedDbgValue(DanglingDebugInfo &DDI) {
1213   Value *V = DDI.getDI()->getValue();
1214   DILocalVariable *Var = DDI.getDI()->getVariable();
1215   DIExpression *Expr = DDI.getDI()->getExpression();
1216   DebugLoc DL = DDI.getdl();
1217   DebugLoc InstDL = DDI.getDI()->getDebugLoc();
1218   unsigned SDOrder = DDI.getSDNodeOrder();
1219 
1220   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1221   // that DW_OP_stack_value is desired.
1222   assert(isa<DbgValueInst>(DDI.getDI()));
1223   bool StackValue = true;
1224 
1225   // Can this Value can be encoded without any further work?
1226   if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder))
1227     return;
1228 
1229   // Attempt to salvage back through as many instructions as possible. Bail if
1230   // a non-instruction is seen, such as a constant expression or global
1231   // variable. FIXME: Further work could recover those too.
1232   while (isa<Instruction>(V)) {
1233     Instruction &VAsInst = *cast<Instruction>(V);
1234     DIExpression *NewExpr = salvageDebugInfoImpl(VAsInst, Expr, StackValue);
1235 
1236     // If we cannot salvage any further, and haven't yet found a suitable debug
1237     // expression, bail out.
1238     if (!NewExpr)
1239       break;
1240 
1241     // New value and expr now represent this debuginfo.
1242     V = VAsInst.getOperand(0);
1243     Expr = NewExpr;
1244 
1245     // Some kind of simplification occurred: check whether the operand of the
1246     // salvaged debug expression can be encoded in this DAG.
1247     if (handleDebugValue(V, Var, Expr, DL, InstDL, SDOrder)) {
1248       LLVM_DEBUG(dbgs() << "Salvaged debug location info for:\n  "
1249                         << DDI.getDI() << "\nBy stripping back to:\n  " << V);
1250       return;
1251     }
1252   }
1253 
1254   // This was the final opportunity to salvage this debug information, and it
1255   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1256   // any earlier variable location.
1257   auto Undef = UndefValue::get(DDI.getDI()->getVariableLocation()->getType());
1258   auto SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1259   DAG.AddDbgValue(SDV, nullptr, false);
1260 
1261   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  " << DDI.getDI()
1262                     << "\n");
1263   LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *DDI.getDI()->getOperand(0)
1264                     << "\n");
1265 }
1266 
1267 bool SelectionDAGBuilder::handleDebugValue(const Value *V, DILocalVariable *Var,
1268                                            DIExpression *Expr, DebugLoc dl,
1269                                            DebugLoc InstDL, unsigned Order) {
1270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1271   SDDbgValue *SDV;
1272   if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1273       isa<ConstantPointerNull>(V)) {
1274     SDV = DAG.getConstantDbgValue(Var, Expr, V, dl, SDNodeOrder);
1275     DAG.AddDbgValue(SDV, nullptr, false);
1276     return true;
1277   }
1278 
1279   // If the Value is a frame index, we can create a FrameIndex debug value
1280   // without relying on the DAG at all.
1281   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1282     auto SI = FuncInfo.StaticAllocaMap.find(AI);
1283     if (SI != FuncInfo.StaticAllocaMap.end()) {
1284       auto SDV =
1285           DAG.getFrameIndexDbgValue(Var, Expr, SI->second,
1286                                     /*IsIndirect*/ false, dl, SDNodeOrder);
1287       // Do not attach the SDNodeDbgValue to an SDNode: this variable location
1288       // is still available even if the SDNode gets optimized out.
1289       DAG.AddDbgValue(SDV, nullptr, false);
1290       return true;
1291     }
1292   }
1293 
1294   // Do not use getValue() in here; we don't want to generate code at
1295   // this point if it hasn't been done yet.
1296   SDValue N = NodeMap[V];
1297   if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1298     N = UnusedArgNodeMap[V];
1299   if (N.getNode()) {
1300     if (EmitFuncArgumentDbgValue(V, Var, Expr, dl, false, N))
1301       return true;
1302     SDV = getDbgValue(N, Var, Expr, dl, SDNodeOrder);
1303     DAG.AddDbgValue(SDV, N.getNode(), false);
1304     return true;
1305   }
1306 
1307   // Special rules apply for the first dbg.values of parameter variables in a
1308   // function. Identify them by the fact they reference Argument Values, that
1309   // they're parameters, and they are parameters of the current function. We
1310   // need to let them dangle until they get an SDNode.
1311   bool IsParamOfFunc = isa<Argument>(V) && Var->isParameter() &&
1312                        !InstDL.getInlinedAt();
1313   if (!IsParamOfFunc) {
1314     // The value is not used in this block yet (or it would have an SDNode).
1315     // We still want the value to appear for the user if possible -- if it has
1316     // an associated VReg, we can refer to that instead.
1317     auto VMI = FuncInfo.ValueMap.find(V);
1318     if (VMI != FuncInfo.ValueMap.end()) {
1319       unsigned Reg = VMI->second;
1320       // If this is a PHI node, it may be split up into several MI PHI nodes
1321       // (in FunctionLoweringInfo::set).
1322       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1323                        V->getType(), None);
1324       if (RFV.occupiesMultipleRegs()) {
1325         unsigned Offset = 0;
1326         unsigned BitsToDescribe = 0;
1327         if (auto VarSize = Var->getSizeInBits())
1328           BitsToDescribe = *VarSize;
1329         if (auto Fragment = Expr->getFragmentInfo())
1330           BitsToDescribe = Fragment->SizeInBits;
1331         for (auto RegAndSize : RFV.getRegsAndSizes()) {
1332           unsigned RegisterSize = RegAndSize.second;
1333           // Bail out if all bits are described already.
1334           if (Offset >= BitsToDescribe)
1335             break;
1336           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1337               ? BitsToDescribe - Offset
1338               : RegisterSize;
1339           auto FragmentExpr = DIExpression::createFragmentExpression(
1340               Expr, Offset, FragmentSize);
1341           if (!FragmentExpr)
1342               continue;
1343           SDV = DAG.getVRegDbgValue(Var, *FragmentExpr, RegAndSize.first,
1344                                     false, dl, SDNodeOrder);
1345           DAG.AddDbgValue(SDV, nullptr, false);
1346           Offset += RegisterSize;
1347         }
1348       } else {
1349         SDV = DAG.getVRegDbgValue(Var, Expr, Reg, false, dl, SDNodeOrder);
1350         DAG.AddDbgValue(SDV, nullptr, false);
1351       }
1352       return true;
1353     }
1354   }
1355 
1356   return false;
1357 }
1358 
1359 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1360   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1361   for (auto &Pair : DanglingDebugInfoMap)
1362     for (auto &DDI : Pair.second)
1363       salvageUnresolvedDbgValue(DDI);
1364   clearDanglingDebugInfo();
1365 }
1366 
1367 /// getCopyFromRegs - If there was virtual register allocated for the value V
1368 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1369 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1370   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1371   SDValue Result;
1372 
1373   if (It != FuncInfo.ValueMap.end()) {
1374     unsigned InReg = It->second;
1375 
1376     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1377                      DAG.getDataLayout(), InReg, Ty,
1378                      None); // This is not an ABI copy.
1379     SDValue Chain = DAG.getEntryNode();
1380     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1381                                  V);
1382     resolveDanglingDebugInfo(V, Result);
1383   }
1384 
1385   return Result;
1386 }
1387 
1388 /// getValue - Return an SDValue for the given Value.
1389 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1390   // If we already have an SDValue for this value, use it. It's important
1391   // to do this first, so that we don't create a CopyFromReg if we already
1392   // have a regular SDValue.
1393   SDValue &N = NodeMap[V];
1394   if (N.getNode()) return N;
1395 
1396   // If there's a virtual register allocated and initialized for this
1397   // value, use it.
1398   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1399     return copyFromReg;
1400 
1401   // Otherwise create a new SDValue and remember it.
1402   SDValue Val = getValueImpl(V);
1403   NodeMap[V] = Val;
1404   resolveDanglingDebugInfo(V, Val);
1405   return Val;
1406 }
1407 
1408 // Return true if SDValue exists for the given Value
1409 bool SelectionDAGBuilder::findValue(const Value *V) const {
1410   return (NodeMap.find(V) != NodeMap.end()) ||
1411     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1412 }
1413 
1414 /// getNonRegisterValue - Return an SDValue for the given Value, but
1415 /// don't look in FuncInfo.ValueMap for a virtual register.
1416 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1417   // If we already have an SDValue for this value, use it.
1418   SDValue &N = NodeMap[V];
1419   if (N.getNode()) {
1420     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1421       // Remove the debug location from the node as the node is about to be used
1422       // in a location which may differ from the original debug location.  This
1423       // is relevant to Constant and ConstantFP nodes because they can appear
1424       // as constant expressions inside PHI nodes.
1425       N->setDebugLoc(DebugLoc());
1426     }
1427     return N;
1428   }
1429 
1430   // Otherwise create a new SDValue and remember it.
1431   SDValue Val = getValueImpl(V);
1432   NodeMap[V] = Val;
1433   resolveDanglingDebugInfo(V, Val);
1434   return Val;
1435 }
1436 
1437 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1438 /// Create an SDValue for the given value.
1439 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1441 
1442   if (const Constant *C = dyn_cast<Constant>(V)) {
1443     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1444 
1445     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1446       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1447 
1448     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1449       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1450 
1451     if (isa<ConstantPointerNull>(C)) {
1452       unsigned AS = V->getType()->getPointerAddressSpace();
1453       return DAG.getConstant(0, getCurSDLoc(),
1454                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1455     }
1456 
1457     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1458       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1459 
1460     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1461       return DAG.getUNDEF(VT);
1462 
1463     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1464       visit(CE->getOpcode(), *CE);
1465       SDValue N1 = NodeMap[V];
1466       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1467       return N1;
1468     }
1469 
1470     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1471       SmallVector<SDValue, 4> Constants;
1472       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1473            OI != OE; ++OI) {
1474         SDNode *Val = getValue(*OI).getNode();
1475         // If the operand is an empty aggregate, there are no values.
1476         if (!Val) continue;
1477         // Add each leaf value from the operand to the Constants list
1478         // to form a flattened list of all the values.
1479         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1480           Constants.push_back(SDValue(Val, i));
1481       }
1482 
1483       return DAG.getMergeValues(Constants, getCurSDLoc());
1484     }
1485 
1486     if (const ConstantDataSequential *CDS =
1487           dyn_cast<ConstantDataSequential>(C)) {
1488       SmallVector<SDValue, 4> Ops;
1489       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1490         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1491         // Add each leaf value from the operand to the Constants list
1492         // to form a flattened list of all the values.
1493         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1494           Ops.push_back(SDValue(Val, i));
1495       }
1496 
1497       if (isa<ArrayType>(CDS->getType()))
1498         return DAG.getMergeValues(Ops, getCurSDLoc());
1499       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1500     }
1501 
1502     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1503       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1504              "Unknown struct or array constant!");
1505 
1506       SmallVector<EVT, 4> ValueVTs;
1507       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1508       unsigned NumElts = ValueVTs.size();
1509       if (NumElts == 0)
1510         return SDValue(); // empty struct
1511       SmallVector<SDValue, 4> Constants(NumElts);
1512       for (unsigned i = 0; i != NumElts; ++i) {
1513         EVT EltVT = ValueVTs[i];
1514         if (isa<UndefValue>(C))
1515           Constants[i] = DAG.getUNDEF(EltVT);
1516         else if (EltVT.isFloatingPoint())
1517           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1518         else
1519           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1520       }
1521 
1522       return DAG.getMergeValues(Constants, getCurSDLoc());
1523     }
1524 
1525     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1526       return DAG.getBlockAddress(BA, VT);
1527 
1528     VectorType *VecTy = cast<VectorType>(V->getType());
1529     unsigned NumElements = VecTy->getNumElements();
1530 
1531     // Now that we know the number and type of the elements, get that number of
1532     // elements into the Ops array based on what kind of constant it is.
1533     SmallVector<SDValue, 16> Ops;
1534     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1535       for (unsigned i = 0; i != NumElements; ++i)
1536         Ops.push_back(getValue(CV->getOperand(i)));
1537     } else {
1538       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1539       EVT EltVT =
1540           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1541 
1542       SDValue Op;
1543       if (EltVT.isFloatingPoint())
1544         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1545       else
1546         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1547       Ops.assign(NumElements, Op);
1548     }
1549 
1550     // Create a BUILD_VECTOR node.
1551     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1552   }
1553 
1554   // If this is a static alloca, generate it as the frameindex instead of
1555   // computation.
1556   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1557     DenseMap<const AllocaInst*, int>::iterator SI =
1558       FuncInfo.StaticAllocaMap.find(AI);
1559     if (SI != FuncInfo.StaticAllocaMap.end())
1560       return DAG.getFrameIndex(SI->second,
1561                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1562   }
1563 
1564   // If this is an instruction which fast-isel has deferred, select it now.
1565   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1566     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1567 
1568     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1569                      Inst->getType(), getABIRegCopyCC(V));
1570     SDValue Chain = DAG.getEntryNode();
1571     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1572   }
1573 
1574   llvm_unreachable("Can't get register for value!");
1575 }
1576 
1577 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1578   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1579   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1580   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1581   bool IsSEH = isAsynchronousEHPersonality(Pers);
1582   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1583   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1584   if (!IsSEH)
1585     CatchPadMBB->setIsEHScopeEntry();
1586   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1587   if (IsMSVCCXX || IsCoreCLR)
1588     CatchPadMBB->setIsEHFuncletEntry();
1589   // Wasm does not need catchpads anymore
1590   if (!IsWasmCXX)
1591     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1592                             getControlRoot()));
1593 }
1594 
1595 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1596   // Update machine-CFG edge.
1597   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1598   FuncInfo.MBB->addSuccessor(TargetMBB);
1599 
1600   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1601   bool IsSEH = isAsynchronousEHPersonality(Pers);
1602   if (IsSEH) {
1603     // If this is not a fall-through branch or optimizations are switched off,
1604     // emit the branch.
1605     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1606         TM.getOptLevel() == CodeGenOpt::None)
1607       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1608                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1609     return;
1610   }
1611 
1612   // Figure out the funclet membership for the catchret's successor.
1613   // This will be used by the FuncletLayout pass to determine how to order the
1614   // BB's.
1615   // A 'catchret' returns to the outer scope's color.
1616   Value *ParentPad = I.getCatchSwitchParentPad();
1617   const BasicBlock *SuccessorColor;
1618   if (isa<ConstantTokenNone>(ParentPad))
1619     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1620   else
1621     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1622   assert(SuccessorColor && "No parent funclet for catchret!");
1623   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1624   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1625 
1626   // Create the terminator node.
1627   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1628                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1629                             DAG.getBasicBlock(SuccessorColorMBB));
1630   DAG.setRoot(Ret);
1631 }
1632 
1633 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1634   // Don't emit any special code for the cleanuppad instruction. It just marks
1635   // the start of an EH scope/funclet.
1636   FuncInfo.MBB->setIsEHScopeEntry();
1637   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1638   if (Pers != EHPersonality::Wasm_CXX) {
1639     FuncInfo.MBB->setIsEHFuncletEntry();
1640     FuncInfo.MBB->setIsCleanupFuncletEntry();
1641   }
1642 }
1643 
1644 // For wasm, there's alwyas a single catch pad attached to a catchswitch, and
1645 // the control flow always stops at the single catch pad, as it does for a
1646 // cleanup pad. In case the exception caught is not of the types the catch pad
1647 // catches, it will be rethrown by a rethrow.
1648 static void findWasmUnwindDestinations(
1649     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1650     BranchProbability Prob,
1651     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1652         &UnwindDests) {
1653   while (EHPadBB) {
1654     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1655     if (isa<CleanupPadInst>(Pad)) {
1656       // Stop on cleanup pads.
1657       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1658       UnwindDests.back().first->setIsEHScopeEntry();
1659       break;
1660     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1661       // Add the catchpad handlers to the possible destinations. We don't
1662       // continue to the unwind destination of the catchswitch for wasm.
1663       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1664         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1665         UnwindDests.back().first->setIsEHScopeEntry();
1666       }
1667       break;
1668     } else {
1669       continue;
1670     }
1671   }
1672 }
1673 
1674 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1675 /// many places it could ultimately go. In the IR, we have a single unwind
1676 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1677 /// This function skips over imaginary basic blocks that hold catchswitch
1678 /// instructions, and finds all the "real" machine
1679 /// basic block destinations. As those destinations may not be successors of
1680 /// EHPadBB, here we also calculate the edge probability to those destinations.
1681 /// The passed-in Prob is the edge probability to EHPadBB.
1682 static void findUnwindDestinations(
1683     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1684     BranchProbability Prob,
1685     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1686         &UnwindDests) {
1687   EHPersonality Personality =
1688     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1689   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1690   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1691   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1692   bool IsSEH = isAsynchronousEHPersonality(Personality);
1693 
1694   if (IsWasmCXX) {
1695     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
1696     assert(UnwindDests.size() <= 1 &&
1697            "There should be at most one unwind destination for wasm");
1698     return;
1699   }
1700 
1701   while (EHPadBB) {
1702     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1703     BasicBlock *NewEHPadBB = nullptr;
1704     if (isa<LandingPadInst>(Pad)) {
1705       // Stop on landingpads. They are not funclets.
1706       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1707       break;
1708     } else if (isa<CleanupPadInst>(Pad)) {
1709       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1710       // personalities.
1711       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1712       UnwindDests.back().first->setIsEHScopeEntry();
1713       UnwindDests.back().first->setIsEHFuncletEntry();
1714       break;
1715     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1716       // Add the catchpad handlers to the possible destinations.
1717       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1718         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1719         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1720         if (IsMSVCCXX || IsCoreCLR)
1721           UnwindDests.back().first->setIsEHFuncletEntry();
1722         if (!IsSEH)
1723           UnwindDests.back().first->setIsEHScopeEntry();
1724       }
1725       NewEHPadBB = CatchSwitch->getUnwindDest();
1726     } else {
1727       continue;
1728     }
1729 
1730     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1731     if (BPI && NewEHPadBB)
1732       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1733     EHPadBB = NewEHPadBB;
1734   }
1735 }
1736 
1737 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1738   // Update successor info.
1739   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1740   auto UnwindDest = I.getUnwindDest();
1741   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1742   BranchProbability UnwindDestProb =
1743       (BPI && UnwindDest)
1744           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1745           : BranchProbability::getZero();
1746   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1747   for (auto &UnwindDest : UnwindDests) {
1748     UnwindDest.first->setIsEHPad();
1749     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1750   }
1751   FuncInfo.MBB->normalizeSuccProbs();
1752 
1753   // Create the terminator node.
1754   SDValue Ret =
1755       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1756   DAG.setRoot(Ret);
1757 }
1758 
1759 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1760   report_fatal_error("visitCatchSwitch not yet implemented!");
1761 }
1762 
1763 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1764   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1765   auto &DL = DAG.getDataLayout();
1766   SDValue Chain = getControlRoot();
1767   SmallVector<ISD::OutputArg, 8> Outs;
1768   SmallVector<SDValue, 8> OutVals;
1769 
1770   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1771   // lower
1772   //
1773   //   %val = call <ty> @llvm.experimental.deoptimize()
1774   //   ret <ty> %val
1775   //
1776   // differently.
1777   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1778     LowerDeoptimizingReturn();
1779     return;
1780   }
1781 
1782   if (!FuncInfo.CanLowerReturn) {
1783     unsigned DemoteReg = FuncInfo.DemoteRegister;
1784     const Function *F = I.getParent()->getParent();
1785 
1786     // Emit a store of the return value through the virtual register.
1787     // Leave Outs empty so that LowerReturn won't try to load return
1788     // registers the usual way.
1789     SmallVector<EVT, 1> PtrValueVTs;
1790     ComputeValueVTs(TLI, DL,
1791                     F->getReturnType()->getPointerTo(
1792                         DAG.getDataLayout().getAllocaAddrSpace()),
1793                     PtrValueVTs);
1794 
1795     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1796                                         DemoteReg, PtrValueVTs[0]);
1797     SDValue RetOp = getValue(I.getOperand(0));
1798 
1799     SmallVector<EVT, 4> ValueVTs, MemVTs;
1800     SmallVector<uint64_t, 4> Offsets;
1801     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
1802                     &Offsets);
1803     unsigned NumValues = ValueVTs.size();
1804 
1805     SmallVector<SDValue, 4> Chains(NumValues);
1806     for (unsigned i = 0; i != NumValues; ++i) {
1807       // An aggregate return value cannot wrap around the address space, so
1808       // offsets to its parts don't wrap either.
1809       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1810 
1811       SDValue Val = RetOp.getValue(i);
1812       if (MemVTs[i] != ValueVTs[i])
1813         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
1814       Chains[i] = DAG.getStore(Chain, getCurSDLoc(), Val,
1815           // FIXME: better loc info would be nice.
1816           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1817     }
1818 
1819     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1820                         MVT::Other, Chains);
1821   } else if (I.getNumOperands() != 0) {
1822     SmallVector<EVT, 4> ValueVTs;
1823     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1824     unsigned NumValues = ValueVTs.size();
1825     if (NumValues) {
1826       SDValue RetOp = getValue(I.getOperand(0));
1827 
1828       const Function *F = I.getParent()->getParent();
1829 
1830       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
1831           I.getOperand(0)->getType(), F->getCallingConv(),
1832           /*IsVarArg*/ false);
1833 
1834       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1835       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1836                                           Attribute::SExt))
1837         ExtendKind = ISD::SIGN_EXTEND;
1838       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1839                                                Attribute::ZExt))
1840         ExtendKind = ISD::ZERO_EXTEND;
1841 
1842       LLVMContext &Context = F->getContext();
1843       bool RetInReg = F->getAttributes().hasAttribute(
1844           AttributeList::ReturnIndex, Attribute::InReg);
1845 
1846       for (unsigned j = 0; j != NumValues; ++j) {
1847         EVT VT = ValueVTs[j];
1848 
1849         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1850           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1851 
1852         CallingConv::ID CC = F->getCallingConv();
1853 
1854         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1855         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1856         SmallVector<SDValue, 4> Parts(NumParts);
1857         getCopyToParts(DAG, getCurSDLoc(),
1858                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1859                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1860 
1861         // 'inreg' on function refers to return value
1862         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1863         if (RetInReg)
1864           Flags.setInReg();
1865 
1866         if (I.getOperand(0)->getType()->isPointerTy()) {
1867           Flags.setPointer();
1868           Flags.setPointerAddrSpace(
1869               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
1870         }
1871 
1872         if (NeedsRegBlock) {
1873           Flags.setInConsecutiveRegs();
1874           if (j == NumValues - 1)
1875             Flags.setInConsecutiveRegsLast();
1876         }
1877 
1878         // Propagate extension type if any
1879         if (ExtendKind == ISD::SIGN_EXTEND)
1880           Flags.setSExt();
1881         else if (ExtendKind == ISD::ZERO_EXTEND)
1882           Flags.setZExt();
1883 
1884         for (unsigned i = 0; i < NumParts; ++i) {
1885           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1886                                         VT, /*isfixed=*/true, 0, 0));
1887           OutVals.push_back(Parts[i]);
1888         }
1889       }
1890     }
1891   }
1892 
1893   // Push in swifterror virtual register as the last element of Outs. This makes
1894   // sure swifterror virtual register will be returned in the swifterror
1895   // physical register.
1896   const Function *F = I.getParent()->getParent();
1897   if (TLI.supportSwiftError() &&
1898       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1899     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
1900     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1901     Flags.setSwiftError();
1902     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1903                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1904                                   true /*isfixed*/, 1 /*origidx*/,
1905                                   0 /*partOffs*/));
1906     // Create SDNode for the swifterror virtual register.
1907     OutVals.push_back(
1908         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
1909                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
1910                         EVT(TLI.getPointerTy(DL))));
1911   }
1912 
1913   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1914   CallingConv::ID CallConv =
1915     DAG.getMachineFunction().getFunction().getCallingConv();
1916   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1917       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1918 
1919   // Verify that the target's LowerReturn behaved as expected.
1920   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1921          "LowerReturn didn't return a valid chain!");
1922 
1923   // Update the DAG with the new chain value resulting from return lowering.
1924   DAG.setRoot(Chain);
1925 }
1926 
1927 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1928 /// created for it, emit nodes to copy the value into the virtual
1929 /// registers.
1930 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1931   // Skip empty types
1932   if (V->getType()->isEmptyTy())
1933     return;
1934 
1935   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1936   if (VMI != FuncInfo.ValueMap.end()) {
1937     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1938     CopyValueToVirtualRegister(V, VMI->second);
1939   }
1940 }
1941 
1942 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1943 /// the current basic block, add it to ValueMap now so that we'll get a
1944 /// CopyTo/FromReg.
1945 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1946   // No need to export constants.
1947   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1948 
1949   // Already exported?
1950   if (FuncInfo.isExportedInst(V)) return;
1951 
1952   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1953   CopyValueToVirtualRegister(V, Reg);
1954 }
1955 
1956 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1957                                                      const BasicBlock *FromBB) {
1958   // The operands of the setcc have to be in this block.  We don't know
1959   // how to export them from some other block.
1960   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1961     // Can export from current BB.
1962     if (VI->getParent() == FromBB)
1963       return true;
1964 
1965     // Is already exported, noop.
1966     return FuncInfo.isExportedInst(V);
1967   }
1968 
1969   // If this is an argument, we can export it if the BB is the entry block or
1970   // if it is already exported.
1971   if (isa<Argument>(V)) {
1972     if (FromBB == &FromBB->getParent()->getEntryBlock())
1973       return true;
1974 
1975     // Otherwise, can only export this if it is already exported.
1976     return FuncInfo.isExportedInst(V);
1977   }
1978 
1979   // Otherwise, constants can always be exported.
1980   return true;
1981 }
1982 
1983 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1984 BranchProbability
1985 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1986                                         const MachineBasicBlock *Dst) const {
1987   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1988   const BasicBlock *SrcBB = Src->getBasicBlock();
1989   const BasicBlock *DstBB = Dst->getBasicBlock();
1990   if (!BPI) {
1991     // If BPI is not available, set the default probability as 1 / N, where N is
1992     // the number of successors.
1993     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1994     return BranchProbability(1, SuccSize);
1995   }
1996   return BPI->getEdgeProbability(SrcBB, DstBB);
1997 }
1998 
1999 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2000                                                MachineBasicBlock *Dst,
2001                                                BranchProbability Prob) {
2002   if (!FuncInfo.BPI)
2003     Src->addSuccessorWithoutProb(Dst);
2004   else {
2005     if (Prob.isUnknown())
2006       Prob = getEdgeProbability(Src, Dst);
2007     Src->addSuccessor(Dst, Prob);
2008   }
2009 }
2010 
2011 static bool InBlock(const Value *V, const BasicBlock *BB) {
2012   if (const Instruction *I = dyn_cast<Instruction>(V))
2013     return I->getParent() == BB;
2014   return true;
2015 }
2016 
2017 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2018 /// This function emits a branch and is used at the leaves of an OR or an
2019 /// AND operator tree.
2020 void
2021 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2022                                                   MachineBasicBlock *TBB,
2023                                                   MachineBasicBlock *FBB,
2024                                                   MachineBasicBlock *CurBB,
2025                                                   MachineBasicBlock *SwitchBB,
2026                                                   BranchProbability TProb,
2027                                                   BranchProbability FProb,
2028                                                   bool InvertCond) {
2029   const BasicBlock *BB = CurBB->getBasicBlock();
2030 
2031   // If the leaf of the tree is a comparison, merge the condition into
2032   // the caseblock.
2033   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2034     // The operands of the cmp have to be in this block.  We don't know
2035     // how to export them from some other block.  If this is the first block
2036     // of the sequence, no exporting is needed.
2037     if (CurBB == SwitchBB ||
2038         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2039          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2040       ISD::CondCode Condition;
2041       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2042         ICmpInst::Predicate Pred =
2043             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2044         Condition = getICmpCondCode(Pred);
2045       } else {
2046         const FCmpInst *FC = cast<FCmpInst>(Cond);
2047         FCmpInst::Predicate Pred =
2048             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2049         Condition = getFCmpCondCode(Pred);
2050         if (TM.Options.NoNaNsFPMath)
2051           Condition = getFCmpCodeWithoutNaN(Condition);
2052       }
2053 
2054       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2055                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2056       SwitchCases.push_back(CB);
2057       return;
2058     }
2059   }
2060 
2061   // Create a CaseBlock record representing this branch.
2062   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2063   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2064                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2065   SwitchCases.push_back(CB);
2066 }
2067 
2068 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2069                                                MachineBasicBlock *TBB,
2070                                                MachineBasicBlock *FBB,
2071                                                MachineBasicBlock *CurBB,
2072                                                MachineBasicBlock *SwitchBB,
2073                                                Instruction::BinaryOps Opc,
2074                                                BranchProbability TProb,
2075                                                BranchProbability FProb,
2076                                                bool InvertCond) {
2077   // Skip over not part of the tree and remember to invert op and operands at
2078   // next level.
2079   Value *NotCond;
2080   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2081       InBlock(NotCond, CurBB->getBasicBlock())) {
2082     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2083                          !InvertCond);
2084     return;
2085   }
2086 
2087   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2088   // Compute the effective opcode for Cond, taking into account whether it needs
2089   // to be inverted, e.g.
2090   //   and (not (or A, B)), C
2091   // gets lowered as
2092   //   and (and (not A, not B), C)
2093   unsigned BOpc = 0;
2094   if (BOp) {
2095     BOpc = BOp->getOpcode();
2096     if (InvertCond) {
2097       if (BOpc == Instruction::And)
2098         BOpc = Instruction::Or;
2099       else if (BOpc == Instruction::Or)
2100         BOpc = Instruction::And;
2101     }
2102   }
2103 
2104   // If this node is not part of the or/and tree, emit it as a branch.
2105   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
2106       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
2107       BOp->getParent() != CurBB->getBasicBlock() ||
2108       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
2109       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
2110     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2111                                  TProb, FProb, InvertCond);
2112     return;
2113   }
2114 
2115   //  Create TmpBB after CurBB.
2116   MachineFunction::iterator BBI(CurBB);
2117   MachineFunction &MF = DAG.getMachineFunction();
2118   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2119   CurBB->getParent()->insert(++BBI, TmpBB);
2120 
2121   if (Opc == Instruction::Or) {
2122     // Codegen X | Y as:
2123     // BB1:
2124     //   jmp_if_X TBB
2125     //   jmp TmpBB
2126     // TmpBB:
2127     //   jmp_if_Y TBB
2128     //   jmp FBB
2129     //
2130 
2131     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2132     // The requirement is that
2133     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2134     //     = TrueProb for original BB.
2135     // Assuming the original probabilities are A and B, one choice is to set
2136     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2137     // A/(1+B) and 2B/(1+B). This choice assumes that
2138     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2139     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2140     // TmpBB, but the math is more complicated.
2141 
2142     auto NewTrueProb = TProb / 2;
2143     auto NewFalseProb = TProb / 2 + FProb;
2144     // Emit the LHS condition.
2145     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
2146                          NewTrueProb, NewFalseProb, InvertCond);
2147 
2148     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2149     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2150     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2151     // Emit the RHS condition into TmpBB.
2152     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2153                          Probs[0], Probs[1], InvertCond);
2154   } else {
2155     assert(Opc == Instruction::And && "Unknown merge op!");
2156     // Codegen X & Y as:
2157     // BB1:
2158     //   jmp_if_X TmpBB
2159     //   jmp FBB
2160     // TmpBB:
2161     //   jmp_if_Y TBB
2162     //   jmp FBB
2163     //
2164     //  This requires creation of TmpBB after CurBB.
2165 
2166     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2167     // The requirement is that
2168     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2169     //     = FalseProb for original BB.
2170     // Assuming the original probabilities are A and B, one choice is to set
2171     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2172     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2173     // TrueProb for BB1 * FalseProb for TmpBB.
2174 
2175     auto NewTrueProb = TProb + FProb / 2;
2176     auto NewFalseProb = FProb / 2;
2177     // Emit the LHS condition.
2178     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
2179                          NewTrueProb, NewFalseProb, InvertCond);
2180 
2181     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2182     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2183     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2184     // Emit the RHS condition into TmpBB.
2185     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
2186                          Probs[0], Probs[1], InvertCond);
2187   }
2188 }
2189 
2190 /// If the set of cases should be emitted as a series of branches, return true.
2191 /// If we should emit this as a bunch of and/or'd together conditions, return
2192 /// false.
2193 bool
2194 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2195   if (Cases.size() != 2) return true;
2196 
2197   // If this is two comparisons of the same values or'd or and'd together, they
2198   // will get folded into a single comparison, so don't emit two blocks.
2199   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2200        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2201       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2202        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2203     return false;
2204   }
2205 
2206   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2207   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2208   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2209       Cases[0].CC == Cases[1].CC &&
2210       isa<Constant>(Cases[0].CmpRHS) &&
2211       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2212     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2213       return false;
2214     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2215       return false;
2216   }
2217 
2218   return true;
2219 }
2220 
2221 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2222   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2223 
2224   // Update machine-CFG edges.
2225   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2226 
2227   if (I.isUnconditional()) {
2228     // Update machine-CFG edges.
2229     BrMBB->addSuccessor(Succ0MBB);
2230 
2231     // If this is not a fall-through branch or optimizations are switched off,
2232     // emit the branch.
2233     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
2234       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2235                               MVT::Other, getControlRoot(),
2236                               DAG.getBasicBlock(Succ0MBB)));
2237 
2238     return;
2239   }
2240 
2241   // If this condition is one of the special cases we handle, do special stuff
2242   // now.
2243   const Value *CondVal = I.getCondition();
2244   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2245 
2246   // If this is a series of conditions that are or'd or and'd together, emit
2247   // this as a sequence of branches instead of setcc's with and/or operations.
2248   // As long as jumps are not expensive, this should improve performance.
2249   // For example, instead of something like:
2250   //     cmp A, B
2251   //     C = seteq
2252   //     cmp D, E
2253   //     F = setle
2254   //     or C, F
2255   //     jnz foo
2256   // Emit:
2257   //     cmp A, B
2258   //     je foo
2259   //     cmp D, E
2260   //     jle foo
2261   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2262     Instruction::BinaryOps Opcode = BOp->getOpcode();
2263     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2264         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2265         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2266       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2267                            Opcode,
2268                            getEdgeProbability(BrMBB, Succ0MBB),
2269                            getEdgeProbability(BrMBB, Succ1MBB),
2270                            /*InvertCond=*/false);
2271       // If the compares in later blocks need to use values not currently
2272       // exported from this block, export them now.  This block should always
2273       // be the first entry.
2274       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2275 
2276       // Allow some cases to be rejected.
2277       if (ShouldEmitAsBranches(SwitchCases)) {
2278         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2279           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2280           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2281         }
2282 
2283         // Emit the branch for this block.
2284         visitSwitchCase(SwitchCases[0], BrMBB);
2285         SwitchCases.erase(SwitchCases.begin());
2286         return;
2287       }
2288 
2289       // Okay, we decided not to do this, remove any inserted MBB's and clear
2290       // SwitchCases.
2291       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2292         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2293 
2294       SwitchCases.clear();
2295     }
2296   }
2297 
2298   // Create a CaseBlock record representing this branch.
2299   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2300                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2301 
2302   // Use visitSwitchCase to actually insert the fast branch sequence for this
2303   // cond branch.
2304   visitSwitchCase(CB, BrMBB);
2305 }
2306 
2307 /// visitSwitchCase - Emits the necessary code to represent a single node in
2308 /// the binary search tree resulting from lowering a switch instruction.
2309 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2310                                           MachineBasicBlock *SwitchBB) {
2311   SDValue Cond;
2312   SDValue CondLHS = getValue(CB.CmpLHS);
2313   SDLoc dl = CB.DL;
2314 
2315   if (CB.CC == ISD::SETTRUE) {
2316     // Branch or fall through to TrueBB.
2317     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2318     SwitchBB->normalizeSuccProbs();
2319     if (CB.TrueBB != NextBlock(SwitchBB)) {
2320       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2321                               DAG.getBasicBlock(CB.TrueBB)));
2322     }
2323     return;
2324   }
2325 
2326   auto &TLI = DAG.getTargetLoweringInfo();
2327   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2328 
2329   // Build the setcc now.
2330   if (!CB.CmpMHS) {
2331     // Fold "(X == true)" to X and "(X == false)" to !X to
2332     // handle common cases produced by branch lowering.
2333     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2334         CB.CC == ISD::SETEQ)
2335       Cond = CondLHS;
2336     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2337              CB.CC == ISD::SETEQ) {
2338       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2339       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2340     } else {
2341       SDValue CondRHS = getValue(CB.CmpRHS);
2342 
2343       // If a pointer's DAG type is larger than its memory type then the DAG
2344       // values are zero-extended. This breaks signed comparisons so truncate
2345       // back to the underlying type before doing the compare.
2346       if (CondLHS.getValueType() != MemVT) {
2347         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2348         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2349       }
2350       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2351     }
2352   } else {
2353     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2354 
2355     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2356     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2357 
2358     SDValue CmpOp = getValue(CB.CmpMHS);
2359     EVT VT = CmpOp.getValueType();
2360 
2361     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2362       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2363                           ISD::SETLE);
2364     } else {
2365       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2366                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2367       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2368                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2369     }
2370   }
2371 
2372   // Update successor info
2373   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2374   // TrueBB and FalseBB are always different unless the incoming IR is
2375   // degenerate. This only happens when running llc on weird IR.
2376   if (CB.TrueBB != CB.FalseBB)
2377     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2378   SwitchBB->normalizeSuccProbs();
2379 
2380   // If the lhs block is the next block, invert the condition so that we can
2381   // fall through to the lhs instead of the rhs block.
2382   if (CB.TrueBB == NextBlock(SwitchBB)) {
2383     std::swap(CB.TrueBB, CB.FalseBB);
2384     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2385     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2386   }
2387 
2388   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2389                                MVT::Other, getControlRoot(), Cond,
2390                                DAG.getBasicBlock(CB.TrueBB));
2391 
2392   // Insert the false branch. Do this even if it's a fall through branch,
2393   // this makes it easier to do DAG optimizations which require inverting
2394   // the branch condition.
2395   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2396                        DAG.getBasicBlock(CB.FalseBB));
2397 
2398   DAG.setRoot(BrCond);
2399 }
2400 
2401 /// visitJumpTable - Emit JumpTable node in the current MBB
2402 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2403   // Emit the code for the jump table
2404   assert(JT.Reg != -1U && "Should lower JT Header first!");
2405   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2406   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2407                                      JT.Reg, PTy);
2408   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2409   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2410                                     MVT::Other, Index.getValue(1),
2411                                     Table, Index);
2412   DAG.setRoot(BrJumpTable);
2413 }
2414 
2415 /// visitJumpTableHeader - This function emits necessary code to produce index
2416 /// in the JumpTable from switch case.
2417 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2418                                                JumpTableHeader &JTH,
2419                                                MachineBasicBlock *SwitchBB) {
2420   SDLoc dl = getCurSDLoc();
2421 
2422   // Subtract the lowest switch case value from the value being switched on.
2423   SDValue SwitchOp = getValue(JTH.SValue);
2424   EVT VT = SwitchOp.getValueType();
2425   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2426                             DAG.getConstant(JTH.First, dl, VT));
2427 
2428   // The SDNode we just created, which holds the value being switched on minus
2429   // the smallest case value, needs to be copied to a virtual register so it
2430   // can be used as an index into the jump table in a subsequent basic block.
2431   // This value may be smaller or larger than the target's pointer type, and
2432   // therefore require extension or truncating.
2433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2434   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2435 
2436   unsigned JumpTableReg =
2437       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2438   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2439                                     JumpTableReg, SwitchOp);
2440   JT.Reg = JumpTableReg;
2441 
2442   if (!JTH.OmitRangeCheck) {
2443     // Emit the range check for the jump table, and branch to the default block
2444     // for the switch statement if the value being switched on exceeds the
2445     // largest case in the switch.
2446     SDValue CMP = DAG.getSetCC(
2447         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2448                                    Sub.getValueType()),
2449         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2450 
2451     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2452                                  MVT::Other, CopyTo, CMP,
2453                                  DAG.getBasicBlock(JT.Default));
2454 
2455     // Avoid emitting unnecessary branches to the next block.
2456     if (JT.MBB != NextBlock(SwitchBB))
2457       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2458                            DAG.getBasicBlock(JT.MBB));
2459 
2460     DAG.setRoot(BrCond);
2461   } else {
2462     // Avoid emitting unnecessary branches to the next block.
2463     if (JT.MBB != NextBlock(SwitchBB))
2464       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
2465                               DAG.getBasicBlock(JT.MBB)));
2466     else
2467       DAG.setRoot(CopyTo);
2468   }
2469 }
2470 
2471 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2472 /// variable if there exists one.
2473 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2474                                  SDValue &Chain) {
2475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2476   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2477   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2478   MachineFunction &MF = DAG.getMachineFunction();
2479   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2480   MachineSDNode *Node =
2481       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2482   if (Global) {
2483     MachinePointerInfo MPInfo(Global);
2484     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2485                  MachineMemOperand::MODereferenceable;
2486     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2487         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2488     DAG.setNodeMemRefs(Node, {MemRef});
2489   }
2490   if (PtrTy != PtrMemTy)
2491     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
2492   return SDValue(Node, 0);
2493 }
2494 
2495 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2496 /// tail spliced into a stack protector check success bb.
2497 ///
2498 /// For a high level explanation of how this fits into the stack protector
2499 /// generation see the comment on the declaration of class
2500 /// StackProtectorDescriptor.
2501 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2502                                                   MachineBasicBlock *ParentBB) {
2503 
2504   // First create the loads to the guard/stack slot for the comparison.
2505   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2506   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2507   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
2508 
2509   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2510   int FI = MFI.getStackProtectorIndex();
2511 
2512   SDValue Guard;
2513   SDLoc dl = getCurSDLoc();
2514   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2515   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2516   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2517 
2518   // Generate code to load the content of the guard slot.
2519   SDValue GuardVal = DAG.getLoad(
2520       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
2521       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2522       MachineMemOperand::MOVolatile);
2523 
2524   if (TLI.useStackGuardXorFP())
2525     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2526 
2527   // Retrieve guard check function, nullptr if instrumentation is inlined.
2528   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
2529     // The target provides a guard check function to validate the guard value.
2530     // Generate a call to that function with the content of the guard slot as
2531     // argument.
2532     FunctionType *FnTy = GuardCheckFn->getFunctionType();
2533     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2534 
2535     TargetLowering::ArgListTy Args;
2536     TargetLowering::ArgListEntry Entry;
2537     Entry.Node = GuardVal;
2538     Entry.Ty = FnTy->getParamType(0);
2539     if (GuardCheckFn->hasAttribute(1, Attribute::AttrKind::InReg))
2540       Entry.IsInReg = true;
2541     Args.push_back(Entry);
2542 
2543     TargetLowering::CallLoweringInfo CLI(DAG);
2544     CLI.setDebugLoc(getCurSDLoc())
2545         .setChain(DAG.getEntryNode())
2546         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
2547                    getValue(GuardCheckFn), std::move(Args));
2548 
2549     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2550     DAG.setRoot(Result.second);
2551     return;
2552   }
2553 
2554   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2555   // Otherwise, emit a volatile load to retrieve the stack guard value.
2556   SDValue Chain = DAG.getEntryNode();
2557   if (TLI.useLoadStackGuardNode()) {
2558     Guard = getLoadStackGuard(DAG, dl, Chain);
2559   } else {
2560     const Value *IRGuard = TLI.getSDagStackGuard(M);
2561     SDValue GuardPtr = getValue(IRGuard);
2562 
2563     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
2564                         MachinePointerInfo(IRGuard, 0), Align,
2565                         MachineMemOperand::MOVolatile);
2566   }
2567 
2568   // Perform the comparison via a subtract/getsetcc.
2569   EVT VT = Guard.getValueType();
2570   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2571 
2572   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2573                                                         *DAG.getContext(),
2574                                                         Sub.getValueType()),
2575                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2576 
2577   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2578   // branch to failure MBB.
2579   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2580                                MVT::Other, GuardVal.getOperand(0),
2581                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2582   // Otherwise branch to success MBB.
2583   SDValue Br = DAG.getNode(ISD::BR, dl,
2584                            MVT::Other, BrCond,
2585                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2586 
2587   DAG.setRoot(Br);
2588 }
2589 
2590 /// Codegen the failure basic block for a stack protector check.
2591 ///
2592 /// A failure stack protector machine basic block consists simply of a call to
2593 /// __stack_chk_fail().
2594 ///
2595 /// For a high level explanation of how this fits into the stack protector
2596 /// generation see the comment on the declaration of class
2597 /// StackProtectorDescriptor.
2598 void
2599 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2600   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2601   SDValue Chain =
2602       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2603                       None, false, getCurSDLoc(), false, false).second;
2604   // On PS4, the "return address" must still be within the calling function,
2605   // even if it's at the very end, so emit an explicit TRAP here.
2606   // Passing 'true' for doesNotReturn above won't generate the trap for us.
2607   if (TM.getTargetTriple().isPS4CPU())
2608     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
2609 
2610   DAG.setRoot(Chain);
2611 }
2612 
2613 /// visitBitTestHeader - This function emits necessary code to produce value
2614 /// suitable for "bit tests"
2615 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2616                                              MachineBasicBlock *SwitchBB) {
2617   SDLoc dl = getCurSDLoc();
2618 
2619   // Subtract the minimum value
2620   SDValue SwitchOp = getValue(B.SValue);
2621   EVT VT = SwitchOp.getValueType();
2622   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2623                             DAG.getConstant(B.First, dl, VT));
2624 
2625   // Check range
2626   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2627   SDValue RangeCmp = DAG.getSetCC(
2628       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2629                                  Sub.getValueType()),
2630       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2631 
2632   // Determine the type of the test operands.
2633   bool UsePtrType = false;
2634   if (!TLI.isTypeLegal(VT))
2635     UsePtrType = true;
2636   else {
2637     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2638       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2639         // Switch table case range are encoded into series of masks.
2640         // Just use pointer type, it's guaranteed to fit.
2641         UsePtrType = true;
2642         break;
2643       }
2644   }
2645   if (UsePtrType) {
2646     VT = TLI.getPointerTy(DAG.getDataLayout());
2647     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2648   }
2649 
2650   B.RegVT = VT.getSimpleVT();
2651   B.Reg = FuncInfo.CreateReg(B.RegVT);
2652   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2653 
2654   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2655 
2656   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2657   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2658   SwitchBB->normalizeSuccProbs();
2659 
2660   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2661                                 MVT::Other, CopyTo, RangeCmp,
2662                                 DAG.getBasicBlock(B.Default));
2663 
2664   // Avoid emitting unnecessary branches to the next block.
2665   if (MBB != NextBlock(SwitchBB))
2666     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2667                           DAG.getBasicBlock(MBB));
2668 
2669   DAG.setRoot(BrRange);
2670 }
2671 
2672 /// visitBitTestCase - this function produces one "bit test"
2673 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2674                                            MachineBasicBlock* NextMBB,
2675                                            BranchProbability BranchProbToNext,
2676                                            unsigned Reg,
2677                                            BitTestCase &B,
2678                                            MachineBasicBlock *SwitchBB) {
2679   SDLoc dl = getCurSDLoc();
2680   MVT VT = BB.RegVT;
2681   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2682   SDValue Cmp;
2683   unsigned PopCount = countPopulation(B.Mask);
2684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2685   if (PopCount == 1) {
2686     // Testing for a single bit; just compare the shift count with what it
2687     // would need to be to shift a 1 bit in that position.
2688     Cmp = DAG.getSetCC(
2689         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2690         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2691         ISD::SETEQ);
2692   } else if (PopCount == BB.Range) {
2693     // There is only one zero bit in the range, test for it directly.
2694     Cmp = DAG.getSetCC(
2695         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2696         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2697         ISD::SETNE);
2698   } else {
2699     // Make desired shift
2700     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2701                                     DAG.getConstant(1, dl, VT), ShiftOp);
2702 
2703     // Emit bit tests and jumps
2704     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2705                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2706     Cmp = DAG.getSetCC(
2707         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2708         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2709   }
2710 
2711   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2712   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2713   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2714   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2715   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2716   // one as they are relative probabilities (and thus work more like weights),
2717   // and hence we need to normalize them to let the sum of them become one.
2718   SwitchBB->normalizeSuccProbs();
2719 
2720   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2721                               MVT::Other, getControlRoot(),
2722                               Cmp, DAG.getBasicBlock(B.TargetBB));
2723 
2724   // Avoid emitting unnecessary branches to the next block.
2725   if (NextMBB != NextBlock(SwitchBB))
2726     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2727                         DAG.getBasicBlock(NextMBB));
2728 
2729   DAG.setRoot(BrAnd);
2730 }
2731 
2732 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2733   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2734 
2735   // Retrieve successors. Look through artificial IR level blocks like
2736   // catchswitch for successors.
2737   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2738   const BasicBlock *EHPadBB = I.getSuccessor(1);
2739 
2740   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2741   // have to do anything here to lower funclet bundles.
2742   assert(!I.hasOperandBundlesOtherThan(
2743              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2744          "Cannot lower invokes with arbitrary operand bundles yet!");
2745 
2746   const Value *Callee(I.getCalledValue());
2747   const Function *Fn = dyn_cast<Function>(Callee);
2748   if (isa<InlineAsm>(Callee))
2749     visitInlineAsm(&I);
2750   else if (Fn && Fn->isIntrinsic()) {
2751     switch (Fn->getIntrinsicID()) {
2752     default:
2753       llvm_unreachable("Cannot invoke this intrinsic");
2754     case Intrinsic::donothing:
2755       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2756       break;
2757     case Intrinsic::experimental_patchpoint_void:
2758     case Intrinsic::experimental_patchpoint_i64:
2759       visitPatchpoint(&I, EHPadBB);
2760       break;
2761     case Intrinsic::experimental_gc_statepoint:
2762       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2763       break;
2764     case Intrinsic::wasm_rethrow_in_catch: {
2765       // This is usually done in visitTargetIntrinsic, but this intrinsic is
2766       // special because it can be invoked, so we manually lower it to a DAG
2767       // node here.
2768       SmallVector<SDValue, 8> Ops;
2769       Ops.push_back(getRoot()); // inchain
2770       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2771       Ops.push_back(
2772           DAG.getTargetConstant(Intrinsic::wasm_rethrow_in_catch, getCurSDLoc(),
2773                                 TLI.getPointerTy(DAG.getDataLayout())));
2774       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
2775       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
2776       break;
2777     }
2778     }
2779   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2780     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2781     // Eventually we will support lowering the @llvm.experimental.deoptimize
2782     // intrinsic, and right now there are no plans to support other intrinsics
2783     // with deopt state.
2784     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2785   } else {
2786     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2787   }
2788 
2789   // If the value of the invoke is used outside of its defining block, make it
2790   // available as a virtual register.
2791   // We already took care of the exported value for the statepoint instruction
2792   // during call to the LowerStatepoint.
2793   if (!isStatepoint(I)) {
2794     CopyToExportRegsIfNeeded(&I);
2795   }
2796 
2797   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2798   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2799   BranchProbability EHPadBBProb =
2800       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2801           : BranchProbability::getZero();
2802   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2803 
2804   // Update successor info.
2805   addSuccessorWithProb(InvokeMBB, Return);
2806   for (auto &UnwindDest : UnwindDests) {
2807     UnwindDest.first->setIsEHPad();
2808     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2809   }
2810   InvokeMBB->normalizeSuccProbs();
2811 
2812   // Drop into normal successor.
2813   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
2814                           DAG.getBasicBlock(Return)));
2815 }
2816 
2817 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
2818   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
2819 
2820   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2821   // have to do anything here to lower funclet bundles.
2822   assert(!I.hasOperandBundlesOtherThan(
2823              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2824          "Cannot lower callbrs with arbitrary operand bundles yet!");
2825 
2826   assert(isa<InlineAsm>(I.getCalledValue()) &&
2827          "Only know how to handle inlineasm callbr");
2828   visitInlineAsm(&I);
2829 
2830   // Retrieve successors.
2831   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
2832 
2833   // Update successor info.
2834   addSuccessorWithProb(CallBrMBB, Return);
2835   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
2836     MachineBasicBlock *Target = FuncInfo.MBBMap[I.getIndirectDest(i)];
2837     addSuccessorWithProb(CallBrMBB, Target);
2838   }
2839   CallBrMBB->normalizeSuccProbs();
2840 
2841   // Drop into default successor.
2842   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2843                           MVT::Other, getControlRoot(),
2844                           DAG.getBasicBlock(Return)));
2845 }
2846 
2847 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2848   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2849 }
2850 
2851 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2852   assert(FuncInfo.MBB->isEHPad() &&
2853          "Call to landingpad not in landing pad!");
2854 
2855   // If there aren't registers to copy the values into (e.g., during SjLj
2856   // exceptions), then don't bother to create these DAG nodes.
2857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2858   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2859   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2860       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2861     return;
2862 
2863   // If landingpad's return type is token type, we don't create DAG nodes
2864   // for its exception pointer and selector value. The extraction of exception
2865   // pointer or selector value from token type landingpads is not currently
2866   // supported.
2867   if (LP.getType()->isTokenTy())
2868     return;
2869 
2870   SmallVector<EVT, 2> ValueVTs;
2871   SDLoc dl = getCurSDLoc();
2872   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2873   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2874 
2875   // Get the two live-in registers as SDValues. The physregs have already been
2876   // copied into virtual registers.
2877   SDValue Ops[2];
2878   if (FuncInfo.ExceptionPointerVirtReg) {
2879     Ops[0] = DAG.getZExtOrTrunc(
2880         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2881                            FuncInfo.ExceptionPointerVirtReg,
2882                            TLI.getPointerTy(DAG.getDataLayout())),
2883         dl, ValueVTs[0]);
2884   } else {
2885     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2886   }
2887   Ops[1] = DAG.getZExtOrTrunc(
2888       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2889                          FuncInfo.ExceptionSelectorVirtReg,
2890                          TLI.getPointerTy(DAG.getDataLayout())),
2891       dl, ValueVTs[1]);
2892 
2893   // Merge into one.
2894   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2895                             DAG.getVTList(ValueVTs), Ops);
2896   setValue(&LP, Res);
2897 }
2898 
2899 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2900 #ifndef NDEBUG
2901   for (const CaseCluster &CC : Clusters)
2902     assert(CC.Low == CC.High && "Input clusters must be single-case");
2903 #endif
2904 
2905   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2906     return a.Low->getValue().slt(b.Low->getValue());
2907   });
2908 
2909   // Merge adjacent clusters with the same destination.
2910   const unsigned N = Clusters.size();
2911   unsigned DstIndex = 0;
2912   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2913     CaseCluster &CC = Clusters[SrcIndex];
2914     const ConstantInt *CaseVal = CC.Low;
2915     MachineBasicBlock *Succ = CC.MBB;
2916 
2917     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2918         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2919       // If this case has the same successor and is a neighbour, merge it into
2920       // the previous cluster.
2921       Clusters[DstIndex - 1].High = CaseVal;
2922       Clusters[DstIndex - 1].Prob += CC.Prob;
2923     } else {
2924       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2925                    sizeof(Clusters[SrcIndex]));
2926     }
2927   }
2928   Clusters.resize(DstIndex);
2929 }
2930 
2931 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2932                                            MachineBasicBlock *Last) {
2933   // Update JTCases.
2934   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2935     if (JTCases[i].first.HeaderBB == First)
2936       JTCases[i].first.HeaderBB = Last;
2937 
2938   // Update BitTestCases.
2939   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2940     if (BitTestCases[i].Parent == First)
2941       BitTestCases[i].Parent = Last;
2942 }
2943 
2944 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2945   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2946 
2947   // Update machine-CFG edges with unique successors.
2948   SmallSet<BasicBlock*, 32> Done;
2949   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2950     BasicBlock *BB = I.getSuccessor(i);
2951     bool Inserted = Done.insert(BB).second;
2952     if (!Inserted)
2953         continue;
2954 
2955     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2956     addSuccessorWithProb(IndirectBrMBB, Succ);
2957   }
2958   IndirectBrMBB->normalizeSuccProbs();
2959 
2960   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2961                           MVT::Other, getControlRoot(),
2962                           getValue(I.getAddress())));
2963 }
2964 
2965 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2966   if (!DAG.getTarget().Options.TrapUnreachable)
2967     return;
2968 
2969   // We may be able to ignore unreachable behind a noreturn call.
2970   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2971     const BasicBlock &BB = *I.getParent();
2972     if (&I != &BB.front()) {
2973       BasicBlock::const_iterator PredI =
2974         std::prev(BasicBlock::const_iterator(&I));
2975       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2976         if (Call->doesNotReturn())
2977           return;
2978       }
2979     }
2980   }
2981 
2982   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2983 }
2984 
2985 void SelectionDAGBuilder::visitFSub(const User &I) {
2986   // -0.0 - X --> fneg
2987   Type *Ty = I.getType();
2988   if (isa<Constant>(I.getOperand(0)) &&
2989       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2990     SDValue Op2 = getValue(I.getOperand(1));
2991     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2992                              Op2.getValueType(), Op2));
2993     return;
2994   }
2995 
2996   visitBinary(I, ISD::FSUB);
2997 }
2998 
2999 /// Checks if the given instruction performs a vector reduction, in which case
3000 /// we have the freedom to alter the elements in the result as long as the
3001 /// reduction of them stays unchanged.
3002 static bool isVectorReductionOp(const User *I) {
3003   const Instruction *Inst = dyn_cast<Instruction>(I);
3004   if (!Inst || !Inst->getType()->isVectorTy())
3005     return false;
3006 
3007   auto OpCode = Inst->getOpcode();
3008   switch (OpCode) {
3009   case Instruction::Add:
3010   case Instruction::Mul:
3011   case Instruction::And:
3012   case Instruction::Or:
3013   case Instruction::Xor:
3014     break;
3015   case Instruction::FAdd:
3016   case Instruction::FMul:
3017     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3018       if (FPOp->getFastMathFlags().isFast())
3019         break;
3020     LLVM_FALLTHROUGH;
3021   default:
3022     return false;
3023   }
3024 
3025   unsigned ElemNum = Inst->getType()->getVectorNumElements();
3026   // Ensure the reduction size is a power of 2.
3027   if (!isPowerOf2_32(ElemNum))
3028     return false;
3029 
3030   unsigned ElemNumToReduce = ElemNum;
3031 
3032   // Do DFS search on the def-use chain from the given instruction. We only
3033   // allow four kinds of operations during the search until we reach the
3034   // instruction that extracts the first element from the vector:
3035   //
3036   //   1. The reduction operation of the same opcode as the given instruction.
3037   //
3038   //   2. PHI node.
3039   //
3040   //   3. ShuffleVector instruction together with a reduction operation that
3041   //      does a partial reduction.
3042   //
3043   //   4. ExtractElement that extracts the first element from the vector, and we
3044   //      stop searching the def-use chain here.
3045   //
3046   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
3047   // from 1-3 to the stack to continue the DFS. The given instruction is not
3048   // a reduction operation if we meet any other instructions other than those
3049   // listed above.
3050 
3051   SmallVector<const User *, 16> UsersToVisit{Inst};
3052   SmallPtrSet<const User *, 16> Visited;
3053   bool ReduxExtracted = false;
3054 
3055   while (!UsersToVisit.empty()) {
3056     auto User = UsersToVisit.back();
3057     UsersToVisit.pop_back();
3058     if (!Visited.insert(User).second)
3059       continue;
3060 
3061     for (const auto &U : User->users()) {
3062       auto Inst = dyn_cast<Instruction>(U);
3063       if (!Inst)
3064         return false;
3065 
3066       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
3067         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
3068           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
3069             return false;
3070         UsersToVisit.push_back(U);
3071       } else if (const ShuffleVectorInst *ShufInst =
3072                      dyn_cast<ShuffleVectorInst>(U)) {
3073         // Detect the following pattern: A ShuffleVector instruction together
3074         // with a reduction that do partial reduction on the first and second
3075         // ElemNumToReduce / 2 elements, and store the result in
3076         // ElemNumToReduce / 2 elements in another vector.
3077 
3078         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
3079         if (ResultElements < ElemNum)
3080           return false;
3081 
3082         if (ElemNumToReduce == 1)
3083           return false;
3084         if (!isa<UndefValue>(U->getOperand(1)))
3085           return false;
3086         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
3087           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
3088             return false;
3089         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
3090           if (ShufInst->getMaskValue(i) != -1)
3091             return false;
3092 
3093         // There is only one user of this ShuffleVector instruction, which
3094         // must be a reduction operation.
3095         if (!U->hasOneUse())
3096           return false;
3097 
3098         auto U2 = dyn_cast<Instruction>(*U->user_begin());
3099         if (!U2 || U2->getOpcode() != OpCode)
3100           return false;
3101 
3102         // Check operands of the reduction operation.
3103         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
3104             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
3105           UsersToVisit.push_back(U2);
3106           ElemNumToReduce /= 2;
3107         } else
3108           return false;
3109       } else if (isa<ExtractElementInst>(U)) {
3110         // At this moment we should have reduced all elements in the vector.
3111         if (ElemNumToReduce != 1)
3112           return false;
3113 
3114         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
3115         if (!Val || !Val->isZero())
3116           return false;
3117 
3118         ReduxExtracted = true;
3119       } else
3120         return false;
3121     }
3122   }
3123   return ReduxExtracted;
3124 }
3125 
3126 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3127   SDNodeFlags Flags;
3128 
3129   SDValue Op = getValue(I.getOperand(0));
3130   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3131                                     Op, Flags);
3132   setValue(&I, UnNodeValue);
3133 }
3134 
3135 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3136   SDNodeFlags Flags;
3137   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3138     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3139     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3140   }
3141   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
3142     Flags.setExact(ExactOp->isExact());
3143   }
3144   if (isVectorReductionOp(&I)) {
3145     Flags.setVectorReduction(true);
3146     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
3147   }
3148 
3149   SDValue Op1 = getValue(I.getOperand(0));
3150   SDValue Op2 = getValue(I.getOperand(1));
3151   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3152                                      Op1, Op2, Flags);
3153   setValue(&I, BinNodeValue);
3154 }
3155 
3156 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3157   SDValue Op1 = getValue(I.getOperand(0));
3158   SDValue Op2 = getValue(I.getOperand(1));
3159 
3160   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3161       Op1.getValueType(), DAG.getDataLayout());
3162 
3163   // Coerce the shift amount to the right type if we can.
3164   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3165     unsigned ShiftSize = ShiftTy.getSizeInBits();
3166     unsigned Op2Size = Op2.getValueSizeInBits();
3167     SDLoc DL = getCurSDLoc();
3168 
3169     // If the operand is smaller than the shift count type, promote it.
3170     if (ShiftSize > Op2Size)
3171       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
3172 
3173     // If the operand is larger than the shift count type but the shift
3174     // count type has enough bits to represent any shift value, truncate
3175     // it now. This is a common case and it exposes the truncate to
3176     // optimization early.
3177     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
3178       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
3179     // Otherwise we'll need to temporarily settle for some other convenient
3180     // type.  Type legalization will make adjustments once the shiftee is split.
3181     else
3182       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
3183   }
3184 
3185   bool nuw = false;
3186   bool nsw = false;
3187   bool exact = false;
3188 
3189   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3190 
3191     if (const OverflowingBinaryOperator *OFBinOp =
3192             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3193       nuw = OFBinOp->hasNoUnsignedWrap();
3194       nsw = OFBinOp->hasNoSignedWrap();
3195     }
3196     if (const PossiblyExactOperator *ExactOp =
3197             dyn_cast<const PossiblyExactOperator>(&I))
3198       exact = ExactOp->isExact();
3199   }
3200   SDNodeFlags Flags;
3201   Flags.setExact(exact);
3202   Flags.setNoSignedWrap(nsw);
3203   Flags.setNoUnsignedWrap(nuw);
3204   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3205                             Flags);
3206   setValue(&I, Res);
3207 }
3208 
3209 void SelectionDAGBuilder::visitSDiv(const User &I) {
3210   SDValue Op1 = getValue(I.getOperand(0));
3211   SDValue Op2 = getValue(I.getOperand(1));
3212 
3213   SDNodeFlags Flags;
3214   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3215                  cast<PossiblyExactOperator>(&I)->isExact());
3216   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3217                            Op2, Flags));
3218 }
3219 
3220 void SelectionDAGBuilder::visitICmp(const User &I) {
3221   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3222   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3223     predicate = IC->getPredicate();
3224   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3225     predicate = ICmpInst::Predicate(IC->getPredicate());
3226   SDValue Op1 = getValue(I.getOperand(0));
3227   SDValue Op2 = getValue(I.getOperand(1));
3228   ISD::CondCode Opcode = getICmpCondCode(predicate);
3229 
3230   auto &TLI = DAG.getTargetLoweringInfo();
3231   EVT MemVT =
3232       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3233 
3234   // If a pointer's DAG type is larger than its memory type then the DAG values
3235   // are zero-extended. This breaks signed comparisons so truncate back to the
3236   // underlying type before doing the compare.
3237   if (Op1.getValueType() != MemVT) {
3238     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3239     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3240   }
3241 
3242   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3243                                                         I.getType());
3244   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3245 }
3246 
3247 void SelectionDAGBuilder::visitFCmp(const User &I) {
3248   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3249   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3250     predicate = FC->getPredicate();
3251   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3252     predicate = FCmpInst::Predicate(FC->getPredicate());
3253   SDValue Op1 = getValue(I.getOperand(0));
3254   SDValue Op2 = getValue(I.getOperand(1));
3255 
3256   ISD::CondCode Condition = getFCmpCondCode(predicate);
3257   auto *FPMO = dyn_cast<FPMathOperator>(&I);
3258   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
3259     Condition = getFCmpCodeWithoutNaN(Condition);
3260 
3261   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3262                                                         I.getType());
3263   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3264 }
3265 
3266 // Check if the condition of the select has one use or two users that are both
3267 // selects with the same condition.
3268 static bool hasOnlySelectUsers(const Value *Cond) {
3269   return llvm::all_of(Cond->users(), [](const Value *V) {
3270     return isa<SelectInst>(V);
3271   });
3272 }
3273 
3274 void SelectionDAGBuilder::visitSelect(const User &I) {
3275   SmallVector<EVT, 4> ValueVTs;
3276   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3277                   ValueVTs);
3278   unsigned NumValues = ValueVTs.size();
3279   if (NumValues == 0) return;
3280 
3281   SmallVector<SDValue, 4> Values(NumValues);
3282   SDValue Cond     = getValue(I.getOperand(0));
3283   SDValue LHSVal   = getValue(I.getOperand(1));
3284   SDValue RHSVal   = getValue(I.getOperand(2));
3285   auto BaseOps = {Cond};
3286   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
3287     ISD::VSELECT : ISD::SELECT;
3288 
3289   bool IsUnaryAbs = false;
3290 
3291   // Min/max matching is only viable if all output VTs are the same.
3292   if (is_splat(ValueVTs)) {
3293     EVT VT = ValueVTs[0];
3294     LLVMContext &Ctx = *DAG.getContext();
3295     auto &TLI = DAG.getTargetLoweringInfo();
3296 
3297     // We care about the legality of the operation after it has been type
3298     // legalized.
3299     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
3300            VT != TLI.getTypeToTransformTo(Ctx, VT))
3301       VT = TLI.getTypeToTransformTo(Ctx, VT);
3302 
3303     // If the vselect is legal, assume we want to leave this as a vector setcc +
3304     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3305     // min/max is legal on the scalar type.
3306     bool UseScalarMinMax = VT.isVector() &&
3307       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3308 
3309     Value *LHS, *RHS;
3310     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3311     ISD::NodeType Opc = ISD::DELETED_NODE;
3312     switch (SPR.Flavor) {
3313     case SPF_UMAX:    Opc = ISD::UMAX; break;
3314     case SPF_UMIN:    Opc = ISD::UMIN; break;
3315     case SPF_SMAX:    Opc = ISD::SMAX; break;
3316     case SPF_SMIN:    Opc = ISD::SMIN; break;
3317     case SPF_FMINNUM:
3318       switch (SPR.NaNBehavior) {
3319       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3320       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
3321       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3322       case SPNB_RETURNS_ANY: {
3323         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
3324           Opc = ISD::FMINNUM;
3325         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
3326           Opc = ISD::FMINIMUM;
3327         else if (UseScalarMinMax)
3328           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
3329             ISD::FMINNUM : ISD::FMINIMUM;
3330         break;
3331       }
3332       }
3333       break;
3334     case SPF_FMAXNUM:
3335       switch (SPR.NaNBehavior) {
3336       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3337       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3338       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3339       case SPNB_RETURNS_ANY:
3340 
3341         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3342           Opc = ISD::FMAXNUM;
3343         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3344           Opc = ISD::FMAXIMUM;
3345         else if (UseScalarMinMax)
3346           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3347             ISD::FMAXNUM : ISD::FMAXIMUM;
3348         break;
3349       }
3350       break;
3351     case SPF_ABS:
3352       IsUnaryAbs = true;
3353       Opc = ISD::ABS;
3354       break;
3355     case SPF_NABS:
3356       // TODO: we need to produce sub(0, abs(X)).
3357     default: break;
3358     }
3359 
3360     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3361         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3362          (UseScalarMinMax &&
3363           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3364         // If the underlying comparison instruction is used by any other
3365         // instruction, the consumed instructions won't be destroyed, so it is
3366         // not profitable to convert to a min/max.
3367         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3368       OpCode = Opc;
3369       LHSVal = getValue(LHS);
3370       RHSVal = getValue(RHS);
3371       BaseOps = {};
3372     }
3373 
3374     if (IsUnaryAbs) {
3375       OpCode = Opc;
3376       LHSVal = getValue(LHS);
3377       BaseOps = {};
3378     }
3379   }
3380 
3381   if (IsUnaryAbs) {
3382     for (unsigned i = 0; i != NumValues; ++i) {
3383       Values[i] =
3384           DAG.getNode(OpCode, getCurSDLoc(),
3385                       LHSVal.getNode()->getValueType(LHSVal.getResNo() + i),
3386                       SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3387     }
3388   } else {
3389     for (unsigned i = 0; i != NumValues; ++i) {
3390       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3391       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3392       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3393       Values[i] = DAG.getNode(
3394           OpCode, getCurSDLoc(),
3395           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops);
3396     }
3397   }
3398 
3399   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3400                            DAG.getVTList(ValueVTs), Values));
3401 }
3402 
3403 void SelectionDAGBuilder::visitTrunc(const User &I) {
3404   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3405   SDValue N = getValue(I.getOperand(0));
3406   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3407                                                         I.getType());
3408   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3409 }
3410 
3411 void SelectionDAGBuilder::visitZExt(const User &I) {
3412   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3413   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3414   SDValue N = getValue(I.getOperand(0));
3415   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3416                                                         I.getType());
3417   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3418 }
3419 
3420 void SelectionDAGBuilder::visitSExt(const User &I) {
3421   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3422   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3423   SDValue N = getValue(I.getOperand(0));
3424   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3425                                                         I.getType());
3426   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3427 }
3428 
3429 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3430   // FPTrunc is never a no-op cast, no need to check
3431   SDValue N = getValue(I.getOperand(0));
3432   SDLoc dl = getCurSDLoc();
3433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3434   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3435   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3436                            DAG.getTargetConstant(
3437                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3438 }
3439 
3440 void SelectionDAGBuilder::visitFPExt(const User &I) {
3441   // FPExt is never a no-op cast, no need to check
3442   SDValue N = getValue(I.getOperand(0));
3443   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3444                                                         I.getType());
3445   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3446 }
3447 
3448 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3449   // FPToUI is never a no-op cast, no need to check
3450   SDValue N = getValue(I.getOperand(0));
3451   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3452                                                         I.getType());
3453   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3454 }
3455 
3456 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3457   // FPToSI is never a no-op cast, no need to check
3458   SDValue N = getValue(I.getOperand(0));
3459   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3460                                                         I.getType());
3461   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3462 }
3463 
3464 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3465   // UIToFP is never a no-op cast, no need to check
3466   SDValue N = getValue(I.getOperand(0));
3467   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3468                                                         I.getType());
3469   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3470 }
3471 
3472 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3473   // SIToFP is never a no-op cast, no need to check
3474   SDValue N = getValue(I.getOperand(0));
3475   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3476                                                         I.getType());
3477   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3478 }
3479 
3480 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3481   // What to do depends on the size of the integer and the size of the pointer.
3482   // We can either truncate, zero extend, or no-op, accordingly.
3483   SDValue N = getValue(I.getOperand(0));
3484   auto &TLI = DAG.getTargetLoweringInfo();
3485   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3486                                                         I.getType());
3487   EVT PtrMemVT =
3488       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3489   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3490   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3491   setValue(&I, N);
3492 }
3493 
3494 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3495   // What to do depends on the size of the integer and the size of the pointer.
3496   // We can either truncate, zero extend, or no-op, accordingly.
3497   SDValue N = getValue(I.getOperand(0));
3498   auto &TLI = DAG.getTargetLoweringInfo();
3499   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3500   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3501   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3502   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3503   setValue(&I, N);
3504 }
3505 
3506 void SelectionDAGBuilder::visitBitCast(const User &I) {
3507   SDValue N = getValue(I.getOperand(0));
3508   SDLoc dl = getCurSDLoc();
3509   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3510                                                         I.getType());
3511 
3512   // BitCast assures us that source and destination are the same size so this is
3513   // either a BITCAST or a no-op.
3514   if (DestVT != N.getValueType())
3515     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3516                              DestVT, N)); // convert types.
3517   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3518   // might fold any kind of constant expression to an integer constant and that
3519   // is not what we are looking for. Only recognize a bitcast of a genuine
3520   // constant integer as an opaque constant.
3521   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3522     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3523                                  /*isOpaque*/true));
3524   else
3525     setValue(&I, N);            // noop cast.
3526 }
3527 
3528 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3530   const Value *SV = I.getOperand(0);
3531   SDValue N = getValue(SV);
3532   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3533 
3534   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3535   unsigned DestAS = I.getType()->getPointerAddressSpace();
3536 
3537   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3538     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3539 
3540   setValue(&I, N);
3541 }
3542 
3543 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3545   SDValue InVec = getValue(I.getOperand(0));
3546   SDValue InVal = getValue(I.getOperand(1));
3547   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3548                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3549   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3550                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3551                            InVec, InVal, InIdx));
3552 }
3553 
3554 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3555   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3556   SDValue InVec = getValue(I.getOperand(0));
3557   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3558                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3559   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3560                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3561                            InVec, InIdx));
3562 }
3563 
3564 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3565   SDValue Src1 = getValue(I.getOperand(0));
3566   SDValue Src2 = getValue(I.getOperand(1));
3567   SDLoc DL = getCurSDLoc();
3568 
3569   SmallVector<int, 8> Mask;
3570   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3571   unsigned MaskNumElts = Mask.size();
3572 
3573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3574   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3575   EVT SrcVT = Src1.getValueType();
3576   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3577 
3578   if (SrcNumElts == MaskNumElts) {
3579     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3580     return;
3581   }
3582 
3583   // Normalize the shuffle vector since mask and vector length don't match.
3584   if (SrcNumElts < MaskNumElts) {
3585     // Mask is longer than the source vectors. We can use concatenate vector to
3586     // make the mask and vectors lengths match.
3587 
3588     if (MaskNumElts % SrcNumElts == 0) {
3589       // Mask length is a multiple of the source vector length.
3590       // Check if the shuffle is some kind of concatenation of the input
3591       // vectors.
3592       unsigned NumConcat = MaskNumElts / SrcNumElts;
3593       bool IsConcat = true;
3594       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3595       for (unsigned i = 0; i != MaskNumElts; ++i) {
3596         int Idx = Mask[i];
3597         if (Idx < 0)
3598           continue;
3599         // Ensure the indices in each SrcVT sized piece are sequential and that
3600         // the same source is used for the whole piece.
3601         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3602             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3603              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3604           IsConcat = false;
3605           break;
3606         }
3607         // Remember which source this index came from.
3608         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3609       }
3610 
3611       // The shuffle is concatenating multiple vectors together. Just emit
3612       // a CONCAT_VECTORS operation.
3613       if (IsConcat) {
3614         SmallVector<SDValue, 8> ConcatOps;
3615         for (auto Src : ConcatSrcs) {
3616           if (Src < 0)
3617             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3618           else if (Src == 0)
3619             ConcatOps.push_back(Src1);
3620           else
3621             ConcatOps.push_back(Src2);
3622         }
3623         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3624         return;
3625       }
3626     }
3627 
3628     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3629     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3630     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3631                                     PaddedMaskNumElts);
3632 
3633     // Pad both vectors with undefs to make them the same length as the mask.
3634     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3635 
3636     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3637     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3638     MOps1[0] = Src1;
3639     MOps2[0] = Src2;
3640 
3641     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3642     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3643 
3644     // Readjust mask for new input vector length.
3645     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3646     for (unsigned i = 0; i != MaskNumElts; ++i) {
3647       int Idx = Mask[i];
3648       if (Idx >= (int)SrcNumElts)
3649         Idx -= SrcNumElts - PaddedMaskNumElts;
3650       MappedOps[i] = Idx;
3651     }
3652 
3653     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3654 
3655     // If the concatenated vector was padded, extract a subvector with the
3656     // correct number of elements.
3657     if (MaskNumElts != PaddedMaskNumElts)
3658       Result = DAG.getNode(
3659           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3660           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3661 
3662     setValue(&I, Result);
3663     return;
3664   }
3665 
3666   if (SrcNumElts > MaskNumElts) {
3667     // Analyze the access pattern of the vector to see if we can extract
3668     // two subvectors and do the shuffle.
3669     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3670     bool CanExtract = true;
3671     for (int Idx : Mask) {
3672       unsigned Input = 0;
3673       if (Idx < 0)
3674         continue;
3675 
3676       if (Idx >= (int)SrcNumElts) {
3677         Input = 1;
3678         Idx -= SrcNumElts;
3679       }
3680 
3681       // If all the indices come from the same MaskNumElts sized portion of
3682       // the sources we can use extract. Also make sure the extract wouldn't
3683       // extract past the end of the source.
3684       int NewStartIdx = alignDown(Idx, MaskNumElts);
3685       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3686           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3687         CanExtract = false;
3688       // Make sure we always update StartIdx as we use it to track if all
3689       // elements are undef.
3690       StartIdx[Input] = NewStartIdx;
3691     }
3692 
3693     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3694       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3695       return;
3696     }
3697     if (CanExtract) {
3698       // Extract appropriate subvector and generate a vector shuffle
3699       for (unsigned Input = 0; Input < 2; ++Input) {
3700         SDValue &Src = Input == 0 ? Src1 : Src2;
3701         if (StartIdx[Input] < 0)
3702           Src = DAG.getUNDEF(VT);
3703         else {
3704           Src = DAG.getNode(
3705               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3706               DAG.getConstant(StartIdx[Input], DL,
3707                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3708         }
3709       }
3710 
3711       // Calculate new mask.
3712       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3713       for (int &Idx : MappedOps) {
3714         if (Idx >= (int)SrcNumElts)
3715           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3716         else if (Idx >= 0)
3717           Idx -= StartIdx[0];
3718       }
3719 
3720       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3721       return;
3722     }
3723   }
3724 
3725   // We can't use either concat vectors or extract subvectors so fall back to
3726   // replacing the shuffle with extract and build vector.
3727   // to insert and build vector.
3728   EVT EltVT = VT.getVectorElementType();
3729   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3730   SmallVector<SDValue,8> Ops;
3731   for (int Idx : Mask) {
3732     SDValue Res;
3733 
3734     if (Idx < 0) {
3735       Res = DAG.getUNDEF(EltVT);
3736     } else {
3737       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3738       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3739 
3740       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3741                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3742     }
3743 
3744     Ops.push_back(Res);
3745   }
3746 
3747   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3748 }
3749 
3750 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3751   ArrayRef<unsigned> Indices;
3752   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3753     Indices = IV->getIndices();
3754   else
3755     Indices = cast<ConstantExpr>(&I)->getIndices();
3756 
3757   const Value *Op0 = I.getOperand(0);
3758   const Value *Op1 = I.getOperand(1);
3759   Type *AggTy = I.getType();
3760   Type *ValTy = Op1->getType();
3761   bool IntoUndef = isa<UndefValue>(Op0);
3762   bool FromUndef = isa<UndefValue>(Op1);
3763 
3764   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3765 
3766   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3767   SmallVector<EVT, 4> AggValueVTs;
3768   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3769   SmallVector<EVT, 4> ValValueVTs;
3770   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3771 
3772   unsigned NumAggValues = AggValueVTs.size();
3773   unsigned NumValValues = ValValueVTs.size();
3774   SmallVector<SDValue, 4> Values(NumAggValues);
3775 
3776   // Ignore an insertvalue that produces an empty object
3777   if (!NumAggValues) {
3778     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3779     return;
3780   }
3781 
3782   SDValue Agg = getValue(Op0);
3783   unsigned i = 0;
3784   // Copy the beginning value(s) from the original aggregate.
3785   for (; i != LinearIndex; ++i)
3786     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3787                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3788   // Copy values from the inserted value(s).
3789   if (NumValValues) {
3790     SDValue Val = getValue(Op1);
3791     for (; i != LinearIndex + NumValValues; ++i)
3792       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3793                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3794   }
3795   // Copy remaining value(s) from the original aggregate.
3796   for (; i != NumAggValues; ++i)
3797     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3798                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3799 
3800   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3801                            DAG.getVTList(AggValueVTs), Values));
3802 }
3803 
3804 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3805   ArrayRef<unsigned> Indices;
3806   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3807     Indices = EV->getIndices();
3808   else
3809     Indices = cast<ConstantExpr>(&I)->getIndices();
3810 
3811   const Value *Op0 = I.getOperand(0);
3812   Type *AggTy = Op0->getType();
3813   Type *ValTy = I.getType();
3814   bool OutOfUndef = isa<UndefValue>(Op0);
3815 
3816   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3817 
3818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3819   SmallVector<EVT, 4> ValValueVTs;
3820   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3821 
3822   unsigned NumValValues = ValValueVTs.size();
3823 
3824   // Ignore a extractvalue that produces an empty object
3825   if (!NumValValues) {
3826     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3827     return;
3828   }
3829 
3830   SmallVector<SDValue, 4> Values(NumValValues);
3831 
3832   SDValue Agg = getValue(Op0);
3833   // Copy out the selected value(s).
3834   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3835     Values[i - LinearIndex] =
3836       OutOfUndef ?
3837         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3838         SDValue(Agg.getNode(), Agg.getResNo() + i);
3839 
3840   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3841                            DAG.getVTList(ValValueVTs), Values));
3842 }
3843 
3844 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3845   Value *Op0 = I.getOperand(0);
3846   // Note that the pointer operand may be a vector of pointers. Take the scalar
3847   // element which holds a pointer.
3848   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3849   SDValue N = getValue(Op0);
3850   SDLoc dl = getCurSDLoc();
3851   auto &TLI = DAG.getTargetLoweringInfo();
3852   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
3853   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
3854 
3855   // Normalize Vector GEP - all scalar operands should be converted to the
3856   // splat vector.
3857   unsigned VectorWidth = I.getType()->isVectorTy() ?
3858     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3859 
3860   if (VectorWidth && !N.getValueType().isVector()) {
3861     LLVMContext &Context = *DAG.getContext();
3862     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3863     N = DAG.getSplatBuildVector(VT, dl, N);
3864   }
3865 
3866   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3867        GTI != E; ++GTI) {
3868     const Value *Idx = GTI.getOperand();
3869     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3870       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3871       if (Field) {
3872         // N = N + Offset
3873         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3874 
3875         // In an inbounds GEP with an offset that is nonnegative even when
3876         // interpreted as signed, assume there is no unsigned overflow.
3877         SDNodeFlags Flags;
3878         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3879           Flags.setNoUnsignedWrap(true);
3880 
3881         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3882                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3883       }
3884     } else {
3885       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3886       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3887       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3888 
3889       // If this is a scalar constant or a splat vector of constants,
3890       // handle it quickly.
3891       const auto *CI = dyn_cast<ConstantInt>(Idx);
3892       if (!CI && isa<ConstantDataVector>(Idx) &&
3893           cast<ConstantDataVector>(Idx)->getSplatValue())
3894         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3895 
3896       if (CI) {
3897         if (CI->isZero())
3898           continue;
3899         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3900         LLVMContext &Context = *DAG.getContext();
3901         SDValue OffsVal = VectorWidth ?
3902           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3903           DAG.getConstant(Offs, dl, IdxTy);
3904 
3905         // In an inbouds GEP with an offset that is nonnegative even when
3906         // interpreted as signed, assume there is no unsigned overflow.
3907         SDNodeFlags Flags;
3908         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3909           Flags.setNoUnsignedWrap(true);
3910 
3911         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
3912 
3913         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3914         continue;
3915       }
3916 
3917       // N = N + Idx * ElementSize;
3918       SDValue IdxN = getValue(Idx);
3919 
3920       if (!IdxN.getValueType().isVector() && VectorWidth) {
3921         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3922         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3923       }
3924 
3925       // If the index is smaller or larger than intptr_t, truncate or extend
3926       // it.
3927       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3928 
3929       // If this is a multiply by a power of two, turn it into a shl
3930       // immediately.  This is a very common case.
3931       if (ElementSize != 1) {
3932         if (ElementSize.isPowerOf2()) {
3933           unsigned Amt = ElementSize.logBase2();
3934           IdxN = DAG.getNode(ISD::SHL, dl,
3935                              N.getValueType(), IdxN,
3936                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3937         } else {
3938           SDValue Scale = DAG.getConstant(ElementSize.getZExtValue(), dl,
3939                                           IdxN.getValueType());
3940           IdxN = DAG.getNode(ISD::MUL, dl,
3941                              N.getValueType(), IdxN, Scale);
3942         }
3943       }
3944 
3945       N = DAG.getNode(ISD::ADD, dl,
3946                       N.getValueType(), N, IdxN);
3947     }
3948   }
3949 
3950   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
3951     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
3952 
3953   setValue(&I, N);
3954 }
3955 
3956 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3957   // If this is a fixed sized alloca in the entry block of the function,
3958   // allocate it statically on the stack.
3959   if (FuncInfo.StaticAllocaMap.count(&I))
3960     return;   // getValue will auto-populate this.
3961 
3962   SDLoc dl = getCurSDLoc();
3963   Type *Ty = I.getAllocatedType();
3964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3965   auto &DL = DAG.getDataLayout();
3966   uint64_t TySize = DL.getTypeAllocSize(Ty);
3967   unsigned Align =
3968       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3969 
3970   SDValue AllocSize = getValue(I.getArraySize());
3971 
3972   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3973   if (AllocSize.getValueType() != IntPtr)
3974     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3975 
3976   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3977                           AllocSize,
3978                           DAG.getConstant(TySize, dl, IntPtr));
3979 
3980   // Handle alignment.  If the requested alignment is less than or equal to
3981   // the stack alignment, ignore it.  If the size is greater than or equal to
3982   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3983   unsigned StackAlign =
3984       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3985   if (Align <= StackAlign)
3986     Align = 0;
3987 
3988   // Round the size of the allocation up to the stack alignment size
3989   // by add SA-1 to the size. This doesn't overflow because we're computing
3990   // an address inside an alloca.
3991   SDNodeFlags Flags;
3992   Flags.setNoUnsignedWrap(true);
3993   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3994                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3995 
3996   // Mask out the low bits for alignment purposes.
3997   AllocSize =
3998       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3999                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
4000 
4001   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
4002   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4003   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4004   setValue(&I, DSA);
4005   DAG.setRoot(DSA.getValue(1));
4006 
4007   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4008 }
4009 
4010 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4011   if (I.isAtomic())
4012     return visitAtomicLoad(I);
4013 
4014   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4015   const Value *SV = I.getOperand(0);
4016   if (TLI.supportSwiftError()) {
4017     // Swifterror values can come from either a function parameter with
4018     // swifterror attribute or an alloca with swifterror attribute.
4019     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4020       if (Arg->hasSwiftErrorAttr())
4021         return visitLoadFromSwiftError(I);
4022     }
4023 
4024     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4025       if (Alloca->isSwiftError())
4026         return visitLoadFromSwiftError(I);
4027     }
4028   }
4029 
4030   SDValue Ptr = getValue(SV);
4031 
4032   Type *Ty = I.getType();
4033 
4034   bool isVolatile = I.isVolatile();
4035   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
4036   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
4037   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
4038   unsigned Alignment = I.getAlignment();
4039 
4040   AAMDNodes AAInfo;
4041   I.getAAMetadata(AAInfo);
4042   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4043 
4044   SmallVector<EVT, 4> ValueVTs, MemVTs;
4045   SmallVector<uint64_t, 4> Offsets;
4046   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4047   unsigned NumValues = ValueVTs.size();
4048   if (NumValues == 0)
4049     return;
4050 
4051   SDValue Root;
4052   bool ConstantMemory = false;
4053   if (isVolatile || NumValues > MaxParallelChains)
4054     // Serialize volatile loads with other side effects.
4055     Root = getRoot();
4056   else if (AA &&
4057            AA->pointsToConstantMemory(MemoryLocation(
4058                SV,
4059                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4060                AAInfo))) {
4061     // Do not serialize (non-volatile) loads of constant memory with anything.
4062     Root = DAG.getEntryNode();
4063     ConstantMemory = true;
4064   } else {
4065     // Do not serialize non-volatile loads against each other.
4066     Root = DAG.getRoot();
4067   }
4068 
4069   SDLoc dl = getCurSDLoc();
4070 
4071   if (isVolatile)
4072     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4073 
4074   // An aggregate load cannot wrap around the address space, so offsets to its
4075   // parts don't wrap either.
4076   SDNodeFlags Flags;
4077   Flags.setNoUnsignedWrap(true);
4078 
4079   SmallVector<SDValue, 4> Values(NumValues);
4080   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4081   EVT PtrVT = Ptr.getValueType();
4082   unsigned ChainI = 0;
4083   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4084     // Serializing loads here may result in excessive register pressure, and
4085     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4086     // could recover a bit by hoisting nodes upward in the chain by recognizing
4087     // they are side-effect free or do not alias. The optimizer should really
4088     // avoid this case by converting large object/array copies to llvm.memcpy
4089     // (MaxParallelChains should always remain as failsafe).
4090     if (ChainI == MaxParallelChains) {
4091       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4092       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4093                                   makeArrayRef(Chains.data(), ChainI));
4094       Root = Chain;
4095       ChainI = 0;
4096     }
4097     SDValue A = DAG.getNode(ISD::ADD, dl,
4098                             PtrVT, Ptr,
4099                             DAG.getConstant(Offsets[i], dl, PtrVT),
4100                             Flags);
4101     auto MMOFlags = MachineMemOperand::MONone;
4102     if (isVolatile)
4103       MMOFlags |= MachineMemOperand::MOVolatile;
4104     if (isNonTemporal)
4105       MMOFlags |= MachineMemOperand::MONonTemporal;
4106     if (isInvariant)
4107       MMOFlags |= MachineMemOperand::MOInvariant;
4108     if (isDereferenceable)
4109       MMOFlags |= MachineMemOperand::MODereferenceable;
4110     MMOFlags |= TLI.getMMOFlags(I);
4111 
4112     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A,
4113                             MachinePointerInfo(SV, Offsets[i]), Alignment,
4114                             MMOFlags, AAInfo, Ranges);
4115     Chains[ChainI] = L.getValue(1);
4116 
4117     if (MemVTs[i] != ValueVTs[i])
4118       L = DAG.getZExtOrTrunc(L, dl, ValueVTs[i]);
4119 
4120     Values[i] = L;
4121   }
4122 
4123   if (!ConstantMemory) {
4124     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4125                                 makeArrayRef(Chains.data(), ChainI));
4126     if (isVolatile)
4127       DAG.setRoot(Chain);
4128     else
4129       PendingLoads.push_back(Chain);
4130   }
4131 
4132   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4133                            DAG.getVTList(ValueVTs), Values));
4134 }
4135 
4136 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4137   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4138          "call visitStoreToSwiftError when backend supports swifterror");
4139 
4140   SmallVector<EVT, 4> ValueVTs;
4141   SmallVector<uint64_t, 4> Offsets;
4142   const Value *SrcV = I.getOperand(0);
4143   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4144                   SrcV->getType(), ValueVTs, &Offsets);
4145   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4146          "expect a single EVT for swifterror");
4147 
4148   SDValue Src = getValue(SrcV);
4149   // Create a virtual register, then update the virtual register.
4150   unsigned VReg =
4151       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4152   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4153   // Chain can be getRoot or getControlRoot.
4154   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4155                                       SDValue(Src.getNode(), Src.getResNo()));
4156   DAG.setRoot(CopyNode);
4157 }
4158 
4159 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4160   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4161          "call visitLoadFromSwiftError when backend supports swifterror");
4162 
4163   assert(!I.isVolatile() &&
4164          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
4165          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
4166          "Support volatile, non temporal, invariant for load_from_swift_error");
4167 
4168   const Value *SV = I.getOperand(0);
4169   Type *Ty = I.getType();
4170   AAMDNodes AAInfo;
4171   I.getAAMetadata(AAInfo);
4172   assert(
4173       (!AA ||
4174        !AA->pointsToConstantMemory(MemoryLocation(
4175            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4176            AAInfo))) &&
4177       "load_from_swift_error should not be constant memory");
4178 
4179   SmallVector<EVT, 4> ValueVTs;
4180   SmallVector<uint64_t, 4> Offsets;
4181   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4182                   ValueVTs, &Offsets);
4183   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4184          "expect a single EVT for swifterror");
4185 
4186   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4187   SDValue L = DAG.getCopyFromReg(
4188       getRoot(), getCurSDLoc(),
4189       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4190 
4191   setValue(&I, L);
4192 }
4193 
4194 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4195   if (I.isAtomic())
4196     return visitAtomicStore(I);
4197 
4198   const Value *SrcV = I.getOperand(0);
4199   const Value *PtrV = I.getOperand(1);
4200 
4201   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4202   if (TLI.supportSwiftError()) {
4203     // Swifterror values can come from either a function parameter with
4204     // swifterror attribute or an alloca with swifterror attribute.
4205     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4206       if (Arg->hasSwiftErrorAttr())
4207         return visitStoreToSwiftError(I);
4208     }
4209 
4210     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4211       if (Alloca->isSwiftError())
4212         return visitStoreToSwiftError(I);
4213     }
4214   }
4215 
4216   SmallVector<EVT, 4> ValueVTs, MemVTs;
4217   SmallVector<uint64_t, 4> Offsets;
4218   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4219                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4220   unsigned NumValues = ValueVTs.size();
4221   if (NumValues == 0)
4222     return;
4223 
4224   // Get the lowered operands. Note that we do this after
4225   // checking if NumResults is zero, because with zero results
4226   // the operands won't have values in the map.
4227   SDValue Src = getValue(SrcV);
4228   SDValue Ptr = getValue(PtrV);
4229 
4230   SDValue Root = getRoot();
4231   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4232   SDLoc dl = getCurSDLoc();
4233   EVT PtrVT = Ptr.getValueType();
4234   unsigned Alignment = I.getAlignment();
4235   AAMDNodes AAInfo;
4236   I.getAAMetadata(AAInfo);
4237 
4238   auto MMOFlags = MachineMemOperand::MONone;
4239   if (I.isVolatile())
4240     MMOFlags |= MachineMemOperand::MOVolatile;
4241   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
4242     MMOFlags |= MachineMemOperand::MONonTemporal;
4243   MMOFlags |= TLI.getMMOFlags(I);
4244 
4245   // An aggregate load cannot wrap around the address space, so offsets to its
4246   // parts don't wrap either.
4247   SDNodeFlags Flags;
4248   Flags.setNoUnsignedWrap(true);
4249 
4250   unsigned ChainI = 0;
4251   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4252     // See visitLoad comments.
4253     if (ChainI == MaxParallelChains) {
4254       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4255                                   makeArrayRef(Chains.data(), ChainI));
4256       Root = Chain;
4257       ChainI = 0;
4258     }
4259     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
4260                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
4261     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4262     if (MemVTs[i] != ValueVTs[i])
4263       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4264     SDValue St =
4265         DAG.getStore(Root, dl, Val, Add, MachinePointerInfo(PtrV, Offsets[i]),
4266                      Alignment, MMOFlags, AAInfo);
4267     Chains[ChainI] = St;
4268   }
4269 
4270   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4271                                   makeArrayRef(Chains.data(), ChainI));
4272   DAG.setRoot(StoreNode);
4273 }
4274 
4275 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4276                                            bool IsCompressing) {
4277   SDLoc sdl = getCurSDLoc();
4278 
4279   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4280                            unsigned& Alignment) {
4281     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4282     Src0 = I.getArgOperand(0);
4283     Ptr = I.getArgOperand(1);
4284     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
4285     Mask = I.getArgOperand(3);
4286   };
4287   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4288                            unsigned& Alignment) {
4289     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4290     Src0 = I.getArgOperand(0);
4291     Ptr = I.getArgOperand(1);
4292     Mask = I.getArgOperand(2);
4293     Alignment = 0;
4294   };
4295 
4296   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4297   unsigned Alignment;
4298   if (IsCompressing)
4299     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4300   else
4301     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4302 
4303   SDValue Ptr = getValue(PtrOperand);
4304   SDValue Src0 = getValue(Src0Operand);
4305   SDValue Mask = getValue(MaskOperand);
4306 
4307   EVT VT = Src0.getValueType();
4308   if (!Alignment)
4309     Alignment = DAG.getEVTAlignment(VT);
4310 
4311   AAMDNodes AAInfo;
4312   I.getAAMetadata(AAInfo);
4313 
4314   MachineMemOperand *MMO =
4315     DAG.getMachineFunction().
4316     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4317                           MachineMemOperand::MOStore,  VT.getStoreSize(),
4318                           Alignment, AAInfo);
4319   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
4320                                          MMO, false /* Truncating */,
4321                                          IsCompressing);
4322   DAG.setRoot(StoreNode);
4323   setValue(&I, StoreNode);
4324 }
4325 
4326 // Get a uniform base for the Gather/Scatter intrinsic.
4327 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4328 // We try to represent it as a base pointer + vector of indices.
4329 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4330 // The first operand of the GEP may be a single pointer or a vector of pointers
4331 // Example:
4332 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4333 //  or
4334 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4335 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4336 //
4337 // When the first GEP operand is a single pointer - it is the uniform base we
4338 // are looking for. If first operand of the GEP is a splat vector - we
4339 // extract the splat value and use it as a uniform base.
4340 // In all other cases the function returns 'false'.
4341 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
4342                            SDValue &Scale, SelectionDAGBuilder* SDB) {
4343   SelectionDAG& DAG = SDB->DAG;
4344   LLVMContext &Context = *DAG.getContext();
4345 
4346   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
4347   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4348   if (!GEP)
4349     return false;
4350 
4351   const Value *GEPPtr = GEP->getPointerOperand();
4352   if (!GEPPtr->getType()->isVectorTy())
4353     Ptr = GEPPtr;
4354   else if (!(Ptr = getSplatValue(GEPPtr)))
4355     return false;
4356 
4357   unsigned FinalIndex = GEP->getNumOperands() - 1;
4358   Value *IndexVal = GEP->getOperand(FinalIndex);
4359 
4360   // Ensure all the other indices are 0.
4361   for (unsigned i = 1; i < FinalIndex; ++i) {
4362     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
4363     if (!C || !C->isZero())
4364       return false;
4365   }
4366 
4367   // The operands of the GEP may be defined in another basic block.
4368   // In this case we'll not find nodes for the operands.
4369   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
4370     return false;
4371 
4372   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4373   const DataLayout &DL = DAG.getDataLayout();
4374   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4375                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4376   Base = SDB->getValue(Ptr);
4377   Index = SDB->getValue(IndexVal);
4378 
4379   if (!Index.getValueType().isVector()) {
4380     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4381     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4382     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4383   }
4384   return true;
4385 }
4386 
4387 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4388   SDLoc sdl = getCurSDLoc();
4389 
4390   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4391   const Value *Ptr = I.getArgOperand(1);
4392   SDValue Src0 = getValue(I.getArgOperand(0));
4393   SDValue Mask = getValue(I.getArgOperand(3));
4394   EVT VT = Src0.getValueType();
4395   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4396   if (!Alignment)
4397     Alignment = DAG.getEVTAlignment(VT);
4398   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4399 
4400   AAMDNodes AAInfo;
4401   I.getAAMetadata(AAInfo);
4402 
4403   SDValue Base;
4404   SDValue Index;
4405   SDValue Scale;
4406   const Value *BasePtr = Ptr;
4407   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4408 
4409   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4410   MachineMemOperand *MMO = DAG.getMachineFunction().
4411     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4412                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4413                          Alignment, AAInfo);
4414   if (!UniformBase) {
4415     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4416     Index = getValue(Ptr);
4417     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4418   }
4419   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4420   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4421                                          Ops, MMO);
4422   DAG.setRoot(Scatter);
4423   setValue(&I, Scatter);
4424 }
4425 
4426 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4427   SDLoc sdl = getCurSDLoc();
4428 
4429   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4430                            unsigned& Alignment) {
4431     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4432     Ptr = I.getArgOperand(0);
4433     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4434     Mask = I.getArgOperand(2);
4435     Src0 = I.getArgOperand(3);
4436   };
4437   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4438                            unsigned& Alignment) {
4439     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4440     Ptr = I.getArgOperand(0);
4441     Alignment = 0;
4442     Mask = I.getArgOperand(1);
4443     Src0 = I.getArgOperand(2);
4444   };
4445 
4446   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4447   unsigned Alignment;
4448   if (IsExpanding)
4449     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4450   else
4451     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4452 
4453   SDValue Ptr = getValue(PtrOperand);
4454   SDValue Src0 = getValue(Src0Operand);
4455   SDValue Mask = getValue(MaskOperand);
4456 
4457   EVT VT = Src0.getValueType();
4458   if (!Alignment)
4459     Alignment = DAG.getEVTAlignment(VT);
4460 
4461   AAMDNodes AAInfo;
4462   I.getAAMetadata(AAInfo);
4463   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4464 
4465   // Do not serialize masked loads of constant memory with anything.
4466   bool AddToChain =
4467       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4468                  PtrOperand,
4469                  LocationSize::precise(
4470                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4471                  AAInfo));
4472   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4473 
4474   MachineMemOperand *MMO =
4475     DAG.getMachineFunction().
4476     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4477                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4478                           Alignment, AAInfo, Ranges);
4479 
4480   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4481                                    ISD::NON_EXTLOAD, IsExpanding);
4482   if (AddToChain)
4483     PendingLoads.push_back(Load.getValue(1));
4484   setValue(&I, Load);
4485 }
4486 
4487 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4488   SDLoc sdl = getCurSDLoc();
4489 
4490   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4491   const Value *Ptr = I.getArgOperand(0);
4492   SDValue Src0 = getValue(I.getArgOperand(3));
4493   SDValue Mask = getValue(I.getArgOperand(2));
4494 
4495   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4496   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4497   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4498   if (!Alignment)
4499     Alignment = DAG.getEVTAlignment(VT);
4500 
4501   AAMDNodes AAInfo;
4502   I.getAAMetadata(AAInfo);
4503   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4504 
4505   SDValue Root = DAG.getRoot();
4506   SDValue Base;
4507   SDValue Index;
4508   SDValue Scale;
4509   const Value *BasePtr = Ptr;
4510   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4511   bool ConstantMemory = false;
4512   if (UniformBase && AA &&
4513       AA->pointsToConstantMemory(
4514           MemoryLocation(BasePtr,
4515                          LocationSize::precise(
4516                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4517                          AAInfo))) {
4518     // Do not serialize (non-volatile) loads of constant memory with anything.
4519     Root = DAG.getEntryNode();
4520     ConstantMemory = true;
4521   }
4522 
4523   MachineMemOperand *MMO =
4524     DAG.getMachineFunction().
4525     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4526                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4527                          Alignment, AAInfo, Ranges);
4528 
4529   if (!UniformBase) {
4530     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4531     Index = getValue(Ptr);
4532     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4533   }
4534   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4535   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4536                                        Ops, MMO);
4537 
4538   SDValue OutChain = Gather.getValue(1);
4539   if (!ConstantMemory)
4540     PendingLoads.push_back(OutChain);
4541   setValue(&I, Gather);
4542 }
4543 
4544 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4545   SDLoc dl = getCurSDLoc();
4546   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4547   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4548   SyncScope::ID SSID = I.getSyncScopeID();
4549 
4550   SDValue InChain = getRoot();
4551 
4552   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4553   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4554 
4555   auto Alignment = DAG.getEVTAlignment(MemVT);
4556 
4557   auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
4558   if (I.isVolatile())
4559     Flags |= MachineMemOperand::MOVolatile;
4560   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4561 
4562   MachineFunction &MF = DAG.getMachineFunction();
4563   MachineMemOperand *MMO =
4564     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4565                             Flags, MemVT.getStoreSize(), Alignment,
4566                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
4567                             FailureOrdering);
4568 
4569   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
4570                                    dl, MemVT, VTs, InChain,
4571                                    getValue(I.getPointerOperand()),
4572                                    getValue(I.getCompareOperand()),
4573                                    getValue(I.getNewValOperand()), MMO);
4574 
4575   SDValue OutChain = L.getValue(2);
4576 
4577   setValue(&I, L);
4578   DAG.setRoot(OutChain);
4579 }
4580 
4581 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4582   SDLoc dl = getCurSDLoc();
4583   ISD::NodeType NT;
4584   switch (I.getOperation()) {
4585   default: llvm_unreachable("Unknown atomicrmw operation");
4586   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4587   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4588   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4589   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4590   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4591   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4592   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4593   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4594   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4595   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4596   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4597   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
4598   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
4599   }
4600   AtomicOrdering Ordering = I.getOrdering();
4601   SyncScope::ID SSID = I.getSyncScopeID();
4602 
4603   SDValue InChain = getRoot();
4604 
4605   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
4606   auto Alignment = DAG.getEVTAlignment(MemVT);
4607 
4608   auto Flags = MachineMemOperand::MOLoad |  MachineMemOperand::MOStore;
4609   if (I.isVolatile())
4610     Flags |= MachineMemOperand::MOVolatile;
4611   Flags |= DAG.getTargetLoweringInfo().getMMOFlags(I);
4612 
4613   MachineFunction &MF = DAG.getMachineFunction();
4614   MachineMemOperand *MMO =
4615     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4616                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
4617                             nullptr, SSID, Ordering);
4618 
4619   SDValue L =
4620     DAG.getAtomic(NT, dl, MemVT, InChain,
4621                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
4622                   MMO);
4623 
4624   SDValue OutChain = L.getValue(1);
4625 
4626   setValue(&I, L);
4627   DAG.setRoot(OutChain);
4628 }
4629 
4630 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4631   SDLoc dl = getCurSDLoc();
4632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4633   SDValue Ops[3];
4634   Ops[0] = getRoot();
4635   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4636                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4637   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4638                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4639   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4640 }
4641 
4642 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4643   SDLoc dl = getCurSDLoc();
4644   AtomicOrdering Order = I.getOrdering();
4645   SyncScope::ID SSID = I.getSyncScopeID();
4646 
4647   SDValue InChain = getRoot();
4648 
4649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4650   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4651   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
4652 
4653   if (!TLI.supportsUnalignedAtomics() &&
4654       I.getAlignment() < MemVT.getSizeInBits() / 8)
4655     report_fatal_error("Cannot generate unaligned atomic load");
4656 
4657   auto Flags = MachineMemOperand::MOLoad;
4658   if (I.isVolatile())
4659     Flags |= MachineMemOperand::MOVolatile;
4660   if (I.getMetadata(LLVMContext::MD_invariant_load) != nullptr)
4661     Flags |= MachineMemOperand::MOInvariant;
4662   if (isDereferenceablePointer(I.getPointerOperand(), DAG.getDataLayout()))
4663     Flags |= MachineMemOperand::MODereferenceable;
4664 
4665   Flags |= TLI.getMMOFlags(I);
4666 
4667   MachineMemOperand *MMO =
4668       DAG.getMachineFunction().
4669       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4670                            Flags, MemVT.getStoreSize(),
4671                            I.getAlignment() ? I.getAlignment() :
4672                                               DAG.getEVTAlignment(MemVT),
4673                            AAMDNodes(), nullptr, SSID, Order);
4674 
4675   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4676   SDValue L =
4677       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
4678                     getValue(I.getPointerOperand()), MMO);
4679 
4680   SDValue OutChain = L.getValue(1);
4681   if (MemVT != VT)
4682     L = DAG.getPtrExtOrTrunc(L, dl, VT);
4683 
4684   setValue(&I, L);
4685   DAG.setRoot(OutChain);
4686 }
4687 
4688 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4689   SDLoc dl = getCurSDLoc();
4690 
4691   AtomicOrdering Ordering = I.getOrdering();
4692   SyncScope::ID SSID = I.getSyncScopeID();
4693 
4694   SDValue InChain = getRoot();
4695 
4696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4697   EVT MemVT =
4698       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4699 
4700   if (I.getAlignment() < MemVT.getSizeInBits() / 8)
4701     report_fatal_error("Cannot generate unaligned atomic store");
4702 
4703   auto Flags = MachineMemOperand::MOStore;
4704   if (I.isVolatile())
4705     Flags |= MachineMemOperand::MOVolatile;
4706   Flags |= TLI.getMMOFlags(I);
4707 
4708   MachineFunction &MF = DAG.getMachineFunction();
4709   MachineMemOperand *MMO =
4710     MF.getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), Flags,
4711                             MemVT.getStoreSize(), I.getAlignment(), AAMDNodes(),
4712                             nullptr, SSID, Ordering);
4713 
4714   SDValue Val = getValue(I.getValueOperand());
4715   if (Val.getValueType() != MemVT)
4716     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
4717 
4718   SDValue OutChain = DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain,
4719                                    getValue(I.getPointerOperand()), Val, MMO);
4720 
4721 
4722   DAG.setRoot(OutChain);
4723 }
4724 
4725 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4726 /// node.
4727 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4728                                                unsigned Intrinsic) {
4729   // Ignore the callsite's attributes. A specific call site may be marked with
4730   // readnone, but the lowering code will expect the chain based on the
4731   // definition.
4732   const Function *F = I.getCalledFunction();
4733   bool HasChain = !F->doesNotAccessMemory();
4734   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4735 
4736   // Build the operand list.
4737   SmallVector<SDValue, 8> Ops;
4738   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4739     if (OnlyLoad) {
4740       // We don't need to serialize loads against other loads.
4741       Ops.push_back(DAG.getRoot());
4742     } else {
4743       Ops.push_back(getRoot());
4744     }
4745   }
4746 
4747   // Info is set by getTgtMemInstrinsic
4748   TargetLowering::IntrinsicInfo Info;
4749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4750   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4751                                                DAG.getMachineFunction(),
4752                                                Intrinsic);
4753 
4754   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4755   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4756       Info.opc == ISD::INTRINSIC_W_CHAIN)
4757     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4758                                         TLI.getPointerTy(DAG.getDataLayout())));
4759 
4760   // Add all operands of the call to the operand list.
4761   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4762     SDValue Op = getValue(I.getArgOperand(i));
4763     Ops.push_back(Op);
4764   }
4765 
4766   SmallVector<EVT, 4> ValueVTs;
4767   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4768 
4769   if (HasChain)
4770     ValueVTs.push_back(MVT::Other);
4771 
4772   SDVTList VTs = DAG.getVTList(ValueVTs);
4773 
4774   // Create the node.
4775   SDValue Result;
4776   if (IsTgtIntrinsic) {
4777     // This is target intrinsic that touches memory
4778     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4779       Ops, Info.memVT,
4780       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4781       Info.flags, Info.size);
4782   } else if (!HasChain) {
4783     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4784   } else if (!I.getType()->isVoidTy()) {
4785     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4786   } else {
4787     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4788   }
4789 
4790   if (HasChain) {
4791     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4792     if (OnlyLoad)
4793       PendingLoads.push_back(Chain);
4794     else
4795       DAG.setRoot(Chain);
4796   }
4797 
4798   if (!I.getType()->isVoidTy()) {
4799     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4800       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4801       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4802     } else
4803       Result = lowerRangeToAssertZExt(DAG, I, Result);
4804 
4805     setValue(&I, Result);
4806   }
4807 }
4808 
4809 /// GetSignificand - Get the significand and build it into a floating-point
4810 /// number with exponent of 1:
4811 ///
4812 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4813 ///
4814 /// where Op is the hexadecimal representation of floating point value.
4815 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4816   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4817                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4818   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4819                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4820   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4821 }
4822 
4823 /// GetExponent - Get the exponent:
4824 ///
4825 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4826 ///
4827 /// where Op is the hexadecimal representation of floating point value.
4828 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4829                            const TargetLowering &TLI, const SDLoc &dl) {
4830   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4831                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4832   SDValue t1 = DAG.getNode(
4833       ISD::SRL, dl, MVT::i32, t0,
4834       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4835   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4836                            DAG.getConstant(127, dl, MVT::i32));
4837   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4838 }
4839 
4840 /// getF32Constant - Get 32-bit floating point constant.
4841 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4842                               const SDLoc &dl) {
4843   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4844                            MVT::f32);
4845 }
4846 
4847 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4848                                        SelectionDAG &DAG) {
4849   // TODO: What fast-math-flags should be set on the floating-point nodes?
4850 
4851   //   IntegerPartOfX = ((int32_t)(t0);
4852   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4853 
4854   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4855   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4856   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4857 
4858   //   IntegerPartOfX <<= 23;
4859   IntegerPartOfX = DAG.getNode(
4860       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4861       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4862                                   DAG.getDataLayout())));
4863 
4864   SDValue TwoToFractionalPartOfX;
4865   if (LimitFloatPrecision <= 6) {
4866     // For floating-point precision of 6:
4867     //
4868     //   TwoToFractionalPartOfX =
4869     //     0.997535578f +
4870     //       (0.735607626f + 0.252464424f * x) * x;
4871     //
4872     // error 0.0144103317, which is 6 bits
4873     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4874                              getF32Constant(DAG, 0x3e814304, dl));
4875     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4876                              getF32Constant(DAG, 0x3f3c50c8, dl));
4877     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4878     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4879                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4880   } else if (LimitFloatPrecision <= 12) {
4881     // For floating-point precision of 12:
4882     //
4883     //   TwoToFractionalPartOfX =
4884     //     0.999892986f +
4885     //       (0.696457318f +
4886     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4887     //
4888     // error 0.000107046256, which is 13 to 14 bits
4889     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4890                              getF32Constant(DAG, 0x3da235e3, dl));
4891     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4892                              getF32Constant(DAG, 0x3e65b8f3, dl));
4893     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4894     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4895                              getF32Constant(DAG, 0x3f324b07, dl));
4896     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4897     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4898                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4899   } else { // LimitFloatPrecision <= 18
4900     // For floating-point precision of 18:
4901     //
4902     //   TwoToFractionalPartOfX =
4903     //     0.999999982f +
4904     //       (0.693148872f +
4905     //         (0.240227044f +
4906     //           (0.554906021e-1f +
4907     //             (0.961591928e-2f +
4908     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4909     // error 2.47208000*10^(-7), which is better than 18 bits
4910     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4911                              getF32Constant(DAG, 0x3924b03e, dl));
4912     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4913                              getF32Constant(DAG, 0x3ab24b87, dl));
4914     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4915     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4916                              getF32Constant(DAG, 0x3c1d8c17, dl));
4917     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4918     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4919                              getF32Constant(DAG, 0x3d634a1d, dl));
4920     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4921     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4922                              getF32Constant(DAG, 0x3e75fe14, dl));
4923     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4924     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4925                               getF32Constant(DAG, 0x3f317234, dl));
4926     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4927     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4928                                          getF32Constant(DAG, 0x3f800000, dl));
4929   }
4930 
4931   // Add the exponent into the result in integer domain.
4932   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4933   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4934                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4935 }
4936 
4937 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4938 /// limited-precision mode.
4939 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4940                          const TargetLowering &TLI) {
4941   if (Op.getValueType() == MVT::f32 &&
4942       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4943 
4944     // Put the exponent in the right bit position for later addition to the
4945     // final result:
4946     //
4947     //   #define LOG2OFe 1.4426950f
4948     //   t0 = Op * LOG2OFe
4949 
4950     // TODO: What fast-math-flags should be set here?
4951     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4952                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4953     return getLimitedPrecisionExp2(t0, dl, DAG);
4954   }
4955 
4956   // No special expansion.
4957   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4958 }
4959 
4960 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4961 /// limited-precision mode.
4962 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4963                          const TargetLowering &TLI) {
4964   // TODO: What fast-math-flags should be set on the floating-point nodes?
4965 
4966   if (Op.getValueType() == MVT::f32 &&
4967       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4968     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4969 
4970     // Scale the exponent by log(2) [0.69314718f].
4971     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4972     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4973                                         getF32Constant(DAG, 0x3f317218, dl));
4974 
4975     // Get the significand and build it into a floating-point number with
4976     // exponent of 1.
4977     SDValue X = GetSignificand(DAG, Op1, dl);
4978 
4979     SDValue LogOfMantissa;
4980     if (LimitFloatPrecision <= 6) {
4981       // For floating-point precision of 6:
4982       //
4983       //   LogofMantissa =
4984       //     -1.1609546f +
4985       //       (1.4034025f - 0.23903021f * x) * x;
4986       //
4987       // error 0.0034276066, which is better than 8 bits
4988       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4989                                getF32Constant(DAG, 0xbe74c456, dl));
4990       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4991                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4992       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4993       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4994                                   getF32Constant(DAG, 0x3f949a29, dl));
4995     } else if (LimitFloatPrecision <= 12) {
4996       // For floating-point precision of 12:
4997       //
4998       //   LogOfMantissa =
4999       //     -1.7417939f +
5000       //       (2.8212026f +
5001       //         (-1.4699568f +
5002       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5003       //
5004       // error 0.000061011436, which is 14 bits
5005       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5006                                getF32Constant(DAG, 0xbd67b6d6, dl));
5007       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5008                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5009       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5010       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5011                                getF32Constant(DAG, 0x3fbc278b, dl));
5012       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5013       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5014                                getF32Constant(DAG, 0x40348e95, dl));
5015       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5016       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5017                                   getF32Constant(DAG, 0x3fdef31a, dl));
5018     } else { // LimitFloatPrecision <= 18
5019       // For floating-point precision of 18:
5020       //
5021       //   LogOfMantissa =
5022       //     -2.1072184f +
5023       //       (4.2372794f +
5024       //         (-3.7029485f +
5025       //           (2.2781945f +
5026       //             (-0.87823314f +
5027       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5028       //
5029       // error 0.0000023660568, which is better than 18 bits
5030       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5031                                getF32Constant(DAG, 0xbc91e5ac, dl));
5032       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5033                                getF32Constant(DAG, 0x3e4350aa, dl));
5034       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5035       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5036                                getF32Constant(DAG, 0x3f60d3e3, dl));
5037       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5038       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5039                                getF32Constant(DAG, 0x4011cdf0, dl));
5040       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5041       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5042                                getF32Constant(DAG, 0x406cfd1c, dl));
5043       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5044       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5045                                getF32Constant(DAG, 0x408797cb, dl));
5046       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5047       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5048                                   getF32Constant(DAG, 0x4006dcab, dl));
5049     }
5050 
5051     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5052   }
5053 
5054   // No special expansion.
5055   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
5056 }
5057 
5058 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5059 /// limited-precision mode.
5060 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5061                           const TargetLowering &TLI) {
5062   // TODO: What fast-math-flags should be set on the floating-point nodes?
5063 
5064   if (Op.getValueType() == MVT::f32 &&
5065       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5066     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5067 
5068     // Get the exponent.
5069     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5070 
5071     // Get the significand and build it into a floating-point number with
5072     // exponent of 1.
5073     SDValue X = GetSignificand(DAG, Op1, dl);
5074 
5075     // Different possible minimax approximations of significand in
5076     // floating-point for various degrees of accuracy over [1,2].
5077     SDValue Log2ofMantissa;
5078     if (LimitFloatPrecision <= 6) {
5079       // For floating-point precision of 6:
5080       //
5081       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5082       //
5083       // error 0.0049451742, which is more than 7 bits
5084       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5085                                getF32Constant(DAG, 0xbeb08fe0, dl));
5086       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5087                                getF32Constant(DAG, 0x40019463, dl));
5088       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5089       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5090                                    getF32Constant(DAG, 0x3fd6633d, dl));
5091     } else if (LimitFloatPrecision <= 12) {
5092       // For floating-point precision of 12:
5093       //
5094       //   Log2ofMantissa =
5095       //     -2.51285454f +
5096       //       (4.07009056f +
5097       //         (-2.12067489f +
5098       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5099       //
5100       // error 0.0000876136000, which is better than 13 bits
5101       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5102                                getF32Constant(DAG, 0xbda7262e, dl));
5103       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5104                                getF32Constant(DAG, 0x3f25280b, dl));
5105       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5106       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5107                                getF32Constant(DAG, 0x4007b923, dl));
5108       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5109       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5110                                getF32Constant(DAG, 0x40823e2f, dl));
5111       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5112       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5113                                    getF32Constant(DAG, 0x4020d29c, dl));
5114     } else { // LimitFloatPrecision <= 18
5115       // For floating-point precision of 18:
5116       //
5117       //   Log2ofMantissa =
5118       //     -3.0400495f +
5119       //       (6.1129976f +
5120       //         (-5.3420409f +
5121       //           (3.2865683f +
5122       //             (-1.2669343f +
5123       //               (0.27515199f -
5124       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5125       //
5126       // error 0.0000018516, which is better than 18 bits
5127       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5128                                getF32Constant(DAG, 0xbcd2769e, dl));
5129       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5130                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5131       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5132       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5133                                getF32Constant(DAG, 0x3fa22ae7, dl));
5134       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5135       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5136                                getF32Constant(DAG, 0x40525723, dl));
5137       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5138       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5139                                getF32Constant(DAG, 0x40aaf200, dl));
5140       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5141       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5142                                getF32Constant(DAG, 0x40c39dad, dl));
5143       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5144       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5145                                    getF32Constant(DAG, 0x4042902c, dl));
5146     }
5147 
5148     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5149   }
5150 
5151   // No special expansion.
5152   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
5153 }
5154 
5155 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5156 /// limited-precision mode.
5157 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5158                            const TargetLowering &TLI) {
5159   // TODO: What fast-math-flags should be set on the floating-point nodes?
5160 
5161   if (Op.getValueType() == MVT::f32 &&
5162       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5163     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5164 
5165     // Scale the exponent by log10(2) [0.30102999f].
5166     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5167     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5168                                         getF32Constant(DAG, 0x3e9a209a, dl));
5169 
5170     // Get the significand and build it into a floating-point number with
5171     // exponent of 1.
5172     SDValue X = GetSignificand(DAG, Op1, dl);
5173 
5174     SDValue Log10ofMantissa;
5175     if (LimitFloatPrecision <= 6) {
5176       // For floating-point precision of 6:
5177       //
5178       //   Log10ofMantissa =
5179       //     -0.50419619f +
5180       //       (0.60948995f - 0.10380950f * x) * x;
5181       //
5182       // error 0.0014886165, which is 6 bits
5183       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5184                                getF32Constant(DAG, 0xbdd49a13, dl));
5185       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5186                                getF32Constant(DAG, 0x3f1c0789, dl));
5187       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5188       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5189                                     getF32Constant(DAG, 0x3f011300, dl));
5190     } else if (LimitFloatPrecision <= 12) {
5191       // For floating-point precision of 12:
5192       //
5193       //   Log10ofMantissa =
5194       //     -0.64831180f +
5195       //       (0.91751397f +
5196       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5197       //
5198       // error 0.00019228036, which is better than 12 bits
5199       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5200                                getF32Constant(DAG, 0x3d431f31, dl));
5201       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5202                                getF32Constant(DAG, 0x3ea21fb2, dl));
5203       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5204       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5205                                getF32Constant(DAG, 0x3f6ae232, dl));
5206       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5207       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5208                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5209     } else { // LimitFloatPrecision <= 18
5210       // For floating-point precision of 18:
5211       //
5212       //   Log10ofMantissa =
5213       //     -0.84299375f +
5214       //       (1.5327582f +
5215       //         (-1.0688956f +
5216       //           (0.49102474f +
5217       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5218       //
5219       // error 0.0000037995730, which is better than 18 bits
5220       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5221                                getF32Constant(DAG, 0x3c5d51ce, dl));
5222       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5223                                getF32Constant(DAG, 0x3e00685a, dl));
5224       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5225       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5226                                getF32Constant(DAG, 0x3efb6798, dl));
5227       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5228       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5229                                getF32Constant(DAG, 0x3f88d192, dl));
5230       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5231       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5232                                getF32Constant(DAG, 0x3fc4316c, dl));
5233       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5234       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5235                                     getF32Constant(DAG, 0x3f57ce70, dl));
5236     }
5237 
5238     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5239   }
5240 
5241   // No special expansion.
5242   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
5243 }
5244 
5245 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5246 /// limited-precision mode.
5247 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5248                           const TargetLowering &TLI) {
5249   if (Op.getValueType() == MVT::f32 &&
5250       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5251     return getLimitedPrecisionExp2(Op, dl, DAG);
5252 
5253   // No special expansion.
5254   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
5255 }
5256 
5257 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5258 /// limited-precision mode with x == 10.0f.
5259 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5260                          SelectionDAG &DAG, const TargetLowering &TLI) {
5261   bool IsExp10 = false;
5262   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5263       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5264     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5265       APFloat Ten(10.0f);
5266       IsExp10 = LHSC->isExactlyValue(Ten);
5267     }
5268   }
5269 
5270   // TODO: What fast-math-flags should be set on the FMUL node?
5271   if (IsExp10) {
5272     // Put the exponent in the right bit position for later addition to the
5273     // final result:
5274     //
5275     //   #define LOG2OF10 3.3219281f
5276     //   t0 = Op * LOG2OF10;
5277     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5278                              getF32Constant(DAG, 0x40549a78, dl));
5279     return getLimitedPrecisionExp2(t0, dl, DAG);
5280   }
5281 
5282   // No special expansion.
5283   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
5284 }
5285 
5286 /// ExpandPowI - Expand a llvm.powi intrinsic.
5287 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5288                           SelectionDAG &DAG) {
5289   // If RHS is a constant, we can expand this out to a multiplication tree,
5290   // otherwise we end up lowering to a call to __powidf2 (for example).  When
5291   // optimizing for size, we only want to do this if the expansion would produce
5292   // a small number of multiplies, otherwise we do the full expansion.
5293   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5294     // Get the exponent as a positive value.
5295     unsigned Val = RHSC->getSExtValue();
5296     if ((int)Val < 0) Val = -Val;
5297 
5298     // powi(x, 0) -> 1.0
5299     if (Val == 0)
5300       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5301 
5302     const Function &F = DAG.getMachineFunction().getFunction();
5303     if (!F.hasOptSize() ||
5304         // If optimizing for size, don't insert too many multiplies.
5305         // This inserts up to 5 multiplies.
5306         countPopulation(Val) + Log2_32(Val) < 7) {
5307       // We use the simple binary decomposition method to generate the multiply
5308       // sequence.  There are more optimal ways to do this (for example,
5309       // powi(x,15) generates one more multiply than it should), but this has
5310       // the benefit of being both really simple and much better than a libcall.
5311       SDValue Res;  // Logically starts equal to 1.0
5312       SDValue CurSquare = LHS;
5313       // TODO: Intrinsics should have fast-math-flags that propagate to these
5314       // nodes.
5315       while (Val) {
5316         if (Val & 1) {
5317           if (Res.getNode())
5318             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
5319           else
5320             Res = CurSquare;  // 1.0*CurSquare.
5321         }
5322 
5323         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5324                                 CurSquare, CurSquare);
5325         Val >>= 1;
5326       }
5327 
5328       // If the original was negative, invert the result, producing 1/(x*x*x).
5329       if (RHSC->getSExtValue() < 0)
5330         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5331                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5332       return Res;
5333     }
5334   }
5335 
5336   // Otherwise, expand to a libcall.
5337   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5338 }
5339 
5340 // getUnderlyingArgReg - Find underlying register used for a truncated or
5341 // bitcasted argument.
5342 static unsigned getUnderlyingArgReg(const SDValue &N) {
5343   switch (N.getOpcode()) {
5344   case ISD::CopyFromReg:
5345     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
5346   case ISD::BITCAST:
5347   case ISD::AssertZext:
5348   case ISD::AssertSext:
5349   case ISD::TRUNCATE:
5350     return getUnderlyingArgReg(N.getOperand(0));
5351   default:
5352     return 0;
5353   }
5354 }
5355 
5356 /// If the DbgValueInst is a dbg_value of a function argument, create the
5357 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5358 /// instruction selection, they will be inserted to the entry BB.
5359 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5360     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5361     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
5362   const Argument *Arg = dyn_cast<Argument>(V);
5363   if (!Arg)
5364     return false;
5365 
5366   if (!IsDbgDeclare) {
5367     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5368     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5369     // the entry block.
5370     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5371     if (!IsInEntryBlock)
5372       return false;
5373 
5374     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5375     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5376     // variable that also is a param.
5377     //
5378     // Although, if we are at the top of the entry block already, we can still
5379     // emit using ArgDbgValue. This might catch some situations when the
5380     // dbg.value refers to an argument that isn't used in the entry block, so
5381     // any CopyToReg node would be optimized out and the only way to express
5382     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5383     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5384     // we should only emit as ArgDbgValue if the Variable is an argument to the
5385     // current function, and the dbg.value intrinsic is found in the entry
5386     // block.
5387     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5388         !DL->getInlinedAt();
5389     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5390     if (!IsInPrologue && !VariableIsFunctionInputArg)
5391       return false;
5392 
5393     // Here we assume that a function argument on IR level only can be used to
5394     // describe one input parameter on source level. If we for example have
5395     // source code like this
5396     //
5397     //    struct A { long x, y; };
5398     //    void foo(struct A a, long b) {
5399     //      ...
5400     //      b = a.x;
5401     //      ...
5402     //    }
5403     //
5404     // and IR like this
5405     //
5406     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5407     //  entry:
5408     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5409     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5410     //    call void @llvm.dbg.value(metadata i32 %b, "b",
5411     //    ...
5412     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
5413     //    ...
5414     //
5415     // then the last dbg.value is describing a parameter "b" using a value that
5416     // is an argument. But since we already has used %a1 to describe a parameter
5417     // we should not handle that last dbg.value here (that would result in an
5418     // incorrect hoisting of the DBG_VALUE to the function entry).
5419     // Notice that we allow one dbg.value per IR level argument, to accomodate
5420     // for the situation with fragments above.
5421     if (VariableIsFunctionInputArg) {
5422       unsigned ArgNo = Arg->getArgNo();
5423       if (ArgNo >= FuncInfo.DescribedArgs.size())
5424         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
5425       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
5426         return false;
5427       FuncInfo.DescribedArgs.set(ArgNo);
5428     }
5429   }
5430 
5431   MachineFunction &MF = DAG.getMachineFunction();
5432   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5433 
5434   bool IsIndirect = false;
5435   Optional<MachineOperand> Op;
5436   // Some arguments' frame index is recorded during argument lowering.
5437   int FI = FuncInfo.getArgumentFrameIndex(Arg);
5438   if (FI != std::numeric_limits<int>::max())
5439     Op = MachineOperand::CreateFI(FI);
5440 
5441   if (!Op && N.getNode()) {
5442     unsigned Reg = getUnderlyingArgReg(N);
5443     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
5444       MachineRegisterInfo &RegInfo = MF.getRegInfo();
5445       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
5446       if (PR)
5447         Reg = PR;
5448     }
5449     if (Reg) {
5450       Op = MachineOperand::CreateReg(Reg, false);
5451       IsIndirect = IsDbgDeclare;
5452     }
5453   }
5454 
5455   if (!Op && N.getNode()) {
5456     // Check if frame index is available.
5457     SDValue LCandidate = peekThroughBitcasts(N);
5458     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
5459       if (FrameIndexSDNode *FINode =
5460           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
5461         Op = MachineOperand::CreateFI(FINode->getIndex());
5462   }
5463 
5464   if (!Op) {
5465     // Check if ValueMap has reg number.
5466     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
5467     if (VMI != FuncInfo.ValueMap.end()) {
5468       const auto &TLI = DAG.getTargetLoweringInfo();
5469       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
5470                        V->getType(), getABIRegCopyCC(V));
5471       if (RFV.occupiesMultipleRegs()) {
5472         unsigned Offset = 0;
5473         for (auto RegAndSize : RFV.getRegsAndSizes()) {
5474           Op = MachineOperand::CreateReg(RegAndSize.first, false);
5475           auto FragmentExpr = DIExpression::createFragmentExpression(
5476               Expr, Offset, RegAndSize.second);
5477           if (!FragmentExpr)
5478             continue;
5479           FuncInfo.ArgDbgValues.push_back(
5480               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
5481                       Op->getReg(), Variable, *FragmentExpr));
5482           Offset += RegAndSize.second;
5483         }
5484         return true;
5485       }
5486       Op = MachineOperand::CreateReg(VMI->second, false);
5487       IsIndirect = IsDbgDeclare;
5488     }
5489   }
5490 
5491   if (!Op)
5492     return false;
5493 
5494   assert(Variable->isValidLocationForIntrinsic(DL) &&
5495          "Expected inlined-at fields to agree");
5496   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5497   FuncInfo.ArgDbgValues.push_back(
5498       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5499               *Op, Variable, Expr));
5500 
5501   return true;
5502 }
5503 
5504 /// Return the appropriate SDDbgValue based on N.
5505 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5506                                              DILocalVariable *Variable,
5507                                              DIExpression *Expr,
5508                                              const DebugLoc &dl,
5509                                              unsigned DbgSDNodeOrder) {
5510   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5511     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5512     // stack slot locations.
5513     //
5514     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5515     // debug values here after optimization:
5516     //
5517     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5518     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5519     //
5520     // Both describe the direct values of their associated variables.
5521     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5522                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5523   }
5524   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5525                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5526 }
5527 
5528 // VisualStudio defines setjmp as _setjmp
5529 #if defined(_MSC_VER) && defined(setjmp) && \
5530                          !defined(setjmp_undefined_for_msvc)
5531 #  pragma push_macro("setjmp")
5532 #  undef setjmp
5533 #  define setjmp_undefined_for_msvc
5534 #endif
5535 
5536 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
5537   switch (Intrinsic) {
5538   case Intrinsic::smul_fix:
5539     return ISD::SMULFIX;
5540   case Intrinsic::umul_fix:
5541     return ISD::UMULFIX;
5542   default:
5543     llvm_unreachable("Unhandled fixed point intrinsic");
5544   }
5545 }
5546 
5547 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
5548                                            const char *FunctionName) {
5549   assert(FunctionName && "FunctionName must not be nullptr");
5550   SDValue Callee = DAG.getExternalSymbol(
5551       FunctionName,
5552       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
5553   LowerCallTo(&I, Callee, I.isTailCall());
5554 }
5555 
5556 /// Lower the call to the specified intrinsic function.
5557 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
5558                                              unsigned Intrinsic) {
5559   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5560   SDLoc sdl = getCurSDLoc();
5561   DebugLoc dl = getCurDebugLoc();
5562   SDValue Res;
5563 
5564   switch (Intrinsic) {
5565   default:
5566     // By default, turn this into a target intrinsic node.
5567     visitTargetIntrinsic(I, Intrinsic);
5568     return;
5569   case Intrinsic::vastart:  visitVAStart(I); return;
5570   case Intrinsic::vaend:    visitVAEnd(I); return;
5571   case Intrinsic::vacopy:   visitVACopy(I); return;
5572   case Intrinsic::returnaddress:
5573     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5574                              TLI.getPointerTy(DAG.getDataLayout()),
5575                              getValue(I.getArgOperand(0))));
5576     return;
5577   case Intrinsic::addressofreturnaddress:
5578     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5579                              TLI.getPointerTy(DAG.getDataLayout())));
5580     return;
5581   case Intrinsic::sponentry:
5582     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5583                              TLI.getPointerTy(DAG.getDataLayout())));
5584     return;
5585   case Intrinsic::frameaddress:
5586     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5587                              TLI.getPointerTy(DAG.getDataLayout()),
5588                              getValue(I.getArgOperand(0))));
5589     return;
5590   case Intrinsic::read_register: {
5591     Value *Reg = I.getArgOperand(0);
5592     SDValue Chain = getRoot();
5593     SDValue RegName =
5594         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5595     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5596     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5597       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5598     setValue(&I, Res);
5599     DAG.setRoot(Res.getValue(1));
5600     return;
5601   }
5602   case Intrinsic::write_register: {
5603     Value *Reg = I.getArgOperand(0);
5604     Value *RegValue = I.getArgOperand(1);
5605     SDValue Chain = getRoot();
5606     SDValue RegName =
5607         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5608     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5609                             RegName, getValue(RegValue)));
5610     return;
5611   }
5612   case Intrinsic::setjmp:
5613     lowerCallToExternalSymbol(I, &"_setjmp"[!TLI.usesUnderscoreSetJmp()]);
5614     return;
5615   case Intrinsic::longjmp:
5616     lowerCallToExternalSymbol(I, &"_longjmp"[!TLI.usesUnderscoreLongJmp()]);
5617     return;
5618   case Intrinsic::memcpy: {
5619     const auto &MCI = cast<MemCpyInst>(I);
5620     SDValue Op1 = getValue(I.getArgOperand(0));
5621     SDValue Op2 = getValue(I.getArgOperand(1));
5622     SDValue Op3 = getValue(I.getArgOperand(2));
5623     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5624     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5625     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5626     unsigned Align = MinAlign(DstAlign, SrcAlign);
5627     bool isVol = MCI.isVolatile();
5628     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5629     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5630     // node.
5631     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5632                                false, isTC,
5633                                MachinePointerInfo(I.getArgOperand(0)),
5634                                MachinePointerInfo(I.getArgOperand(1)));
5635     updateDAGForMaybeTailCall(MC);
5636     return;
5637   }
5638   case Intrinsic::memset: {
5639     const auto &MSI = cast<MemSetInst>(I);
5640     SDValue Op1 = getValue(I.getArgOperand(0));
5641     SDValue Op2 = getValue(I.getArgOperand(1));
5642     SDValue Op3 = getValue(I.getArgOperand(2));
5643     // @llvm.memset defines 0 and 1 to both mean no alignment.
5644     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5645     bool isVol = MSI.isVolatile();
5646     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5647     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5648                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5649     updateDAGForMaybeTailCall(MS);
5650     return;
5651   }
5652   case Intrinsic::memmove: {
5653     const auto &MMI = cast<MemMoveInst>(I);
5654     SDValue Op1 = getValue(I.getArgOperand(0));
5655     SDValue Op2 = getValue(I.getArgOperand(1));
5656     SDValue Op3 = getValue(I.getArgOperand(2));
5657     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5658     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5659     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5660     unsigned Align = MinAlign(DstAlign, SrcAlign);
5661     bool isVol = MMI.isVolatile();
5662     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5663     // FIXME: Support passing different dest/src alignments to the memmove DAG
5664     // node.
5665     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5666                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5667                                 MachinePointerInfo(I.getArgOperand(1)));
5668     updateDAGForMaybeTailCall(MM);
5669     return;
5670   }
5671   case Intrinsic::memcpy_element_unordered_atomic: {
5672     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5673     SDValue Dst = getValue(MI.getRawDest());
5674     SDValue Src = getValue(MI.getRawSource());
5675     SDValue Length = getValue(MI.getLength());
5676 
5677     unsigned DstAlign = MI.getDestAlignment();
5678     unsigned SrcAlign = MI.getSourceAlignment();
5679     Type *LengthTy = MI.getLength()->getType();
5680     unsigned ElemSz = MI.getElementSizeInBytes();
5681     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5682     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5683                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5684                                      MachinePointerInfo(MI.getRawDest()),
5685                                      MachinePointerInfo(MI.getRawSource()));
5686     updateDAGForMaybeTailCall(MC);
5687     return;
5688   }
5689   case Intrinsic::memmove_element_unordered_atomic: {
5690     auto &MI = cast<AtomicMemMoveInst>(I);
5691     SDValue Dst = getValue(MI.getRawDest());
5692     SDValue Src = getValue(MI.getRawSource());
5693     SDValue Length = getValue(MI.getLength());
5694 
5695     unsigned DstAlign = MI.getDestAlignment();
5696     unsigned SrcAlign = MI.getSourceAlignment();
5697     Type *LengthTy = MI.getLength()->getType();
5698     unsigned ElemSz = MI.getElementSizeInBytes();
5699     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5700     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5701                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5702                                       MachinePointerInfo(MI.getRawDest()),
5703                                       MachinePointerInfo(MI.getRawSource()));
5704     updateDAGForMaybeTailCall(MC);
5705     return;
5706   }
5707   case Intrinsic::memset_element_unordered_atomic: {
5708     auto &MI = cast<AtomicMemSetInst>(I);
5709     SDValue Dst = getValue(MI.getRawDest());
5710     SDValue Val = getValue(MI.getValue());
5711     SDValue Length = getValue(MI.getLength());
5712 
5713     unsigned DstAlign = MI.getDestAlignment();
5714     Type *LengthTy = MI.getLength()->getType();
5715     unsigned ElemSz = MI.getElementSizeInBytes();
5716     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5717     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5718                                      LengthTy, ElemSz, isTC,
5719                                      MachinePointerInfo(MI.getRawDest()));
5720     updateDAGForMaybeTailCall(MC);
5721     return;
5722   }
5723   case Intrinsic::dbg_addr:
5724   case Intrinsic::dbg_declare: {
5725     const auto &DI = cast<DbgVariableIntrinsic>(I);
5726     DILocalVariable *Variable = DI.getVariable();
5727     DIExpression *Expression = DI.getExpression();
5728     dropDanglingDebugInfo(Variable, Expression);
5729     assert(Variable && "Missing variable");
5730 
5731     // Check if address has undef value.
5732     const Value *Address = DI.getVariableLocation();
5733     if (!Address || isa<UndefValue>(Address) ||
5734         (Address->use_empty() && !isa<Argument>(Address))) {
5735       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5736       return;
5737     }
5738 
5739     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5740 
5741     // Check if this variable can be described by a frame index, typically
5742     // either as a static alloca or a byval parameter.
5743     int FI = std::numeric_limits<int>::max();
5744     if (const auto *AI =
5745             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5746       if (AI->isStaticAlloca()) {
5747         auto I = FuncInfo.StaticAllocaMap.find(AI);
5748         if (I != FuncInfo.StaticAllocaMap.end())
5749           FI = I->second;
5750       }
5751     } else if (const auto *Arg = dyn_cast<Argument>(
5752                    Address->stripInBoundsConstantOffsets())) {
5753       FI = FuncInfo.getArgumentFrameIndex(Arg);
5754     }
5755 
5756     // llvm.dbg.addr is control dependent and always generates indirect
5757     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5758     // the MachineFunction variable table.
5759     if (FI != std::numeric_limits<int>::max()) {
5760       if (Intrinsic == Intrinsic::dbg_addr) {
5761         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5762             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5763         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5764       }
5765       return;
5766     }
5767 
5768     SDValue &N = NodeMap[Address];
5769     if (!N.getNode() && isa<Argument>(Address))
5770       // Check unused arguments map.
5771       N = UnusedArgNodeMap[Address];
5772     SDDbgValue *SDV;
5773     if (N.getNode()) {
5774       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5775         Address = BCI->getOperand(0);
5776       // Parameters are handled specially.
5777       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5778       if (isParameter && FINode) {
5779         // Byval parameter. We have a frame index at this point.
5780         SDV =
5781             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5782                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5783       } else if (isa<Argument>(Address)) {
5784         // Address is an argument, so try to emit its dbg value using
5785         // virtual register info from the FuncInfo.ValueMap.
5786         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5787         return;
5788       } else {
5789         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5790                               true, dl, SDNodeOrder);
5791       }
5792       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5793     } else {
5794       // If Address is an argument then try to emit its dbg value using
5795       // virtual register info from the FuncInfo.ValueMap.
5796       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5797                                     N)) {
5798         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5799       }
5800     }
5801     return;
5802   }
5803   case Intrinsic::dbg_label: {
5804     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5805     DILabel *Label = DI.getLabel();
5806     assert(Label && "Missing label");
5807 
5808     SDDbgLabel *SDV;
5809     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5810     DAG.AddDbgLabel(SDV);
5811     return;
5812   }
5813   case Intrinsic::dbg_value: {
5814     const DbgValueInst &DI = cast<DbgValueInst>(I);
5815     assert(DI.getVariable() && "Missing variable");
5816 
5817     DILocalVariable *Variable = DI.getVariable();
5818     DIExpression *Expression = DI.getExpression();
5819     dropDanglingDebugInfo(Variable, Expression);
5820     const Value *V = DI.getValue();
5821     if (!V)
5822       return;
5823 
5824     if (handleDebugValue(V, Variable, Expression, dl, DI.getDebugLoc(),
5825         SDNodeOrder))
5826       return;
5827 
5828     // TODO: Dangling debug info will eventually either be resolved or produce
5829     // an Undef DBG_VALUE. However in the resolution case, a gap may appear
5830     // between the original dbg.value location and its resolved DBG_VALUE, which
5831     // we should ideally fill with an extra Undef DBG_VALUE.
5832 
5833     DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5834     return;
5835   }
5836 
5837   case Intrinsic::eh_typeid_for: {
5838     // Find the type id for the given typeinfo.
5839     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5840     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5841     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5842     setValue(&I, Res);
5843     return;
5844   }
5845 
5846   case Intrinsic::eh_return_i32:
5847   case Intrinsic::eh_return_i64:
5848     DAG.getMachineFunction().setCallsEHReturn(true);
5849     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5850                             MVT::Other,
5851                             getControlRoot(),
5852                             getValue(I.getArgOperand(0)),
5853                             getValue(I.getArgOperand(1))));
5854     return;
5855   case Intrinsic::eh_unwind_init:
5856     DAG.getMachineFunction().setCallsUnwindInit(true);
5857     return;
5858   case Intrinsic::eh_dwarf_cfa:
5859     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5860                              TLI.getPointerTy(DAG.getDataLayout()),
5861                              getValue(I.getArgOperand(0))));
5862     return;
5863   case Intrinsic::eh_sjlj_callsite: {
5864     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5865     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5866     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5867     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5868 
5869     MMI.setCurrentCallSite(CI->getZExtValue());
5870     return;
5871   }
5872   case Intrinsic::eh_sjlj_functioncontext: {
5873     // Get and store the index of the function context.
5874     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5875     AllocaInst *FnCtx =
5876       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5877     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5878     MFI.setFunctionContextIndex(FI);
5879     return;
5880   }
5881   case Intrinsic::eh_sjlj_setjmp: {
5882     SDValue Ops[2];
5883     Ops[0] = getRoot();
5884     Ops[1] = getValue(I.getArgOperand(0));
5885     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5886                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5887     setValue(&I, Op.getValue(0));
5888     DAG.setRoot(Op.getValue(1));
5889     return;
5890   }
5891   case Intrinsic::eh_sjlj_longjmp:
5892     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5893                             getRoot(), getValue(I.getArgOperand(0))));
5894     return;
5895   case Intrinsic::eh_sjlj_setup_dispatch:
5896     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5897                             getRoot()));
5898     return;
5899   case Intrinsic::masked_gather:
5900     visitMaskedGather(I);
5901     return;
5902   case Intrinsic::masked_load:
5903     visitMaskedLoad(I);
5904     return;
5905   case Intrinsic::masked_scatter:
5906     visitMaskedScatter(I);
5907     return;
5908   case Intrinsic::masked_store:
5909     visitMaskedStore(I);
5910     return;
5911   case Intrinsic::masked_expandload:
5912     visitMaskedLoad(I, true /* IsExpanding */);
5913     return;
5914   case Intrinsic::masked_compressstore:
5915     visitMaskedStore(I, true /* IsCompressing */);
5916     return;
5917   case Intrinsic::x86_mmx_pslli_w:
5918   case Intrinsic::x86_mmx_pslli_d:
5919   case Intrinsic::x86_mmx_pslli_q:
5920   case Intrinsic::x86_mmx_psrli_w:
5921   case Intrinsic::x86_mmx_psrli_d:
5922   case Intrinsic::x86_mmx_psrli_q:
5923   case Intrinsic::x86_mmx_psrai_w:
5924   case Intrinsic::x86_mmx_psrai_d: {
5925     SDValue ShAmt = getValue(I.getArgOperand(1));
5926     if (isa<ConstantSDNode>(ShAmt)) {
5927       visitTargetIntrinsic(I, Intrinsic);
5928       return;
5929     }
5930     unsigned NewIntrinsic = 0;
5931     EVT ShAmtVT = MVT::v2i32;
5932     switch (Intrinsic) {
5933     case Intrinsic::x86_mmx_pslli_w:
5934       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5935       break;
5936     case Intrinsic::x86_mmx_pslli_d:
5937       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5938       break;
5939     case Intrinsic::x86_mmx_pslli_q:
5940       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5941       break;
5942     case Intrinsic::x86_mmx_psrli_w:
5943       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5944       break;
5945     case Intrinsic::x86_mmx_psrli_d:
5946       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5947       break;
5948     case Intrinsic::x86_mmx_psrli_q:
5949       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5950       break;
5951     case Intrinsic::x86_mmx_psrai_w:
5952       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5953       break;
5954     case Intrinsic::x86_mmx_psrai_d:
5955       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5956       break;
5957     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5958     }
5959 
5960     // The vector shift intrinsics with scalars uses 32b shift amounts but
5961     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5962     // to be zero.
5963     // We must do this early because v2i32 is not a legal type.
5964     SDValue ShOps[2];
5965     ShOps[0] = ShAmt;
5966     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5967     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5968     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5969     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5970     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5971                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5972                        getValue(I.getArgOperand(0)), ShAmt);
5973     setValue(&I, Res);
5974     return;
5975   }
5976   case Intrinsic::powi:
5977     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5978                             getValue(I.getArgOperand(1)), DAG));
5979     return;
5980   case Intrinsic::log:
5981     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5982     return;
5983   case Intrinsic::log2:
5984     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5985     return;
5986   case Intrinsic::log10:
5987     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5988     return;
5989   case Intrinsic::exp:
5990     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5991     return;
5992   case Intrinsic::exp2:
5993     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5994     return;
5995   case Intrinsic::pow:
5996     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5997                            getValue(I.getArgOperand(1)), DAG, TLI));
5998     return;
5999   case Intrinsic::sqrt:
6000   case Intrinsic::fabs:
6001   case Intrinsic::sin:
6002   case Intrinsic::cos:
6003   case Intrinsic::floor:
6004   case Intrinsic::ceil:
6005   case Intrinsic::trunc:
6006   case Intrinsic::rint:
6007   case Intrinsic::nearbyint:
6008   case Intrinsic::round:
6009   case Intrinsic::canonicalize: {
6010     unsigned Opcode;
6011     switch (Intrinsic) {
6012     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6013     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6014     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6015     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6016     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6017     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6018     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6019     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6020     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6021     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6022     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6023     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6024     }
6025 
6026     setValue(&I, DAG.getNode(Opcode, sdl,
6027                              getValue(I.getArgOperand(0)).getValueType(),
6028                              getValue(I.getArgOperand(0))));
6029     return;
6030   }
6031   case Intrinsic::lround:
6032   case Intrinsic::llround: {
6033     unsigned Opcode;
6034     switch (Intrinsic) {
6035     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6036     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6037     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6038     }
6039 
6040     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6041     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6042                              getValue(I.getArgOperand(0))));
6043     return;
6044   }
6045   case Intrinsic::minnum: {
6046     auto VT = getValue(I.getArgOperand(0)).getValueType();
6047     unsigned Opc =
6048         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
6049             ? ISD::FMINIMUM
6050             : ISD::FMINNUM;
6051     setValue(&I, DAG.getNode(Opc, sdl, VT,
6052                              getValue(I.getArgOperand(0)),
6053                              getValue(I.getArgOperand(1))));
6054     return;
6055   }
6056   case Intrinsic::maxnum: {
6057     auto VT = getValue(I.getArgOperand(0)).getValueType();
6058     unsigned Opc =
6059         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
6060             ? ISD::FMAXIMUM
6061             : ISD::FMAXNUM;
6062     setValue(&I, DAG.getNode(Opc, sdl, VT,
6063                              getValue(I.getArgOperand(0)),
6064                              getValue(I.getArgOperand(1))));
6065     return;
6066   }
6067   case Intrinsic::minimum:
6068     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6069                              getValue(I.getArgOperand(0)).getValueType(),
6070                              getValue(I.getArgOperand(0)),
6071                              getValue(I.getArgOperand(1))));
6072     return;
6073   case Intrinsic::maximum:
6074     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6075                              getValue(I.getArgOperand(0)).getValueType(),
6076                              getValue(I.getArgOperand(0)),
6077                              getValue(I.getArgOperand(1))));
6078     return;
6079   case Intrinsic::copysign:
6080     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6081                              getValue(I.getArgOperand(0)).getValueType(),
6082                              getValue(I.getArgOperand(0)),
6083                              getValue(I.getArgOperand(1))));
6084     return;
6085   case Intrinsic::fma:
6086     setValue(&I, DAG.getNode(ISD::FMA, sdl,
6087                              getValue(I.getArgOperand(0)).getValueType(),
6088                              getValue(I.getArgOperand(0)),
6089                              getValue(I.getArgOperand(1)),
6090                              getValue(I.getArgOperand(2))));
6091     return;
6092   case Intrinsic::experimental_constrained_fadd:
6093   case Intrinsic::experimental_constrained_fsub:
6094   case Intrinsic::experimental_constrained_fmul:
6095   case Intrinsic::experimental_constrained_fdiv:
6096   case Intrinsic::experimental_constrained_frem:
6097   case Intrinsic::experimental_constrained_fma:
6098   case Intrinsic::experimental_constrained_fptrunc:
6099   case Intrinsic::experimental_constrained_fpext:
6100   case Intrinsic::experimental_constrained_sqrt:
6101   case Intrinsic::experimental_constrained_pow:
6102   case Intrinsic::experimental_constrained_powi:
6103   case Intrinsic::experimental_constrained_sin:
6104   case Intrinsic::experimental_constrained_cos:
6105   case Intrinsic::experimental_constrained_exp:
6106   case Intrinsic::experimental_constrained_exp2:
6107   case Intrinsic::experimental_constrained_log:
6108   case Intrinsic::experimental_constrained_log10:
6109   case Intrinsic::experimental_constrained_log2:
6110   case Intrinsic::experimental_constrained_rint:
6111   case Intrinsic::experimental_constrained_nearbyint:
6112   case Intrinsic::experimental_constrained_maxnum:
6113   case Intrinsic::experimental_constrained_minnum:
6114   case Intrinsic::experimental_constrained_ceil:
6115   case Intrinsic::experimental_constrained_floor:
6116   case Intrinsic::experimental_constrained_round:
6117   case Intrinsic::experimental_constrained_trunc:
6118     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6119     return;
6120   case Intrinsic::fmuladd: {
6121     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6122     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6123         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
6124       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6125                                getValue(I.getArgOperand(0)).getValueType(),
6126                                getValue(I.getArgOperand(0)),
6127                                getValue(I.getArgOperand(1)),
6128                                getValue(I.getArgOperand(2))));
6129     } else {
6130       // TODO: Intrinsic calls should have fast-math-flags.
6131       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
6132                                 getValue(I.getArgOperand(0)).getValueType(),
6133                                 getValue(I.getArgOperand(0)),
6134                                 getValue(I.getArgOperand(1)));
6135       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6136                                 getValue(I.getArgOperand(0)).getValueType(),
6137                                 Mul,
6138                                 getValue(I.getArgOperand(2)));
6139       setValue(&I, Add);
6140     }
6141     return;
6142   }
6143   case Intrinsic::convert_to_fp16:
6144     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6145                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6146                                          getValue(I.getArgOperand(0)),
6147                                          DAG.getTargetConstant(0, sdl,
6148                                                                MVT::i32))));
6149     return;
6150   case Intrinsic::convert_from_fp16:
6151     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6152                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6153                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6154                                          getValue(I.getArgOperand(0)))));
6155     return;
6156   case Intrinsic::pcmarker: {
6157     SDValue Tmp = getValue(I.getArgOperand(0));
6158     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6159     return;
6160   }
6161   case Intrinsic::readcyclecounter: {
6162     SDValue Op = getRoot();
6163     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6164                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6165     setValue(&I, Res);
6166     DAG.setRoot(Res.getValue(1));
6167     return;
6168   }
6169   case Intrinsic::bitreverse:
6170     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6171                              getValue(I.getArgOperand(0)).getValueType(),
6172                              getValue(I.getArgOperand(0))));
6173     return;
6174   case Intrinsic::bswap:
6175     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6176                              getValue(I.getArgOperand(0)).getValueType(),
6177                              getValue(I.getArgOperand(0))));
6178     return;
6179   case Intrinsic::cttz: {
6180     SDValue Arg = getValue(I.getArgOperand(0));
6181     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6182     EVT Ty = Arg.getValueType();
6183     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
6184                              sdl, Ty, Arg));
6185     return;
6186   }
6187   case Intrinsic::ctlz: {
6188     SDValue Arg = getValue(I.getArgOperand(0));
6189     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
6190     EVT Ty = Arg.getValueType();
6191     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
6192                              sdl, Ty, Arg));
6193     return;
6194   }
6195   case Intrinsic::ctpop: {
6196     SDValue Arg = getValue(I.getArgOperand(0));
6197     EVT Ty = Arg.getValueType();
6198     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
6199     return;
6200   }
6201   case Intrinsic::fshl:
6202   case Intrinsic::fshr: {
6203     bool IsFSHL = Intrinsic == Intrinsic::fshl;
6204     SDValue X = getValue(I.getArgOperand(0));
6205     SDValue Y = getValue(I.getArgOperand(1));
6206     SDValue Z = getValue(I.getArgOperand(2));
6207     EVT VT = X.getValueType();
6208     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
6209     SDValue Zero = DAG.getConstant(0, sdl, VT);
6210     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
6211 
6212     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
6213     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
6214       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
6215       return;
6216     }
6217 
6218     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
6219     // avoid the select that is necessary in the general case to filter out
6220     // the 0-shift possibility that leads to UB.
6221     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
6222       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
6223       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6224         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
6225         return;
6226       }
6227 
6228       // Some targets only rotate one way. Try the opposite direction.
6229       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
6230       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
6231         // Negate the shift amount because it is safe to ignore the high bits.
6232         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6233         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
6234         return;
6235       }
6236 
6237       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
6238       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
6239       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
6240       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
6241       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
6242       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
6243       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
6244       return;
6245     }
6246 
6247     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
6248     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
6249     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
6250     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
6251     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6252     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
6253 
6254     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
6255     // and that is undefined. We must compare and select to avoid UB.
6256     EVT CCVT = MVT::i1;
6257     if (VT.isVector())
6258       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
6259 
6260     // For fshl, 0-shift returns the 1st arg (X).
6261     // For fshr, 0-shift returns the 2nd arg (Y).
6262     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
6263     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
6264     return;
6265   }
6266   case Intrinsic::sadd_sat: {
6267     SDValue Op1 = getValue(I.getArgOperand(0));
6268     SDValue Op2 = getValue(I.getArgOperand(1));
6269     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6270     return;
6271   }
6272   case Intrinsic::uadd_sat: {
6273     SDValue Op1 = getValue(I.getArgOperand(0));
6274     SDValue Op2 = getValue(I.getArgOperand(1));
6275     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
6276     return;
6277   }
6278   case Intrinsic::ssub_sat: {
6279     SDValue Op1 = getValue(I.getArgOperand(0));
6280     SDValue Op2 = getValue(I.getArgOperand(1));
6281     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6282     return;
6283   }
6284   case Intrinsic::usub_sat: {
6285     SDValue Op1 = getValue(I.getArgOperand(0));
6286     SDValue Op2 = getValue(I.getArgOperand(1));
6287     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
6288     return;
6289   }
6290   case Intrinsic::smul_fix:
6291   case Intrinsic::umul_fix: {
6292     SDValue Op1 = getValue(I.getArgOperand(0));
6293     SDValue Op2 = getValue(I.getArgOperand(1));
6294     SDValue Op3 = getValue(I.getArgOperand(2));
6295     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
6296                              Op1.getValueType(), Op1, Op2, Op3));
6297     return;
6298   }
6299   case Intrinsic::smul_fix_sat: {
6300     SDValue Op1 = getValue(I.getArgOperand(0));
6301     SDValue Op2 = getValue(I.getArgOperand(1));
6302     SDValue Op3 = getValue(I.getArgOperand(2));
6303     setValue(&I, DAG.getNode(ISD::SMULFIXSAT, sdl, Op1.getValueType(), Op1, Op2,
6304                              Op3));
6305     return;
6306   }
6307   case Intrinsic::stacksave: {
6308     SDValue Op = getRoot();
6309     Res = DAG.getNode(
6310         ISD::STACKSAVE, sdl,
6311         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
6312     setValue(&I, Res);
6313     DAG.setRoot(Res.getValue(1));
6314     return;
6315   }
6316   case Intrinsic::stackrestore:
6317     Res = getValue(I.getArgOperand(0));
6318     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
6319     return;
6320   case Intrinsic::get_dynamic_area_offset: {
6321     SDValue Op = getRoot();
6322     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6323     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
6324     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
6325     // target.
6326     if (PtrTy.getSizeInBits() < ResTy.getSizeInBits())
6327       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
6328                          " intrinsic!");
6329     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
6330                       Op);
6331     DAG.setRoot(Op);
6332     setValue(&I, Res);
6333     return;
6334   }
6335   case Intrinsic::stackguard: {
6336     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6337     MachineFunction &MF = DAG.getMachineFunction();
6338     const Module &M = *MF.getFunction().getParent();
6339     SDValue Chain = getRoot();
6340     if (TLI.useLoadStackGuardNode()) {
6341       Res = getLoadStackGuard(DAG, sdl, Chain);
6342     } else {
6343       const Value *Global = TLI.getSDagStackGuard(M);
6344       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
6345       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
6346                         MachinePointerInfo(Global, 0), Align,
6347                         MachineMemOperand::MOVolatile);
6348     }
6349     if (TLI.useStackGuardXorFP())
6350       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
6351     DAG.setRoot(Chain);
6352     setValue(&I, Res);
6353     return;
6354   }
6355   case Intrinsic::stackprotector: {
6356     // Emit code into the DAG to store the stack guard onto the stack.
6357     MachineFunction &MF = DAG.getMachineFunction();
6358     MachineFrameInfo &MFI = MF.getFrameInfo();
6359     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
6360     SDValue Src, Chain = getRoot();
6361 
6362     if (TLI.useLoadStackGuardNode())
6363       Src = getLoadStackGuard(DAG, sdl, Chain);
6364     else
6365       Src = getValue(I.getArgOperand(0));   // The guard's value.
6366 
6367     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
6368 
6369     int FI = FuncInfo.StaticAllocaMap[Slot];
6370     MFI.setStackProtectorIndex(FI);
6371 
6372     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
6373 
6374     // Store the stack protector onto the stack.
6375     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
6376                                                  DAG.getMachineFunction(), FI),
6377                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
6378     setValue(&I, Res);
6379     DAG.setRoot(Res);
6380     return;
6381   }
6382   case Intrinsic::objectsize: {
6383     // If we don't know by now, we're never going to know.
6384     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
6385 
6386     assert(CI && "Non-constant type in __builtin_object_size?");
6387 
6388     SDValue Arg = getValue(I.getCalledValue());
6389     EVT Ty = Arg.getValueType();
6390 
6391     if (CI->isZero())
6392       Res = DAG.getConstant(-1ULL, sdl, Ty);
6393     else
6394       Res = DAG.getConstant(0, sdl, Ty);
6395 
6396     setValue(&I, Res);
6397     return;
6398   }
6399 
6400   case Intrinsic::is_constant:
6401     // If this wasn't constant-folded away by now, then it's not a
6402     // constant.
6403     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
6404     return;
6405 
6406   case Intrinsic::annotation:
6407   case Intrinsic::ptr_annotation:
6408   case Intrinsic::launder_invariant_group:
6409   case Intrinsic::strip_invariant_group:
6410     // Drop the intrinsic, but forward the value
6411     setValue(&I, getValue(I.getOperand(0)));
6412     return;
6413   case Intrinsic::assume:
6414   case Intrinsic::var_annotation:
6415   case Intrinsic::sideeffect:
6416     // Discard annotate attributes, assumptions, and artificial side-effects.
6417     return;
6418 
6419   case Intrinsic::codeview_annotation: {
6420     // Emit a label associated with this metadata.
6421     MachineFunction &MF = DAG.getMachineFunction();
6422     MCSymbol *Label =
6423         MF.getMMI().getContext().createTempSymbol("annotation", true);
6424     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
6425     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
6426     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
6427     DAG.setRoot(Res);
6428     return;
6429   }
6430 
6431   case Intrinsic::init_trampoline: {
6432     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
6433 
6434     SDValue Ops[6];
6435     Ops[0] = getRoot();
6436     Ops[1] = getValue(I.getArgOperand(0));
6437     Ops[2] = getValue(I.getArgOperand(1));
6438     Ops[3] = getValue(I.getArgOperand(2));
6439     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
6440     Ops[5] = DAG.getSrcValue(F);
6441 
6442     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
6443 
6444     DAG.setRoot(Res);
6445     return;
6446   }
6447   case Intrinsic::adjust_trampoline:
6448     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
6449                              TLI.getPointerTy(DAG.getDataLayout()),
6450                              getValue(I.getArgOperand(0))));
6451     return;
6452   case Intrinsic::gcroot: {
6453     assert(DAG.getMachineFunction().getFunction().hasGC() &&
6454            "only valid in functions with gc specified, enforced by Verifier");
6455     assert(GFI && "implied by previous");
6456     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
6457     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
6458 
6459     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
6460     GFI->addStackRoot(FI->getIndex(), TypeMap);
6461     return;
6462   }
6463   case Intrinsic::gcread:
6464   case Intrinsic::gcwrite:
6465     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6466   case Intrinsic::flt_rounds:
6467     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6468     return;
6469 
6470   case Intrinsic::expect:
6471     // Just replace __builtin_expect(exp, c) with EXP.
6472     setValue(&I, getValue(I.getArgOperand(0)));
6473     return;
6474 
6475   case Intrinsic::debugtrap:
6476   case Intrinsic::trap: {
6477     StringRef TrapFuncName =
6478         I.getAttributes()
6479             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6480             .getValueAsString();
6481     if (TrapFuncName.empty()) {
6482       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6483         ISD::TRAP : ISD::DEBUGTRAP;
6484       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6485       return;
6486     }
6487     TargetLowering::ArgListTy Args;
6488 
6489     TargetLowering::CallLoweringInfo CLI(DAG);
6490     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6491         CallingConv::C, I.getType(),
6492         DAG.getExternalSymbol(TrapFuncName.data(),
6493                               TLI.getPointerTy(DAG.getDataLayout())),
6494         std::move(Args));
6495 
6496     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6497     DAG.setRoot(Result.second);
6498     return;
6499   }
6500 
6501   case Intrinsic::uadd_with_overflow:
6502   case Intrinsic::sadd_with_overflow:
6503   case Intrinsic::usub_with_overflow:
6504   case Intrinsic::ssub_with_overflow:
6505   case Intrinsic::umul_with_overflow:
6506   case Intrinsic::smul_with_overflow: {
6507     ISD::NodeType Op;
6508     switch (Intrinsic) {
6509     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6510     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6511     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6512     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6513     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6514     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6515     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6516     }
6517     SDValue Op1 = getValue(I.getArgOperand(0));
6518     SDValue Op2 = getValue(I.getArgOperand(1));
6519 
6520     EVT ResultVT = Op1.getValueType();
6521     EVT OverflowVT = MVT::i1;
6522     if (ResultVT.isVector())
6523       OverflowVT = EVT::getVectorVT(
6524           *Context, OverflowVT, ResultVT.getVectorNumElements());
6525 
6526     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
6527     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6528     return;
6529   }
6530   case Intrinsic::prefetch: {
6531     SDValue Ops[5];
6532     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6533     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6534     Ops[0] = DAG.getRoot();
6535     Ops[1] = getValue(I.getArgOperand(0));
6536     Ops[2] = getValue(I.getArgOperand(1));
6537     Ops[3] = getValue(I.getArgOperand(2));
6538     Ops[4] = getValue(I.getArgOperand(3));
6539     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6540                                              DAG.getVTList(MVT::Other), Ops,
6541                                              EVT::getIntegerVT(*Context, 8),
6542                                              MachinePointerInfo(I.getArgOperand(0)),
6543                                              0, /* align */
6544                                              Flags);
6545 
6546     // Chain the prefetch in parallell with any pending loads, to stay out of
6547     // the way of later optimizations.
6548     PendingLoads.push_back(Result);
6549     Result = getRoot();
6550     DAG.setRoot(Result);
6551     return;
6552   }
6553   case Intrinsic::lifetime_start:
6554   case Intrinsic::lifetime_end: {
6555     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6556     // Stack coloring is not enabled in O0, discard region information.
6557     if (TM.getOptLevel() == CodeGenOpt::None)
6558       return;
6559 
6560     const int64_t ObjectSize =
6561         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
6562     Value *const ObjectPtr = I.getArgOperand(1);
6563     SmallVector<const Value *, 4> Allocas;
6564     GetUnderlyingObjects(ObjectPtr, Allocas, *DL);
6565 
6566     for (SmallVectorImpl<const Value*>::iterator Object = Allocas.begin(),
6567            E = Allocas.end(); Object != E; ++Object) {
6568       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6569 
6570       // Could not find an Alloca.
6571       if (!LifetimeObject)
6572         continue;
6573 
6574       // First check that the Alloca is static, otherwise it won't have a
6575       // valid frame index.
6576       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6577       if (SI == FuncInfo.StaticAllocaMap.end())
6578         return;
6579 
6580       const int FrameIndex = SI->second;
6581       int64_t Offset;
6582       if (GetPointerBaseWithConstantOffset(
6583               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
6584         Offset = -1; // Cannot determine offset from alloca to lifetime object.
6585       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
6586                                 Offset);
6587       DAG.setRoot(Res);
6588     }
6589     return;
6590   }
6591   case Intrinsic::invariant_start:
6592     // Discard region information.
6593     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6594     return;
6595   case Intrinsic::invariant_end:
6596     // Discard region information.
6597     return;
6598   case Intrinsic::clear_cache:
6599     /// FunctionName may be null.
6600     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
6601       lowerCallToExternalSymbol(I, FunctionName);
6602     return;
6603   case Intrinsic::donothing:
6604     // ignore
6605     return;
6606   case Intrinsic::experimental_stackmap:
6607     visitStackmap(I);
6608     return;
6609   case Intrinsic::experimental_patchpoint_void:
6610   case Intrinsic::experimental_patchpoint_i64:
6611     visitPatchpoint(&I);
6612     return;
6613   case Intrinsic::experimental_gc_statepoint:
6614     LowerStatepoint(ImmutableStatepoint(&I));
6615     return;
6616   case Intrinsic::experimental_gc_result:
6617     visitGCResult(cast<GCResultInst>(I));
6618     return;
6619   case Intrinsic::experimental_gc_relocate:
6620     visitGCRelocate(cast<GCRelocateInst>(I));
6621     return;
6622   case Intrinsic::instrprof_increment:
6623     llvm_unreachable("instrprof failed to lower an increment");
6624   case Intrinsic::instrprof_value_profile:
6625     llvm_unreachable("instrprof failed to lower a value profiling call");
6626   case Intrinsic::localescape: {
6627     MachineFunction &MF = DAG.getMachineFunction();
6628     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6629 
6630     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6631     // is the same on all targets.
6632     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6633       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6634       if (isa<ConstantPointerNull>(Arg))
6635         continue; // Skip null pointers. They represent a hole in index space.
6636       AllocaInst *Slot = cast<AllocaInst>(Arg);
6637       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6638              "can only escape static allocas");
6639       int FI = FuncInfo.StaticAllocaMap[Slot];
6640       MCSymbol *FrameAllocSym =
6641           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6642               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6643       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6644               TII->get(TargetOpcode::LOCAL_ESCAPE))
6645           .addSym(FrameAllocSym)
6646           .addFrameIndex(FI);
6647     }
6648 
6649     return;
6650   }
6651 
6652   case Intrinsic::localrecover: {
6653     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6654     MachineFunction &MF = DAG.getMachineFunction();
6655     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6656 
6657     // Get the symbol that defines the frame offset.
6658     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6659     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6660     unsigned IdxVal =
6661         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6662     MCSymbol *FrameAllocSym =
6663         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6664             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6665 
6666     // Create a MCSymbol for the label to avoid any target lowering
6667     // that would make this PC relative.
6668     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6669     SDValue OffsetVal =
6670         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6671 
6672     // Add the offset to the FP.
6673     Value *FP = I.getArgOperand(1);
6674     SDValue FPVal = getValue(FP);
6675     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6676     setValue(&I, Add);
6677 
6678     return;
6679   }
6680 
6681   case Intrinsic::eh_exceptionpointer:
6682   case Intrinsic::eh_exceptioncode: {
6683     // Get the exception pointer vreg, copy from it, and resize it to fit.
6684     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6685     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6686     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6687     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6688     SDValue N =
6689         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6690     if (Intrinsic == Intrinsic::eh_exceptioncode)
6691       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6692     setValue(&I, N);
6693     return;
6694   }
6695   case Intrinsic::xray_customevent: {
6696     // Here we want to make sure that the intrinsic behaves as if it has a
6697     // specific calling convention, and only for x86_64.
6698     // FIXME: Support other platforms later.
6699     const auto &Triple = DAG.getTarget().getTargetTriple();
6700     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6701       return;
6702 
6703     SDLoc DL = getCurSDLoc();
6704     SmallVector<SDValue, 8> Ops;
6705 
6706     // We want to say that we always want the arguments in registers.
6707     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6708     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6709     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6710     SDValue Chain = getRoot();
6711     Ops.push_back(LogEntryVal);
6712     Ops.push_back(StrSizeVal);
6713     Ops.push_back(Chain);
6714 
6715     // We need to enforce the calling convention for the callsite, so that
6716     // argument ordering is enforced correctly, and that register allocation can
6717     // see that some registers may be assumed clobbered and have to preserve
6718     // them across calls to the intrinsic.
6719     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6720                                            DL, NodeTys, Ops);
6721     SDValue patchableNode = SDValue(MN, 0);
6722     DAG.setRoot(patchableNode);
6723     setValue(&I, patchableNode);
6724     return;
6725   }
6726   case Intrinsic::xray_typedevent: {
6727     // Here we want to make sure that the intrinsic behaves as if it has a
6728     // specific calling convention, and only for x86_64.
6729     // FIXME: Support other platforms later.
6730     const auto &Triple = DAG.getTarget().getTargetTriple();
6731     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6732       return;
6733 
6734     SDLoc DL = getCurSDLoc();
6735     SmallVector<SDValue, 8> Ops;
6736 
6737     // We want to say that we always want the arguments in registers.
6738     // It's unclear to me how manipulating the selection DAG here forces callers
6739     // to provide arguments in registers instead of on the stack.
6740     SDValue LogTypeId = getValue(I.getArgOperand(0));
6741     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6742     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6743     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6744     SDValue Chain = getRoot();
6745     Ops.push_back(LogTypeId);
6746     Ops.push_back(LogEntryVal);
6747     Ops.push_back(StrSizeVal);
6748     Ops.push_back(Chain);
6749 
6750     // We need to enforce the calling convention for the callsite, so that
6751     // argument ordering is enforced correctly, and that register allocation can
6752     // see that some registers may be assumed clobbered and have to preserve
6753     // them across calls to the intrinsic.
6754     MachineSDNode *MN = DAG.getMachineNode(
6755         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6756     SDValue patchableNode = SDValue(MN, 0);
6757     DAG.setRoot(patchableNode);
6758     setValue(&I, patchableNode);
6759     return;
6760   }
6761   case Intrinsic::experimental_deoptimize:
6762     LowerDeoptimizeCall(&I);
6763     return;
6764 
6765   case Intrinsic::experimental_vector_reduce_fadd:
6766   case Intrinsic::experimental_vector_reduce_fmul:
6767   case Intrinsic::experimental_vector_reduce_add:
6768   case Intrinsic::experimental_vector_reduce_mul:
6769   case Intrinsic::experimental_vector_reduce_and:
6770   case Intrinsic::experimental_vector_reduce_or:
6771   case Intrinsic::experimental_vector_reduce_xor:
6772   case Intrinsic::experimental_vector_reduce_smax:
6773   case Intrinsic::experimental_vector_reduce_smin:
6774   case Intrinsic::experimental_vector_reduce_umax:
6775   case Intrinsic::experimental_vector_reduce_umin:
6776   case Intrinsic::experimental_vector_reduce_fmax:
6777   case Intrinsic::experimental_vector_reduce_fmin:
6778     visitVectorReduce(I, Intrinsic);
6779     return;
6780 
6781   case Intrinsic::icall_branch_funnel: {
6782     SmallVector<SDValue, 16> Ops;
6783     Ops.push_back(DAG.getRoot());
6784     Ops.push_back(getValue(I.getArgOperand(0)));
6785 
6786     int64_t Offset;
6787     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6788         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6789     if (!Base)
6790       report_fatal_error(
6791           "llvm.icall.branch.funnel operand must be a GlobalValue");
6792     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6793 
6794     struct BranchFunnelTarget {
6795       int64_t Offset;
6796       SDValue Target;
6797     };
6798     SmallVector<BranchFunnelTarget, 8> Targets;
6799 
6800     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6801       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6802           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6803       if (ElemBase != Base)
6804         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6805                            "to the same GlobalValue");
6806 
6807       SDValue Val = getValue(I.getArgOperand(Op + 1));
6808       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6809       if (!GA)
6810         report_fatal_error(
6811             "llvm.icall.branch.funnel operand must be a GlobalValue");
6812       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6813                                      GA->getGlobal(), getCurSDLoc(),
6814                                      Val.getValueType(), GA->getOffset())});
6815     }
6816     llvm::sort(Targets,
6817                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6818                  return T1.Offset < T2.Offset;
6819                });
6820 
6821     for (auto &T : Targets) {
6822       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6823       Ops.push_back(T.Target);
6824     }
6825 
6826     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6827                                  getCurSDLoc(), MVT::Other, Ops),
6828               0);
6829     DAG.setRoot(N);
6830     setValue(&I, N);
6831     HasTailCall = true;
6832     return;
6833   }
6834 
6835   case Intrinsic::wasm_landingpad_index:
6836     // Information this intrinsic contained has been transferred to
6837     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6838     // delete it now.
6839     return;
6840   }
6841 }
6842 
6843 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6844     const ConstrainedFPIntrinsic &FPI) {
6845   SDLoc sdl = getCurSDLoc();
6846   unsigned Opcode;
6847   switch (FPI.getIntrinsicID()) {
6848   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6849   case Intrinsic::experimental_constrained_fadd:
6850     Opcode = ISD::STRICT_FADD;
6851     break;
6852   case Intrinsic::experimental_constrained_fsub:
6853     Opcode = ISD::STRICT_FSUB;
6854     break;
6855   case Intrinsic::experimental_constrained_fmul:
6856     Opcode = ISD::STRICT_FMUL;
6857     break;
6858   case Intrinsic::experimental_constrained_fdiv:
6859     Opcode = ISD::STRICT_FDIV;
6860     break;
6861   case Intrinsic::experimental_constrained_frem:
6862     Opcode = ISD::STRICT_FREM;
6863     break;
6864   case Intrinsic::experimental_constrained_fma:
6865     Opcode = ISD::STRICT_FMA;
6866     break;
6867   case Intrinsic::experimental_constrained_fptrunc:
6868     Opcode = ISD::STRICT_FP_ROUND;
6869     break;
6870   case Intrinsic::experimental_constrained_fpext:
6871     Opcode = ISD::STRICT_FP_EXTEND;
6872     break;
6873   case Intrinsic::experimental_constrained_sqrt:
6874     Opcode = ISD::STRICT_FSQRT;
6875     break;
6876   case Intrinsic::experimental_constrained_pow:
6877     Opcode = ISD::STRICT_FPOW;
6878     break;
6879   case Intrinsic::experimental_constrained_powi:
6880     Opcode = ISD::STRICT_FPOWI;
6881     break;
6882   case Intrinsic::experimental_constrained_sin:
6883     Opcode = ISD::STRICT_FSIN;
6884     break;
6885   case Intrinsic::experimental_constrained_cos:
6886     Opcode = ISD::STRICT_FCOS;
6887     break;
6888   case Intrinsic::experimental_constrained_exp:
6889     Opcode = ISD::STRICT_FEXP;
6890     break;
6891   case Intrinsic::experimental_constrained_exp2:
6892     Opcode = ISD::STRICT_FEXP2;
6893     break;
6894   case Intrinsic::experimental_constrained_log:
6895     Opcode = ISD::STRICT_FLOG;
6896     break;
6897   case Intrinsic::experimental_constrained_log10:
6898     Opcode = ISD::STRICT_FLOG10;
6899     break;
6900   case Intrinsic::experimental_constrained_log2:
6901     Opcode = ISD::STRICT_FLOG2;
6902     break;
6903   case Intrinsic::experimental_constrained_rint:
6904     Opcode = ISD::STRICT_FRINT;
6905     break;
6906   case Intrinsic::experimental_constrained_nearbyint:
6907     Opcode = ISD::STRICT_FNEARBYINT;
6908     break;
6909   case Intrinsic::experimental_constrained_maxnum:
6910     Opcode = ISD::STRICT_FMAXNUM;
6911     break;
6912   case Intrinsic::experimental_constrained_minnum:
6913     Opcode = ISD::STRICT_FMINNUM;
6914     break;
6915   case Intrinsic::experimental_constrained_ceil:
6916     Opcode = ISD::STRICT_FCEIL;
6917     break;
6918   case Intrinsic::experimental_constrained_floor:
6919     Opcode = ISD::STRICT_FFLOOR;
6920     break;
6921   case Intrinsic::experimental_constrained_round:
6922     Opcode = ISD::STRICT_FROUND;
6923     break;
6924   case Intrinsic::experimental_constrained_trunc:
6925     Opcode = ISD::STRICT_FTRUNC;
6926     break;
6927   }
6928   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6929   SDValue Chain = getRoot();
6930   SmallVector<EVT, 4> ValueVTs;
6931   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6932   ValueVTs.push_back(MVT::Other); // Out chain
6933 
6934   SDVTList VTs = DAG.getVTList(ValueVTs);
6935   SDValue Result;
6936   if (Opcode == ISD::STRICT_FP_ROUND)
6937     Result = DAG.getNode(Opcode, sdl, VTs,
6938                           { Chain, getValue(FPI.getArgOperand(0)),
6939                                DAG.getTargetConstant(0, sdl,
6940                                TLI.getPointerTy(DAG.getDataLayout())) });
6941   else if (FPI.isUnaryOp())
6942     Result = DAG.getNode(Opcode, sdl, VTs,
6943                          { Chain, getValue(FPI.getArgOperand(0)) });
6944   else if (FPI.isTernaryOp())
6945     Result = DAG.getNode(Opcode, sdl, VTs,
6946                          { Chain, getValue(FPI.getArgOperand(0)),
6947                                   getValue(FPI.getArgOperand(1)),
6948                                   getValue(FPI.getArgOperand(2)) });
6949   else
6950     Result = DAG.getNode(Opcode, sdl, VTs,
6951                          { Chain, getValue(FPI.getArgOperand(0)),
6952                            getValue(FPI.getArgOperand(1))  });
6953 
6954   assert(Result.getNode()->getNumValues() == 2);
6955   SDValue OutChain = Result.getValue(1);
6956   DAG.setRoot(OutChain);
6957   SDValue FPResult = Result.getValue(0);
6958   setValue(&FPI, FPResult);
6959 }
6960 
6961 std::pair<SDValue, SDValue>
6962 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6963                                     const BasicBlock *EHPadBB) {
6964   MachineFunction &MF = DAG.getMachineFunction();
6965   MachineModuleInfo &MMI = MF.getMMI();
6966   MCSymbol *BeginLabel = nullptr;
6967 
6968   if (EHPadBB) {
6969     // Insert a label before the invoke call to mark the try range.  This can be
6970     // used to detect deletion of the invoke via the MachineModuleInfo.
6971     BeginLabel = MMI.getContext().createTempSymbol();
6972 
6973     // For SjLj, keep track of which landing pads go with which invokes
6974     // so as to maintain the ordering of pads in the LSDA.
6975     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6976     if (CallSiteIndex) {
6977       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6978       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6979 
6980       // Now that the call site is handled, stop tracking it.
6981       MMI.setCurrentCallSite(0);
6982     }
6983 
6984     // Both PendingLoads and PendingExports must be flushed here;
6985     // this call might not return.
6986     (void)getRoot();
6987     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6988 
6989     CLI.setChain(getRoot());
6990   }
6991   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6992   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6993 
6994   assert((CLI.IsTailCall || Result.second.getNode()) &&
6995          "Non-null chain expected with non-tail call!");
6996   assert((Result.second.getNode() || !Result.first.getNode()) &&
6997          "Null value expected with tail call!");
6998 
6999   if (!Result.second.getNode()) {
7000     // As a special case, a null chain means that a tail call has been emitted
7001     // and the DAG root is already updated.
7002     HasTailCall = true;
7003 
7004     // Since there's no actual continuation from this block, nothing can be
7005     // relying on us setting vregs for them.
7006     PendingExports.clear();
7007   } else {
7008     DAG.setRoot(Result.second);
7009   }
7010 
7011   if (EHPadBB) {
7012     // Insert a label at the end of the invoke call to mark the try range.  This
7013     // can be used to detect deletion of the invoke via the MachineModuleInfo.
7014     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
7015     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
7016 
7017     // Inform MachineModuleInfo of range.
7018     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
7019     // There is a platform (e.g. wasm) that uses funclet style IR but does not
7020     // actually use outlined funclets and their LSDA info style.
7021     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
7022       assert(CLI.CS);
7023       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
7024       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
7025                                 BeginLabel, EndLabel);
7026     } else if (!isScopedEHPersonality(Pers)) {
7027       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
7028     }
7029   }
7030 
7031   return Result;
7032 }
7033 
7034 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
7035                                       bool isTailCall,
7036                                       const BasicBlock *EHPadBB) {
7037   auto &DL = DAG.getDataLayout();
7038   FunctionType *FTy = CS.getFunctionType();
7039   Type *RetTy = CS.getType();
7040 
7041   TargetLowering::ArgListTy Args;
7042   Args.reserve(CS.arg_size());
7043 
7044   const Value *SwiftErrorVal = nullptr;
7045   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7046 
7047   // We can't tail call inside a function with a swifterror argument. Lowering
7048   // does not support this yet. It would have to move into the swifterror
7049   // register before the call.
7050   auto *Caller = CS.getInstruction()->getParent()->getParent();
7051   if (TLI.supportSwiftError() &&
7052       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
7053     isTailCall = false;
7054 
7055   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
7056        i != e; ++i) {
7057     TargetLowering::ArgListEntry Entry;
7058     const Value *V = *i;
7059 
7060     // Skip empty types
7061     if (V->getType()->isEmptyTy())
7062       continue;
7063 
7064     SDValue ArgNode = getValue(V);
7065     Entry.Node = ArgNode; Entry.Ty = V->getType();
7066 
7067     Entry.setAttributes(&CS, i - CS.arg_begin());
7068 
7069     // Use swifterror virtual register as input to the call.
7070     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
7071       SwiftErrorVal = V;
7072       // We find the virtual register for the actual swifterror argument.
7073       // Instead of using the Value, we use the virtual register instead.
7074       Entry.Node = DAG.getRegister(
7075           SwiftError.getOrCreateVRegUseAt(CS.getInstruction(), FuncInfo.MBB, V),
7076           EVT(TLI.getPointerTy(DL)));
7077     }
7078 
7079     Args.push_back(Entry);
7080 
7081     // If we have an explicit sret argument that is an Instruction, (i.e., it
7082     // might point to function-local memory), we can't meaningfully tail-call.
7083     if (Entry.IsSRet && isa<Instruction>(V))
7084       isTailCall = false;
7085   }
7086 
7087   // Check if target-independent constraints permit a tail call here.
7088   // Target-dependent constraints are checked within TLI->LowerCallTo.
7089   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
7090     isTailCall = false;
7091 
7092   // Disable tail calls if there is an swifterror argument. Targets have not
7093   // been updated to support tail calls.
7094   if (TLI.supportSwiftError() && SwiftErrorVal)
7095     isTailCall = false;
7096 
7097   TargetLowering::CallLoweringInfo CLI(DAG);
7098   CLI.setDebugLoc(getCurSDLoc())
7099       .setChain(getRoot())
7100       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
7101       .setTailCall(isTailCall)
7102       .setConvergent(CS.isConvergent());
7103   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
7104 
7105   if (Result.first.getNode()) {
7106     const Instruction *Inst = CS.getInstruction();
7107     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
7108     setValue(Inst, Result.first);
7109   }
7110 
7111   // The last element of CLI.InVals has the SDValue for swifterror return.
7112   // Here we copy it to a virtual register and update SwiftErrorMap for
7113   // book-keeping.
7114   if (SwiftErrorVal && TLI.supportSwiftError()) {
7115     // Get the last element of InVals.
7116     SDValue Src = CLI.InVals.back();
7117     unsigned VReg = SwiftError.getOrCreateVRegDefAt(
7118         CS.getInstruction(), FuncInfo.MBB, SwiftErrorVal);
7119     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
7120     DAG.setRoot(CopyNode);
7121   }
7122 }
7123 
7124 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
7125                              SelectionDAGBuilder &Builder) {
7126   // Check to see if this load can be trivially constant folded, e.g. if the
7127   // input is from a string literal.
7128   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
7129     // Cast pointer to the type we really want to load.
7130     Type *LoadTy =
7131         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
7132     if (LoadVT.isVector())
7133       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
7134 
7135     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
7136                                          PointerType::getUnqual(LoadTy));
7137 
7138     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
7139             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
7140       return Builder.getValue(LoadCst);
7141   }
7142 
7143   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
7144   // still constant memory, the input chain can be the entry node.
7145   SDValue Root;
7146   bool ConstantMemory = false;
7147 
7148   // Do not serialize (non-volatile) loads of constant memory with anything.
7149   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
7150     Root = Builder.DAG.getEntryNode();
7151     ConstantMemory = true;
7152   } else {
7153     // Do not serialize non-volatile loads against each other.
7154     Root = Builder.DAG.getRoot();
7155   }
7156 
7157   SDValue Ptr = Builder.getValue(PtrVal);
7158   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
7159                                         Ptr, MachinePointerInfo(PtrVal),
7160                                         /* Alignment = */ 1);
7161 
7162   if (!ConstantMemory)
7163     Builder.PendingLoads.push_back(LoadVal.getValue(1));
7164   return LoadVal;
7165 }
7166 
7167 /// Record the value for an instruction that produces an integer result,
7168 /// converting the type where necessary.
7169 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
7170                                                   SDValue Value,
7171                                                   bool IsSigned) {
7172   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7173                                                     I.getType(), true);
7174   if (IsSigned)
7175     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
7176   else
7177     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
7178   setValue(&I, Value);
7179 }
7180 
7181 /// See if we can lower a memcmp call into an optimized form. If so, return
7182 /// true and lower it. Otherwise return false, and it will be lowered like a
7183 /// normal call.
7184 /// The caller already checked that \p I calls the appropriate LibFunc with a
7185 /// correct prototype.
7186 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
7187   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
7188   const Value *Size = I.getArgOperand(2);
7189   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
7190   if (CSize && CSize->getZExtValue() == 0) {
7191     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
7192                                                           I.getType(), true);
7193     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
7194     return true;
7195   }
7196 
7197   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7198   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
7199       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
7200       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
7201   if (Res.first.getNode()) {
7202     processIntegerCallValue(I, Res.first, true);
7203     PendingLoads.push_back(Res.second);
7204     return true;
7205   }
7206 
7207   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
7208   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
7209   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
7210     return false;
7211 
7212   // If the target has a fast compare for the given size, it will return a
7213   // preferred load type for that size. Require that the load VT is legal and
7214   // that the target supports unaligned loads of that type. Otherwise, return
7215   // INVALID.
7216   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
7217     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7218     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
7219     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
7220       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
7221       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
7222       // TODO: Check alignment of src and dest ptrs.
7223       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
7224       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
7225       if (!TLI.isTypeLegal(LVT) ||
7226           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
7227           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
7228         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
7229     }
7230 
7231     return LVT;
7232   };
7233 
7234   // This turns into unaligned loads. We only do this if the target natively
7235   // supports the MVT we'll be loading or if it is small enough (<= 4) that
7236   // we'll only produce a small number of byte loads.
7237   MVT LoadVT;
7238   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
7239   switch (NumBitsToCompare) {
7240   default:
7241     return false;
7242   case 16:
7243     LoadVT = MVT::i16;
7244     break;
7245   case 32:
7246     LoadVT = MVT::i32;
7247     break;
7248   case 64:
7249   case 128:
7250   case 256:
7251     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
7252     break;
7253   }
7254 
7255   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
7256     return false;
7257 
7258   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
7259   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
7260 
7261   // Bitcast to a wide integer type if the loads are vectors.
7262   if (LoadVT.isVector()) {
7263     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
7264     LoadL = DAG.getBitcast(CmpVT, LoadL);
7265     LoadR = DAG.getBitcast(CmpVT, LoadR);
7266   }
7267 
7268   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
7269   processIntegerCallValue(I, Cmp, false);
7270   return true;
7271 }
7272 
7273 /// See if we can lower a memchr call into an optimized form. If so, return
7274 /// true and lower it. Otherwise return false, and it will be lowered like a
7275 /// normal call.
7276 /// The caller already checked that \p I calls the appropriate LibFunc with a
7277 /// correct prototype.
7278 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
7279   const Value *Src = I.getArgOperand(0);
7280   const Value *Char = I.getArgOperand(1);
7281   const Value *Length = I.getArgOperand(2);
7282 
7283   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7284   std::pair<SDValue, SDValue> Res =
7285     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
7286                                 getValue(Src), getValue(Char), getValue(Length),
7287                                 MachinePointerInfo(Src));
7288   if (Res.first.getNode()) {
7289     setValue(&I, Res.first);
7290     PendingLoads.push_back(Res.second);
7291     return true;
7292   }
7293 
7294   return false;
7295 }
7296 
7297 /// See if we can lower a mempcpy call into an optimized form. If so, return
7298 /// true and lower it. Otherwise return false, and it will be lowered like a
7299 /// normal call.
7300 /// The caller already checked that \p I calls the appropriate LibFunc with a
7301 /// correct prototype.
7302 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
7303   SDValue Dst = getValue(I.getArgOperand(0));
7304   SDValue Src = getValue(I.getArgOperand(1));
7305   SDValue Size = getValue(I.getArgOperand(2));
7306 
7307   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
7308   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
7309   unsigned Align = std::min(DstAlign, SrcAlign);
7310   if (Align == 0) // Alignment of one or both could not be inferred.
7311     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
7312 
7313   bool isVol = false;
7314   SDLoc sdl = getCurSDLoc();
7315 
7316   // In the mempcpy context we need to pass in a false value for isTailCall
7317   // because the return pointer needs to be adjusted by the size of
7318   // the copied memory.
7319   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
7320                              false, /*isTailCall=*/false,
7321                              MachinePointerInfo(I.getArgOperand(0)),
7322                              MachinePointerInfo(I.getArgOperand(1)));
7323   assert(MC.getNode() != nullptr &&
7324          "** memcpy should not be lowered as TailCall in mempcpy context **");
7325   DAG.setRoot(MC);
7326 
7327   // Check if Size needs to be truncated or extended.
7328   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
7329 
7330   // Adjust return pointer to point just past the last dst byte.
7331   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
7332                                     Dst, Size);
7333   setValue(&I, DstPlusSize);
7334   return true;
7335 }
7336 
7337 /// See if we can lower a strcpy call into an optimized form.  If so, return
7338 /// true and lower it, otherwise return false and it will be lowered like a
7339 /// normal call.
7340 /// The caller already checked that \p I calls the appropriate LibFunc with a
7341 /// correct prototype.
7342 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
7343   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7344 
7345   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7346   std::pair<SDValue, SDValue> Res =
7347     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
7348                                 getValue(Arg0), getValue(Arg1),
7349                                 MachinePointerInfo(Arg0),
7350                                 MachinePointerInfo(Arg1), isStpcpy);
7351   if (Res.first.getNode()) {
7352     setValue(&I, Res.first);
7353     DAG.setRoot(Res.second);
7354     return true;
7355   }
7356 
7357   return false;
7358 }
7359 
7360 /// See if we can lower a strcmp call into an optimized form.  If so, return
7361 /// true and lower it, otherwise return false and it will be lowered like a
7362 /// normal call.
7363 /// The caller already checked that \p I calls the appropriate LibFunc with a
7364 /// correct prototype.
7365 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
7366   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7367 
7368   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7369   std::pair<SDValue, SDValue> Res =
7370     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
7371                                 getValue(Arg0), getValue(Arg1),
7372                                 MachinePointerInfo(Arg0),
7373                                 MachinePointerInfo(Arg1));
7374   if (Res.first.getNode()) {
7375     processIntegerCallValue(I, Res.first, true);
7376     PendingLoads.push_back(Res.second);
7377     return true;
7378   }
7379 
7380   return false;
7381 }
7382 
7383 /// See if we can lower a strlen call into an optimized form.  If so, return
7384 /// true and lower it, otherwise return false and it will be lowered like a
7385 /// normal call.
7386 /// The caller already checked that \p I calls the appropriate LibFunc with a
7387 /// correct prototype.
7388 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
7389   const Value *Arg0 = I.getArgOperand(0);
7390 
7391   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7392   std::pair<SDValue, SDValue> Res =
7393     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
7394                                 getValue(Arg0), MachinePointerInfo(Arg0));
7395   if (Res.first.getNode()) {
7396     processIntegerCallValue(I, Res.first, false);
7397     PendingLoads.push_back(Res.second);
7398     return true;
7399   }
7400 
7401   return false;
7402 }
7403 
7404 /// See if we can lower a strnlen call into an optimized form.  If so, return
7405 /// true and lower it, otherwise return false and it will be lowered like a
7406 /// normal call.
7407 /// The caller already checked that \p I calls the appropriate LibFunc with a
7408 /// correct prototype.
7409 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
7410   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
7411 
7412   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7413   std::pair<SDValue, SDValue> Res =
7414     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
7415                                  getValue(Arg0), getValue(Arg1),
7416                                  MachinePointerInfo(Arg0));
7417   if (Res.first.getNode()) {
7418     processIntegerCallValue(I, Res.first, false);
7419     PendingLoads.push_back(Res.second);
7420     return true;
7421   }
7422 
7423   return false;
7424 }
7425 
7426 /// See if we can lower a unary floating-point operation into an SDNode with
7427 /// the specified Opcode.  If so, return true and lower it, otherwise return
7428 /// false and it will be lowered like a normal call.
7429 /// The caller already checked that \p I calls the appropriate LibFunc with a
7430 /// correct prototype.
7431 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
7432                                               unsigned Opcode) {
7433   // We already checked this call's prototype; verify it doesn't modify errno.
7434   if (!I.onlyReadsMemory())
7435     return false;
7436 
7437   SDValue Tmp = getValue(I.getArgOperand(0));
7438   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
7439   return true;
7440 }
7441 
7442 /// See if we can lower a binary floating-point operation into an SDNode with
7443 /// the specified Opcode. If so, return true and lower it. Otherwise return
7444 /// false, and it will be lowered like a normal call.
7445 /// The caller already checked that \p I calls the appropriate LibFunc with a
7446 /// correct prototype.
7447 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
7448                                                unsigned Opcode) {
7449   // We already checked this call's prototype; verify it doesn't modify errno.
7450   if (!I.onlyReadsMemory())
7451     return false;
7452 
7453   SDValue Tmp0 = getValue(I.getArgOperand(0));
7454   SDValue Tmp1 = getValue(I.getArgOperand(1));
7455   EVT VT = Tmp0.getValueType();
7456   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
7457   return true;
7458 }
7459 
7460 void SelectionDAGBuilder::visitCall(const CallInst &I) {
7461   // Handle inline assembly differently.
7462   if (isa<InlineAsm>(I.getCalledValue())) {
7463     visitInlineAsm(&I);
7464     return;
7465   }
7466 
7467   if (Function *F = I.getCalledFunction()) {
7468     if (F->isDeclaration()) {
7469       // Is this an LLVM intrinsic or a target-specific intrinsic?
7470       unsigned IID = F->getIntrinsicID();
7471       if (!IID)
7472         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
7473           IID = II->getIntrinsicID(F);
7474 
7475       if (IID) {
7476         visitIntrinsicCall(I, IID);
7477         return;
7478       }
7479     }
7480 
7481     // Check for well-known libc/libm calls.  If the function is internal, it
7482     // can't be a library call.  Don't do the check if marked as nobuiltin for
7483     // some reason or the call site requires strict floating point semantics.
7484     LibFunc Func;
7485     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7486         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7487         LibInfo->hasOptimizedCodeGen(Func)) {
7488       switch (Func) {
7489       default: break;
7490       case LibFunc_copysign:
7491       case LibFunc_copysignf:
7492       case LibFunc_copysignl:
7493         // We already checked this call's prototype; verify it doesn't modify
7494         // errno.
7495         if (I.onlyReadsMemory()) {
7496           SDValue LHS = getValue(I.getArgOperand(0));
7497           SDValue RHS = getValue(I.getArgOperand(1));
7498           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7499                                    LHS.getValueType(), LHS, RHS));
7500           return;
7501         }
7502         break;
7503       case LibFunc_fabs:
7504       case LibFunc_fabsf:
7505       case LibFunc_fabsl:
7506         if (visitUnaryFloatCall(I, ISD::FABS))
7507           return;
7508         break;
7509       case LibFunc_fmin:
7510       case LibFunc_fminf:
7511       case LibFunc_fminl:
7512         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7513           return;
7514         break;
7515       case LibFunc_fmax:
7516       case LibFunc_fmaxf:
7517       case LibFunc_fmaxl:
7518         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7519           return;
7520         break;
7521       case LibFunc_sin:
7522       case LibFunc_sinf:
7523       case LibFunc_sinl:
7524         if (visitUnaryFloatCall(I, ISD::FSIN))
7525           return;
7526         break;
7527       case LibFunc_cos:
7528       case LibFunc_cosf:
7529       case LibFunc_cosl:
7530         if (visitUnaryFloatCall(I, ISD::FCOS))
7531           return;
7532         break;
7533       case LibFunc_sqrt:
7534       case LibFunc_sqrtf:
7535       case LibFunc_sqrtl:
7536       case LibFunc_sqrt_finite:
7537       case LibFunc_sqrtf_finite:
7538       case LibFunc_sqrtl_finite:
7539         if (visitUnaryFloatCall(I, ISD::FSQRT))
7540           return;
7541         break;
7542       case LibFunc_floor:
7543       case LibFunc_floorf:
7544       case LibFunc_floorl:
7545         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7546           return;
7547         break;
7548       case LibFunc_nearbyint:
7549       case LibFunc_nearbyintf:
7550       case LibFunc_nearbyintl:
7551         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7552           return;
7553         break;
7554       case LibFunc_ceil:
7555       case LibFunc_ceilf:
7556       case LibFunc_ceill:
7557         if (visitUnaryFloatCall(I, ISD::FCEIL))
7558           return;
7559         break;
7560       case LibFunc_rint:
7561       case LibFunc_rintf:
7562       case LibFunc_rintl:
7563         if (visitUnaryFloatCall(I, ISD::FRINT))
7564           return;
7565         break;
7566       case LibFunc_round:
7567       case LibFunc_roundf:
7568       case LibFunc_roundl:
7569         if (visitUnaryFloatCall(I, ISD::FROUND))
7570           return;
7571         break;
7572       case LibFunc_trunc:
7573       case LibFunc_truncf:
7574       case LibFunc_truncl:
7575         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7576           return;
7577         break;
7578       case LibFunc_log2:
7579       case LibFunc_log2f:
7580       case LibFunc_log2l:
7581         if (visitUnaryFloatCall(I, ISD::FLOG2))
7582           return;
7583         break;
7584       case LibFunc_exp2:
7585       case LibFunc_exp2f:
7586       case LibFunc_exp2l:
7587         if (visitUnaryFloatCall(I, ISD::FEXP2))
7588           return;
7589         break;
7590       case LibFunc_memcmp:
7591         if (visitMemCmpCall(I))
7592           return;
7593         break;
7594       case LibFunc_mempcpy:
7595         if (visitMemPCpyCall(I))
7596           return;
7597         break;
7598       case LibFunc_memchr:
7599         if (visitMemChrCall(I))
7600           return;
7601         break;
7602       case LibFunc_strcpy:
7603         if (visitStrCpyCall(I, false))
7604           return;
7605         break;
7606       case LibFunc_stpcpy:
7607         if (visitStrCpyCall(I, true))
7608           return;
7609         break;
7610       case LibFunc_strcmp:
7611         if (visitStrCmpCall(I))
7612           return;
7613         break;
7614       case LibFunc_strlen:
7615         if (visitStrLenCall(I))
7616           return;
7617         break;
7618       case LibFunc_strnlen:
7619         if (visitStrNLenCall(I))
7620           return;
7621         break;
7622       }
7623     }
7624   }
7625 
7626   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7627   // have to do anything here to lower funclet bundles.
7628   assert(!I.hasOperandBundlesOtherThan(
7629              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7630          "Cannot lower calls with arbitrary operand bundles!");
7631 
7632   SDValue Callee = getValue(I.getCalledValue());
7633 
7634   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7635     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7636   else
7637     // Check if we can potentially perform a tail call. More detailed checking
7638     // is be done within LowerCallTo, after more information about the call is
7639     // known.
7640     LowerCallTo(&I, Callee, I.isTailCall());
7641 }
7642 
7643 namespace {
7644 
7645 /// AsmOperandInfo - This contains information for each constraint that we are
7646 /// lowering.
7647 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7648 public:
7649   /// CallOperand - If this is the result output operand or a clobber
7650   /// this is null, otherwise it is the incoming operand to the CallInst.
7651   /// This gets modified as the asm is processed.
7652   SDValue CallOperand;
7653 
7654   /// AssignedRegs - If this is a register or register class operand, this
7655   /// contains the set of register corresponding to the operand.
7656   RegsForValue AssignedRegs;
7657 
7658   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7659     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7660   }
7661 
7662   /// Whether or not this operand accesses memory
7663   bool hasMemory(const TargetLowering &TLI) const {
7664     // Indirect operand accesses access memory.
7665     if (isIndirect)
7666       return true;
7667 
7668     for (const auto &Code : Codes)
7669       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7670         return true;
7671 
7672     return false;
7673   }
7674 
7675   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7676   /// corresponds to.  If there is no Value* for this operand, it returns
7677   /// MVT::Other.
7678   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7679                            const DataLayout &DL) const {
7680     if (!CallOperandVal) return MVT::Other;
7681 
7682     if (isa<BasicBlock>(CallOperandVal))
7683       return TLI.getPointerTy(DL);
7684 
7685     llvm::Type *OpTy = CallOperandVal->getType();
7686 
7687     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7688     // If this is an indirect operand, the operand is a pointer to the
7689     // accessed type.
7690     if (isIndirect) {
7691       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7692       if (!PtrTy)
7693         report_fatal_error("Indirect operand for inline asm not a pointer!");
7694       OpTy = PtrTy->getElementType();
7695     }
7696 
7697     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7698     if (StructType *STy = dyn_cast<StructType>(OpTy))
7699       if (STy->getNumElements() == 1)
7700         OpTy = STy->getElementType(0);
7701 
7702     // If OpTy is not a single value, it may be a struct/union that we
7703     // can tile with integers.
7704     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7705       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7706       switch (BitSize) {
7707       default: break;
7708       case 1:
7709       case 8:
7710       case 16:
7711       case 32:
7712       case 64:
7713       case 128:
7714         OpTy = IntegerType::get(Context, BitSize);
7715         break;
7716       }
7717     }
7718 
7719     return TLI.getValueType(DL, OpTy, true);
7720   }
7721 };
7722 
7723 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7724 
7725 } // end anonymous namespace
7726 
7727 /// Make sure that the output operand \p OpInfo and its corresponding input
7728 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7729 /// out).
7730 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7731                                SDISelAsmOperandInfo &MatchingOpInfo,
7732                                SelectionDAG &DAG) {
7733   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7734     return;
7735 
7736   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7737   const auto &TLI = DAG.getTargetLoweringInfo();
7738 
7739   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7740       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7741                                        OpInfo.ConstraintVT);
7742   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7743       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7744                                        MatchingOpInfo.ConstraintVT);
7745   if ((OpInfo.ConstraintVT.isInteger() !=
7746        MatchingOpInfo.ConstraintVT.isInteger()) ||
7747       (MatchRC.second != InputRC.second)) {
7748     // FIXME: error out in a more elegant fashion
7749     report_fatal_error("Unsupported asm: input constraint"
7750                        " with a matching output constraint of"
7751                        " incompatible type!");
7752   }
7753   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7754 }
7755 
7756 /// Get a direct memory input to behave well as an indirect operand.
7757 /// This may introduce stores, hence the need for a \p Chain.
7758 /// \return The (possibly updated) chain.
7759 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7760                                         SDISelAsmOperandInfo &OpInfo,
7761                                         SelectionDAG &DAG) {
7762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7763 
7764   // If we don't have an indirect input, put it in the constpool if we can,
7765   // otherwise spill it to a stack slot.
7766   // TODO: This isn't quite right. We need to handle these according to
7767   // the addressing mode that the constraint wants. Also, this may take
7768   // an additional register for the computation and we don't want that
7769   // either.
7770 
7771   // If the operand is a float, integer, or vector constant, spill to a
7772   // constant pool entry to get its address.
7773   const Value *OpVal = OpInfo.CallOperandVal;
7774   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7775       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7776     OpInfo.CallOperand = DAG.getConstantPool(
7777         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7778     return Chain;
7779   }
7780 
7781   // Otherwise, create a stack slot and emit a store to it before the asm.
7782   Type *Ty = OpVal->getType();
7783   auto &DL = DAG.getDataLayout();
7784   uint64_t TySize = DL.getTypeAllocSize(Ty);
7785   unsigned Align = DL.getPrefTypeAlignment(Ty);
7786   MachineFunction &MF = DAG.getMachineFunction();
7787   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7788   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7789   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7790                             MachinePointerInfo::getFixedStack(MF, SSFI),
7791                             TLI.getMemValueType(DL, Ty));
7792   OpInfo.CallOperand = StackSlot;
7793 
7794   return Chain;
7795 }
7796 
7797 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7798 /// specified operand.  We prefer to assign virtual registers, to allow the
7799 /// register allocator to handle the assignment process.  However, if the asm
7800 /// uses features that we can't model on machineinstrs, we have SDISel do the
7801 /// allocation.  This produces generally horrible, but correct, code.
7802 ///
7803 ///   OpInfo describes the operand
7804 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7805 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7806                                  SDISelAsmOperandInfo &OpInfo,
7807                                  SDISelAsmOperandInfo &RefOpInfo) {
7808   LLVMContext &Context = *DAG.getContext();
7809   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7810 
7811   MachineFunction &MF = DAG.getMachineFunction();
7812   SmallVector<unsigned, 4> Regs;
7813   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7814 
7815   // No work to do for memory operations.
7816   if (OpInfo.ConstraintType == TargetLowering::C_Memory)
7817     return;
7818 
7819   // If this is a constraint for a single physreg, or a constraint for a
7820   // register class, find it.
7821   unsigned AssignedReg;
7822   const TargetRegisterClass *RC;
7823   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7824       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7825   // RC is unset only on failure. Return immediately.
7826   if (!RC)
7827     return;
7828 
7829   // Get the actual register value type.  This is important, because the user
7830   // may have asked for (e.g.) the AX register in i32 type.  We need to
7831   // remember that AX is actually i16 to get the right extension.
7832   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7833 
7834   if (OpInfo.ConstraintVT != MVT::Other) {
7835     // If this is an FP operand in an integer register (or visa versa), or more
7836     // generally if the operand value disagrees with the register class we plan
7837     // to stick it in, fix the operand type.
7838     //
7839     // If this is an input value, the bitcast to the new type is done now.
7840     // Bitcast for output value is done at the end of visitInlineAsm().
7841     if ((OpInfo.Type == InlineAsm::isOutput ||
7842          OpInfo.Type == InlineAsm::isInput) &&
7843         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7844       // Try to convert to the first EVT that the reg class contains.  If the
7845       // types are identical size, use a bitcast to convert (e.g. two differing
7846       // vector types).  Note: output bitcast is done at the end of
7847       // visitInlineAsm().
7848       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7849         // Exclude indirect inputs while they are unsupported because the code
7850         // to perform the load is missing and thus OpInfo.CallOperand still
7851         // refers to the input address rather than the pointed-to value.
7852         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7853           OpInfo.CallOperand =
7854               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7855         OpInfo.ConstraintVT = RegVT;
7856         // If the operand is an FP value and we want it in integer registers,
7857         // use the corresponding integer type. This turns an f64 value into
7858         // i64, which can be passed with two i32 values on a 32-bit machine.
7859       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7860         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7861         if (OpInfo.Type == InlineAsm::isInput)
7862           OpInfo.CallOperand =
7863               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7864         OpInfo.ConstraintVT = VT;
7865       }
7866     }
7867   }
7868 
7869   // No need to allocate a matching input constraint since the constraint it's
7870   // matching to has already been allocated.
7871   if (OpInfo.isMatchingInputConstraint())
7872     return;
7873 
7874   EVT ValueVT = OpInfo.ConstraintVT;
7875   if (OpInfo.ConstraintVT == MVT::Other)
7876     ValueVT = RegVT;
7877 
7878   // Initialize NumRegs.
7879   unsigned NumRegs = 1;
7880   if (OpInfo.ConstraintVT != MVT::Other)
7881     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7882 
7883   // If this is a constraint for a specific physical register, like {r17},
7884   // assign it now.
7885 
7886   // If this associated to a specific register, initialize iterator to correct
7887   // place. If virtual, make sure we have enough registers
7888 
7889   // Initialize iterator if necessary
7890   TargetRegisterClass::iterator I = RC->begin();
7891   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7892 
7893   // Do not check for single registers.
7894   if (AssignedReg) {
7895       for (; *I != AssignedReg; ++I)
7896         assert(I != RC->end() && "AssignedReg should be member of RC");
7897   }
7898 
7899   for (; NumRegs; --NumRegs, ++I) {
7900     assert(I != RC->end() && "Ran out of registers to allocate!");
7901     auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
7902     Regs.push_back(R);
7903   }
7904 
7905   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7906 }
7907 
7908 static unsigned
7909 findMatchingInlineAsmOperand(unsigned OperandNo,
7910                              const std::vector<SDValue> &AsmNodeOperands) {
7911   // Scan until we find the definition we already emitted of this operand.
7912   unsigned CurOp = InlineAsm::Op_FirstOperand;
7913   for (; OperandNo; --OperandNo) {
7914     // Advance to the next operand.
7915     unsigned OpFlag =
7916         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7917     assert((InlineAsm::isRegDefKind(OpFlag) ||
7918             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7919             InlineAsm::isMemKind(OpFlag)) &&
7920            "Skipped past definitions?");
7921     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7922   }
7923   return CurOp;
7924 }
7925 
7926 namespace {
7927 
7928 class ExtraFlags {
7929   unsigned Flags = 0;
7930 
7931 public:
7932   explicit ExtraFlags(ImmutableCallSite CS) {
7933     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7934     if (IA->hasSideEffects())
7935       Flags |= InlineAsm::Extra_HasSideEffects;
7936     if (IA->isAlignStack())
7937       Flags |= InlineAsm::Extra_IsAlignStack;
7938     if (CS.isConvergent())
7939       Flags |= InlineAsm::Extra_IsConvergent;
7940     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7941   }
7942 
7943   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7944     // Ideally, we would only check against memory constraints.  However, the
7945     // meaning of an Other constraint can be target-specific and we can't easily
7946     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7947     // for Other constraints as well.
7948     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7949         OpInfo.ConstraintType == TargetLowering::C_Other) {
7950       if (OpInfo.Type == InlineAsm::isInput)
7951         Flags |= InlineAsm::Extra_MayLoad;
7952       else if (OpInfo.Type == InlineAsm::isOutput)
7953         Flags |= InlineAsm::Extra_MayStore;
7954       else if (OpInfo.Type == InlineAsm::isClobber)
7955         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7956     }
7957   }
7958 
7959   unsigned get() const { return Flags; }
7960 };
7961 
7962 } // end anonymous namespace
7963 
7964 /// visitInlineAsm - Handle a call to an InlineAsm object.
7965 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7966   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7967 
7968   /// ConstraintOperands - Information about all of the constraints.
7969   SDISelAsmOperandInfoVector ConstraintOperands;
7970 
7971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7972   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7973       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7974 
7975   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
7976   // AsmDialect, MayLoad, MayStore).
7977   bool HasSideEffect = IA->hasSideEffects();
7978   ExtraFlags ExtraInfo(CS);
7979 
7980   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7981   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7982   for (auto &T : TargetConstraints) {
7983     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7984     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7985 
7986     // Compute the value type for each operand.
7987     if (OpInfo.Type == InlineAsm::isInput ||
7988         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7989       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7990 
7991       // Process the call argument. BasicBlocks are labels, currently appearing
7992       // only in asm's.
7993       const Instruction *I = CS.getInstruction();
7994       if (isa<CallBrInst>(I) &&
7995           (ArgNo - 1) >= (cast<CallBrInst>(I)->getNumArgOperands() -
7996                           cast<CallBrInst>(I)->getNumIndirectDests())) {
7997         const auto *BA = cast<BlockAddress>(OpInfo.CallOperandVal);
7998         EVT VT = TLI.getValueType(DAG.getDataLayout(), BA->getType(), true);
7999         OpInfo.CallOperand = DAG.getTargetBlockAddress(BA, VT);
8000       } else if (const auto *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
8001         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
8002       } else {
8003         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
8004       }
8005 
8006       OpInfo.ConstraintVT =
8007           OpInfo
8008               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
8009               .getSimpleVT();
8010     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
8011       // The return value of the call is this value.  As such, there is no
8012       // corresponding argument.
8013       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8014       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
8015         OpInfo.ConstraintVT = TLI.getSimpleValueType(
8016             DAG.getDataLayout(), STy->getElementType(ResNo));
8017       } else {
8018         assert(ResNo == 0 && "Asm only has one result!");
8019         OpInfo.ConstraintVT =
8020             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
8021       }
8022       ++ResNo;
8023     } else {
8024       OpInfo.ConstraintVT = MVT::Other;
8025     }
8026 
8027     if (!HasSideEffect)
8028       HasSideEffect = OpInfo.hasMemory(TLI);
8029 
8030     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
8031     // FIXME: Could we compute this on OpInfo rather than T?
8032 
8033     // Compute the constraint code and ConstraintType to use.
8034     TLI.ComputeConstraintToUse(T, SDValue());
8035 
8036     ExtraInfo.update(T);
8037   }
8038 
8039 
8040   // We won't need to flush pending loads if this asm doesn't touch
8041   // memory and is nonvolatile.
8042   SDValue Flag, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
8043 
8044   bool IsCallBr = isa<CallBrInst>(CS.getInstruction());
8045   if (IsCallBr) {
8046     // If this is a callbr we need to flush pending exports since inlineasm_br
8047     // is a terminator. We need to do this before nodes are glued to
8048     // the inlineasm_br node.
8049     Chain = getControlRoot();
8050   }
8051 
8052   // Second pass over the constraints: compute which constraint option to use.
8053   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8054     // If this is an output operand with a matching input operand, look up the
8055     // matching input. If their types mismatch, e.g. one is an integer, the
8056     // other is floating point, or their sizes are different, flag it as an
8057     // error.
8058     if (OpInfo.hasMatchingInput()) {
8059       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
8060       patchMatchingInput(OpInfo, Input, DAG);
8061     }
8062 
8063     // Compute the constraint code and ConstraintType to use.
8064     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
8065 
8066     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8067         OpInfo.Type == InlineAsm::isClobber)
8068       continue;
8069 
8070     // If this is a memory input, and if the operand is not indirect, do what we
8071     // need to provide an address for the memory input.
8072     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
8073         !OpInfo.isIndirect) {
8074       assert((OpInfo.isMultipleAlternative ||
8075               (OpInfo.Type == InlineAsm::isInput)) &&
8076              "Can only indirectify direct input operands!");
8077 
8078       // Memory operands really want the address of the value.
8079       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
8080 
8081       // There is no longer a Value* corresponding to this operand.
8082       OpInfo.CallOperandVal = nullptr;
8083 
8084       // It is now an indirect operand.
8085       OpInfo.isIndirect = true;
8086     }
8087 
8088   }
8089 
8090   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
8091   std::vector<SDValue> AsmNodeOperands;
8092   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
8093   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
8094       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
8095 
8096   // If we have a !srcloc metadata node associated with it, we want to attach
8097   // this to the ultimately generated inline asm machineinstr.  To do this, we
8098   // pass in the third operand as this (potentially null) inline asm MDNode.
8099   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
8100   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
8101 
8102   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
8103   // bits as operand 3.
8104   AsmNodeOperands.push_back(DAG.getTargetConstant(
8105       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8106 
8107   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
8108   // this, assign virtual and physical registers for inputs and otput.
8109   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8110     // Assign Registers.
8111     SDISelAsmOperandInfo &RefOpInfo =
8112         OpInfo.isMatchingInputConstraint()
8113             ? ConstraintOperands[OpInfo.getMatchedOperand()]
8114             : OpInfo;
8115     GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
8116 
8117     switch (OpInfo.Type) {
8118     case InlineAsm::isOutput:
8119       if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
8120           (OpInfo.ConstraintType == TargetLowering::C_Other &&
8121            OpInfo.isIndirect)) {
8122         unsigned ConstraintID =
8123             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8124         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8125                "Failed to convert memory constraint code to constraint id.");
8126 
8127         // Add information to the INLINEASM node to know about this output.
8128         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8129         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
8130         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
8131                                                         MVT::i32));
8132         AsmNodeOperands.push_back(OpInfo.CallOperand);
8133         break;
8134       } else if ((OpInfo.ConstraintType == TargetLowering::C_Other &&
8135                   !OpInfo.isIndirect) ||
8136                  OpInfo.ConstraintType == TargetLowering::C_Register ||
8137                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
8138         // Otherwise, this outputs to a register (directly for C_Register /
8139         // C_RegisterClass, and a target-defined fashion for C_Other). Find a
8140         // register that we can use.
8141         if (OpInfo.AssignedRegs.Regs.empty()) {
8142           emitInlineAsmError(
8143               CS, "couldn't allocate output register for constraint '" +
8144                       Twine(OpInfo.ConstraintCode) + "'");
8145           return;
8146         }
8147 
8148         // Add information to the INLINEASM node to know that this register is
8149         // set.
8150         OpInfo.AssignedRegs.AddInlineAsmOperands(
8151             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
8152                                   : InlineAsm::Kind_RegDef,
8153             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
8154       }
8155       break;
8156 
8157     case InlineAsm::isInput: {
8158       SDValue InOperandVal = OpInfo.CallOperand;
8159 
8160       if (OpInfo.isMatchingInputConstraint()) {
8161         // If this is required to match an output register we have already set,
8162         // just use its register.
8163         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
8164                                                   AsmNodeOperands);
8165         unsigned OpFlag =
8166           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
8167         if (InlineAsm::isRegDefKind(OpFlag) ||
8168             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
8169           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
8170           if (OpInfo.isIndirect) {
8171             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
8172             emitInlineAsmError(CS, "inline asm not supported yet:"
8173                                    " don't know how to handle tied "
8174                                    "indirect register inputs");
8175             return;
8176           }
8177 
8178           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
8179           SmallVector<unsigned, 4> Regs;
8180 
8181           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
8182             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
8183             MachineRegisterInfo &RegInfo =
8184                 DAG.getMachineFunction().getRegInfo();
8185             for (unsigned i = 0; i != NumRegs; ++i)
8186               Regs.push_back(RegInfo.createVirtualRegister(RC));
8187           } else {
8188             emitInlineAsmError(CS, "inline asm error: This value type register "
8189                                    "class is not natively supported!");
8190             return;
8191           }
8192 
8193           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
8194 
8195           SDLoc dl = getCurSDLoc();
8196           // Use the produced MatchedRegs object to
8197           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
8198                                     CS.getInstruction());
8199           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
8200                                            true, OpInfo.getMatchedOperand(), dl,
8201                                            DAG, AsmNodeOperands);
8202           break;
8203         }
8204 
8205         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
8206         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
8207                "Unexpected number of operands");
8208         // Add information to the INLINEASM node to know about this input.
8209         // See InlineAsm.h isUseOperandTiedToDef.
8210         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
8211         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
8212                                                     OpInfo.getMatchedOperand());
8213         AsmNodeOperands.push_back(DAG.getTargetConstant(
8214             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8215         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
8216         break;
8217       }
8218 
8219       // Treat indirect 'X' constraint as memory.
8220       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
8221           OpInfo.isIndirect)
8222         OpInfo.ConstraintType = TargetLowering::C_Memory;
8223 
8224       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
8225         std::vector<SDValue> Ops;
8226         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
8227                                           Ops, DAG);
8228         if (Ops.empty()) {
8229           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
8230                                      Twine(OpInfo.ConstraintCode) + "'");
8231           return;
8232         }
8233 
8234         // Add information to the INLINEASM node to know about this input.
8235         unsigned ResOpType =
8236           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
8237         AsmNodeOperands.push_back(DAG.getTargetConstant(
8238             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
8239         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
8240         break;
8241       }
8242 
8243       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
8244         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
8245         assert(InOperandVal.getValueType() ==
8246                    TLI.getPointerTy(DAG.getDataLayout()) &&
8247                "Memory operands expect pointer values");
8248 
8249         unsigned ConstraintID =
8250             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
8251         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
8252                "Failed to convert memory constraint code to constraint id.");
8253 
8254         // Add information to the INLINEASM node to know about this input.
8255         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
8256         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
8257         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
8258                                                         getCurSDLoc(),
8259                                                         MVT::i32));
8260         AsmNodeOperands.push_back(InOperandVal);
8261         break;
8262       }
8263 
8264       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
8265               OpInfo.ConstraintType == TargetLowering::C_Register) &&
8266              "Unknown constraint type!");
8267 
8268       // TODO: Support this.
8269       if (OpInfo.isIndirect) {
8270         emitInlineAsmError(
8271             CS, "Don't know how to handle indirect register inputs yet "
8272                 "for constraint '" +
8273                     Twine(OpInfo.ConstraintCode) + "'");
8274         return;
8275       }
8276 
8277       // Copy the input into the appropriate registers.
8278       if (OpInfo.AssignedRegs.Regs.empty()) {
8279         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
8280                                    Twine(OpInfo.ConstraintCode) + "'");
8281         return;
8282       }
8283 
8284       SDLoc dl = getCurSDLoc();
8285 
8286       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
8287                                         Chain, &Flag, CS.getInstruction());
8288 
8289       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
8290                                                dl, DAG, AsmNodeOperands);
8291       break;
8292     }
8293     case InlineAsm::isClobber:
8294       // Add the clobbered value to the operand list, so that the register
8295       // allocator is aware that the physreg got clobbered.
8296       if (!OpInfo.AssignedRegs.Regs.empty())
8297         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
8298                                                  false, 0, getCurSDLoc(), DAG,
8299                                                  AsmNodeOperands);
8300       break;
8301     }
8302   }
8303 
8304   // Finish up input operands.  Set the input chain and add the flag last.
8305   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
8306   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
8307 
8308   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
8309   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
8310                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
8311   Flag = Chain.getValue(1);
8312 
8313   // Do additional work to generate outputs.
8314 
8315   SmallVector<EVT, 1> ResultVTs;
8316   SmallVector<SDValue, 1> ResultValues;
8317   SmallVector<SDValue, 8> OutChains;
8318 
8319   llvm::Type *CSResultType = CS.getType();
8320   ArrayRef<Type *> ResultTypes;
8321   if (StructType *StructResult = dyn_cast<StructType>(CSResultType))
8322     ResultTypes = StructResult->elements();
8323   else if (!CSResultType->isVoidTy())
8324     ResultTypes = makeArrayRef(CSResultType);
8325 
8326   auto CurResultType = ResultTypes.begin();
8327   auto handleRegAssign = [&](SDValue V) {
8328     assert(CurResultType != ResultTypes.end() && "Unexpected value");
8329     assert((*CurResultType)->isSized() && "Unexpected unsized type");
8330     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
8331     ++CurResultType;
8332     // If the type of the inline asm call site return value is different but has
8333     // same size as the type of the asm output bitcast it.  One example of this
8334     // is for vectors with different width / number of elements.  This can
8335     // happen for register classes that can contain multiple different value
8336     // types.  The preg or vreg allocated may not have the same VT as was
8337     // expected.
8338     //
8339     // This can also happen for a return value that disagrees with the register
8340     // class it is put in, eg. a double in a general-purpose register on a
8341     // 32-bit machine.
8342     if (ResultVT != V.getValueType() &&
8343         ResultVT.getSizeInBits() == V.getValueSizeInBits())
8344       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
8345     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
8346              V.getValueType().isInteger()) {
8347       // If a result value was tied to an input value, the computed result
8348       // may have a wider width than the expected result.  Extract the
8349       // relevant portion.
8350       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
8351     }
8352     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
8353     ResultVTs.push_back(ResultVT);
8354     ResultValues.push_back(V);
8355   };
8356 
8357   // Deal with output operands.
8358   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
8359     if (OpInfo.Type == InlineAsm::isOutput) {
8360       SDValue Val;
8361       // Skip trivial output operands.
8362       if (OpInfo.AssignedRegs.Regs.empty())
8363         continue;
8364 
8365       switch (OpInfo.ConstraintType) {
8366       case TargetLowering::C_Register:
8367       case TargetLowering::C_RegisterClass:
8368         Val = OpInfo.AssignedRegs.getCopyFromRegs(
8369             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
8370         break;
8371       case TargetLowering::C_Other:
8372         Val = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
8373                                               OpInfo, DAG);
8374         break;
8375       case TargetLowering::C_Memory:
8376         break; // Already handled.
8377       case TargetLowering::C_Unknown:
8378         assert(false && "Unexpected unknown constraint");
8379       }
8380 
8381       // Indirect output manifest as stores. Record output chains.
8382       if (OpInfo.isIndirect) {
8383         const Value *Ptr = OpInfo.CallOperandVal;
8384         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
8385         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
8386                                      MachinePointerInfo(Ptr));
8387         OutChains.push_back(Store);
8388       } else {
8389         // generate CopyFromRegs to associated registers.
8390         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
8391         if (Val.getOpcode() == ISD::MERGE_VALUES) {
8392           for (const SDValue &V : Val->op_values())
8393             handleRegAssign(V);
8394         } else
8395           handleRegAssign(Val);
8396       }
8397     }
8398   }
8399 
8400   // Set results.
8401   if (!ResultValues.empty()) {
8402     assert(CurResultType == ResultTypes.end() &&
8403            "Mismatch in number of ResultTypes");
8404     assert(ResultValues.size() == ResultTypes.size() &&
8405            "Mismatch in number of output operands in asm result");
8406 
8407     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
8408                             DAG.getVTList(ResultVTs), ResultValues);
8409     setValue(CS.getInstruction(), V);
8410   }
8411 
8412   // Collect store chains.
8413   if (!OutChains.empty())
8414     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
8415 
8416   // Only Update Root if inline assembly has a memory effect.
8417   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr)
8418     DAG.setRoot(Chain);
8419 }
8420 
8421 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
8422                                              const Twine &Message) {
8423   LLVMContext &Ctx = *DAG.getContext();
8424   Ctx.emitError(CS.getInstruction(), Message);
8425 
8426   // Make sure we leave the DAG in a valid state
8427   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8428   SmallVector<EVT, 1> ValueVTs;
8429   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8430 
8431   if (ValueVTs.empty())
8432     return;
8433 
8434   SmallVector<SDValue, 1> Ops;
8435   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
8436     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
8437 
8438   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
8439 }
8440 
8441 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
8442   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
8443                           MVT::Other, getRoot(),
8444                           getValue(I.getArgOperand(0)),
8445                           DAG.getSrcValue(I.getArgOperand(0))));
8446 }
8447 
8448 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
8449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8450   const DataLayout &DL = DAG.getDataLayout();
8451   SDValue V = DAG.getVAArg(
8452       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
8453       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
8454       DL.getABITypeAlignment(I.getType()));
8455   DAG.setRoot(V.getValue(1));
8456 
8457   if (I.getType()->isPointerTy())
8458     V = DAG.getPtrExtOrTrunc(
8459         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
8460   setValue(&I, V);
8461 }
8462 
8463 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
8464   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
8465                           MVT::Other, getRoot(),
8466                           getValue(I.getArgOperand(0)),
8467                           DAG.getSrcValue(I.getArgOperand(0))));
8468 }
8469 
8470 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
8471   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
8472                           MVT::Other, getRoot(),
8473                           getValue(I.getArgOperand(0)),
8474                           getValue(I.getArgOperand(1)),
8475                           DAG.getSrcValue(I.getArgOperand(0)),
8476                           DAG.getSrcValue(I.getArgOperand(1))));
8477 }
8478 
8479 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
8480                                                     const Instruction &I,
8481                                                     SDValue Op) {
8482   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
8483   if (!Range)
8484     return Op;
8485 
8486   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8487   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
8488     return Op;
8489 
8490   APInt Lo = CR.getUnsignedMin();
8491   if (!Lo.isMinValue())
8492     return Op;
8493 
8494   APInt Hi = CR.getUnsignedMax();
8495   unsigned Bits = std::max(Hi.getActiveBits(),
8496                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8497 
8498   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8499 
8500   SDLoc SL = getCurSDLoc();
8501 
8502   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8503                              DAG.getValueType(SmallVT));
8504   unsigned NumVals = Op.getNode()->getNumValues();
8505   if (NumVals == 1)
8506     return ZExt;
8507 
8508   SmallVector<SDValue, 4> Ops;
8509 
8510   Ops.push_back(ZExt);
8511   for (unsigned I = 1; I != NumVals; ++I)
8512     Ops.push_back(Op.getValue(I));
8513 
8514   return DAG.getMergeValues(Ops, SL);
8515 }
8516 
8517 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8518 /// the call being lowered.
8519 ///
8520 /// This is a helper for lowering intrinsics that follow a target calling
8521 /// convention or require stack pointer adjustment. Only a subset of the
8522 /// intrinsic's operands need to participate in the calling convention.
8523 void SelectionDAGBuilder::populateCallLoweringInfo(
8524     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
8525     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8526     bool IsPatchPoint) {
8527   TargetLowering::ArgListTy Args;
8528   Args.reserve(NumArgs);
8529 
8530   // Populate the argument list.
8531   // Attributes for args start at offset 1, after the return attribute.
8532   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8533        ArgI != ArgE; ++ArgI) {
8534     const Value *V = Call->getOperand(ArgI);
8535 
8536     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8537 
8538     TargetLowering::ArgListEntry Entry;
8539     Entry.Node = getValue(V);
8540     Entry.Ty = V->getType();
8541     Entry.setAttributes(Call, ArgI);
8542     Args.push_back(Entry);
8543   }
8544 
8545   CLI.setDebugLoc(getCurSDLoc())
8546       .setChain(getRoot())
8547       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args))
8548       .setDiscardResult(Call->use_empty())
8549       .setIsPatchPoint(IsPatchPoint);
8550 }
8551 
8552 /// Add a stack map intrinsic call's live variable operands to a stackmap
8553 /// or patchpoint target node's operand list.
8554 ///
8555 /// Constants are converted to TargetConstants purely as an optimization to
8556 /// avoid constant materialization and register allocation.
8557 ///
8558 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8559 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8560 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8561 /// address materialization and register allocation, but may also be required
8562 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8563 /// alloca in the entry block, then the runtime may assume that the alloca's
8564 /// StackMap location can be read immediately after compilation and that the
8565 /// location is valid at any point during execution (this is similar to the
8566 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8567 /// only available in a register, then the runtime would need to trap when
8568 /// execution reaches the StackMap in order to read the alloca's location.
8569 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8570                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8571                                 SelectionDAGBuilder &Builder) {
8572   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8573     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8574     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8575       Ops.push_back(
8576         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8577       Ops.push_back(
8578         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8579     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8580       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8581       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8582           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8583     } else
8584       Ops.push_back(OpVal);
8585   }
8586 }
8587 
8588 /// Lower llvm.experimental.stackmap directly to its target opcode.
8589 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8590   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8591   //                                  [live variables...])
8592 
8593   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8594 
8595   SDValue Chain, InFlag, Callee, NullPtr;
8596   SmallVector<SDValue, 32> Ops;
8597 
8598   SDLoc DL = getCurSDLoc();
8599   Callee = getValue(CI.getCalledValue());
8600   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8601 
8602   // The stackmap intrinsic only records the live variables (the arguemnts
8603   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8604   // intrinsic, this won't be lowered to a function call. This means we don't
8605   // have to worry about calling conventions and target specific lowering code.
8606   // Instead we perform the call lowering right here.
8607   //
8608   // chain, flag = CALLSEQ_START(chain, 0, 0)
8609   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8610   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8611   //
8612   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8613   InFlag = Chain.getValue(1);
8614 
8615   // Add the <id> and <numBytes> constants.
8616   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8617   Ops.push_back(DAG.getTargetConstant(
8618                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8619   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8620   Ops.push_back(DAG.getTargetConstant(
8621                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8622                   MVT::i32));
8623 
8624   // Push live variables for the stack map.
8625   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8626 
8627   // We are not pushing any register mask info here on the operands list,
8628   // because the stackmap doesn't clobber anything.
8629 
8630   // Push the chain and the glue flag.
8631   Ops.push_back(Chain);
8632   Ops.push_back(InFlag);
8633 
8634   // Create the STACKMAP node.
8635   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8636   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8637   Chain = SDValue(SM, 0);
8638   InFlag = Chain.getValue(1);
8639 
8640   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8641 
8642   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8643 
8644   // Set the root to the target-lowered call chain.
8645   DAG.setRoot(Chain);
8646 
8647   // Inform the Frame Information that we have a stackmap in this function.
8648   FuncInfo.MF->getFrameInfo().setHasStackMap();
8649 }
8650 
8651 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8652 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8653                                           const BasicBlock *EHPadBB) {
8654   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8655   //                                                 i32 <numBytes>,
8656   //                                                 i8* <target>,
8657   //                                                 i32 <numArgs>,
8658   //                                                 [Args...],
8659   //                                                 [live variables...])
8660 
8661   CallingConv::ID CC = CS.getCallingConv();
8662   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8663   bool HasDef = !CS->getType()->isVoidTy();
8664   SDLoc dl = getCurSDLoc();
8665   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8666 
8667   // Handle immediate and symbolic callees.
8668   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8669     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8670                                    /*isTarget=*/true);
8671   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8672     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8673                                          SDLoc(SymbolicCallee),
8674                                          SymbolicCallee->getValueType(0));
8675 
8676   // Get the real number of arguments participating in the call <numArgs>
8677   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8678   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8679 
8680   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8681   // Intrinsics include all meta-operands up to but not including CC.
8682   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8683   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8684          "Not enough arguments provided to the patchpoint intrinsic");
8685 
8686   // For AnyRegCC the arguments are lowered later on manually.
8687   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8688   Type *ReturnTy =
8689     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8690 
8691   TargetLowering::CallLoweringInfo CLI(DAG);
8692   populateCallLoweringInfo(CLI, cast<CallBase>(CS.getInstruction()),
8693                            NumMetaOpers, NumCallArgs, Callee, ReturnTy, true);
8694   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8695 
8696   SDNode *CallEnd = Result.second.getNode();
8697   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8698     CallEnd = CallEnd->getOperand(0).getNode();
8699 
8700   /// Get a call instruction from the call sequence chain.
8701   /// Tail calls are not allowed.
8702   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8703          "Expected a callseq node.");
8704   SDNode *Call = CallEnd->getOperand(0).getNode();
8705   bool HasGlue = Call->getGluedNode();
8706 
8707   // Replace the target specific call node with the patchable intrinsic.
8708   SmallVector<SDValue, 8> Ops;
8709 
8710   // Add the <id> and <numBytes> constants.
8711   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8712   Ops.push_back(DAG.getTargetConstant(
8713                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8714   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8715   Ops.push_back(DAG.getTargetConstant(
8716                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8717                   MVT::i32));
8718 
8719   // Add the callee.
8720   Ops.push_back(Callee);
8721 
8722   // Adjust <numArgs> to account for any arguments that have been passed on the
8723   // stack instead.
8724   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8725   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8726   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8727   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8728 
8729   // Add the calling convention
8730   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8731 
8732   // Add the arguments we omitted previously. The register allocator should
8733   // place these in any free register.
8734   if (IsAnyRegCC)
8735     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8736       Ops.push_back(getValue(CS.getArgument(i)));
8737 
8738   // Push the arguments from the call instruction up to the register mask.
8739   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8740   Ops.append(Call->op_begin() + 2, e);
8741 
8742   // Push live variables for the stack map.
8743   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8744 
8745   // Push the register mask info.
8746   if (HasGlue)
8747     Ops.push_back(*(Call->op_end()-2));
8748   else
8749     Ops.push_back(*(Call->op_end()-1));
8750 
8751   // Push the chain (this is originally the first operand of the call, but
8752   // becomes now the last or second to last operand).
8753   Ops.push_back(*(Call->op_begin()));
8754 
8755   // Push the glue flag (last operand).
8756   if (HasGlue)
8757     Ops.push_back(*(Call->op_end()-1));
8758 
8759   SDVTList NodeTys;
8760   if (IsAnyRegCC && HasDef) {
8761     // Create the return types based on the intrinsic definition
8762     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8763     SmallVector<EVT, 3> ValueVTs;
8764     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8765     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8766 
8767     // There is always a chain and a glue type at the end
8768     ValueVTs.push_back(MVT::Other);
8769     ValueVTs.push_back(MVT::Glue);
8770     NodeTys = DAG.getVTList(ValueVTs);
8771   } else
8772     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8773 
8774   // Replace the target specific call node with a PATCHPOINT node.
8775   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8776                                          dl, NodeTys, Ops);
8777 
8778   // Update the NodeMap.
8779   if (HasDef) {
8780     if (IsAnyRegCC)
8781       setValue(CS.getInstruction(), SDValue(MN, 0));
8782     else
8783       setValue(CS.getInstruction(), Result.first);
8784   }
8785 
8786   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8787   // call sequence. Furthermore the location of the chain and glue can change
8788   // when the AnyReg calling convention is used and the intrinsic returns a
8789   // value.
8790   if (IsAnyRegCC && HasDef) {
8791     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8792     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8793     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8794   } else
8795     DAG.ReplaceAllUsesWith(Call, MN);
8796   DAG.DeleteNode(Call);
8797 
8798   // Inform the Frame Information that we have a patchpoint in this function.
8799   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8800 }
8801 
8802 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8803                                             unsigned Intrinsic) {
8804   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8805   SDValue Op1 = getValue(I.getArgOperand(0));
8806   SDValue Op2;
8807   if (I.getNumArgOperands() > 1)
8808     Op2 = getValue(I.getArgOperand(1));
8809   SDLoc dl = getCurSDLoc();
8810   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8811   SDValue Res;
8812   FastMathFlags FMF;
8813   if (isa<FPMathOperator>(I))
8814     FMF = I.getFastMathFlags();
8815 
8816   switch (Intrinsic) {
8817   case Intrinsic::experimental_vector_reduce_fadd:
8818     if (FMF.isFast())
8819       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8820     else
8821       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8822     break;
8823   case Intrinsic::experimental_vector_reduce_fmul:
8824     if (FMF.isFast())
8825       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8826     else
8827       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8828     break;
8829   case Intrinsic::experimental_vector_reduce_add:
8830     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8831     break;
8832   case Intrinsic::experimental_vector_reduce_mul:
8833     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8834     break;
8835   case Intrinsic::experimental_vector_reduce_and:
8836     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8837     break;
8838   case Intrinsic::experimental_vector_reduce_or:
8839     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8840     break;
8841   case Intrinsic::experimental_vector_reduce_xor:
8842     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8843     break;
8844   case Intrinsic::experimental_vector_reduce_smax:
8845     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8846     break;
8847   case Intrinsic::experimental_vector_reduce_smin:
8848     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8849     break;
8850   case Intrinsic::experimental_vector_reduce_umax:
8851     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8852     break;
8853   case Intrinsic::experimental_vector_reduce_umin:
8854     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8855     break;
8856   case Intrinsic::experimental_vector_reduce_fmax:
8857     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8858     break;
8859   case Intrinsic::experimental_vector_reduce_fmin:
8860     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8861     break;
8862   default:
8863     llvm_unreachable("Unhandled vector reduce intrinsic");
8864   }
8865   setValue(&I, Res);
8866 }
8867 
8868 /// Returns an AttributeList representing the attributes applied to the return
8869 /// value of the given call.
8870 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8871   SmallVector<Attribute::AttrKind, 2> Attrs;
8872   if (CLI.RetSExt)
8873     Attrs.push_back(Attribute::SExt);
8874   if (CLI.RetZExt)
8875     Attrs.push_back(Attribute::ZExt);
8876   if (CLI.IsInReg)
8877     Attrs.push_back(Attribute::InReg);
8878 
8879   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8880                             Attrs);
8881 }
8882 
8883 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8884 /// implementation, which just calls LowerCall.
8885 /// FIXME: When all targets are
8886 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8887 std::pair<SDValue, SDValue>
8888 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8889   // Handle the incoming return values from the call.
8890   CLI.Ins.clear();
8891   Type *OrigRetTy = CLI.RetTy;
8892   SmallVector<EVT, 4> RetTys;
8893   SmallVector<uint64_t, 4> Offsets;
8894   auto &DL = CLI.DAG.getDataLayout();
8895   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8896 
8897   if (CLI.IsPostTypeLegalization) {
8898     // If we are lowering a libcall after legalization, split the return type.
8899     SmallVector<EVT, 4> OldRetTys;
8900     SmallVector<uint64_t, 4> OldOffsets;
8901     RetTys.swap(OldRetTys);
8902     Offsets.swap(OldOffsets);
8903 
8904     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8905       EVT RetVT = OldRetTys[i];
8906       uint64_t Offset = OldOffsets[i];
8907       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8908       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8909       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8910       RetTys.append(NumRegs, RegisterVT);
8911       for (unsigned j = 0; j != NumRegs; ++j)
8912         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8913     }
8914   }
8915 
8916   SmallVector<ISD::OutputArg, 4> Outs;
8917   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8918 
8919   bool CanLowerReturn =
8920       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8921                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8922 
8923   SDValue DemoteStackSlot;
8924   int DemoteStackIdx = -100;
8925   if (!CanLowerReturn) {
8926     // FIXME: equivalent assert?
8927     // assert(!CS.hasInAllocaArgument() &&
8928     //        "sret demotion is incompatible with inalloca");
8929     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8930     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8931     MachineFunction &MF = CLI.DAG.getMachineFunction();
8932     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8933     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8934                                               DL.getAllocaAddrSpace());
8935 
8936     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8937     ArgListEntry Entry;
8938     Entry.Node = DemoteStackSlot;
8939     Entry.Ty = StackSlotPtrType;
8940     Entry.IsSExt = false;
8941     Entry.IsZExt = false;
8942     Entry.IsInReg = false;
8943     Entry.IsSRet = true;
8944     Entry.IsNest = false;
8945     Entry.IsByVal = false;
8946     Entry.IsReturned = false;
8947     Entry.IsSwiftSelf = false;
8948     Entry.IsSwiftError = false;
8949     Entry.Alignment = Align;
8950     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8951     CLI.NumFixedArgs += 1;
8952     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8953 
8954     // sret demotion isn't compatible with tail-calls, since the sret argument
8955     // points into the callers stack frame.
8956     CLI.IsTailCall = false;
8957   } else {
8958     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8959         CLI.RetTy, CLI.CallConv, CLI.IsVarArg);
8960     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8961       ISD::ArgFlagsTy Flags;
8962       if (NeedsRegBlock) {
8963         Flags.setInConsecutiveRegs();
8964         if (I == RetTys.size() - 1)
8965           Flags.setInConsecutiveRegsLast();
8966       }
8967       EVT VT = RetTys[I];
8968       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8969                                                      CLI.CallConv, VT);
8970       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8971                                                        CLI.CallConv, VT);
8972       for (unsigned i = 0; i != NumRegs; ++i) {
8973         ISD::InputArg MyFlags;
8974         MyFlags.Flags = Flags;
8975         MyFlags.VT = RegisterVT;
8976         MyFlags.ArgVT = VT;
8977         MyFlags.Used = CLI.IsReturnValueUsed;
8978         if (CLI.RetTy->isPointerTy()) {
8979           MyFlags.Flags.setPointer();
8980           MyFlags.Flags.setPointerAddrSpace(
8981               cast<PointerType>(CLI.RetTy)->getAddressSpace());
8982         }
8983         if (CLI.RetSExt)
8984           MyFlags.Flags.setSExt();
8985         if (CLI.RetZExt)
8986           MyFlags.Flags.setZExt();
8987         if (CLI.IsInReg)
8988           MyFlags.Flags.setInReg();
8989         CLI.Ins.push_back(MyFlags);
8990       }
8991     }
8992   }
8993 
8994   // We push in swifterror return as the last element of CLI.Ins.
8995   ArgListTy &Args = CLI.getArgs();
8996   if (supportSwiftError()) {
8997     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8998       if (Args[i].IsSwiftError) {
8999         ISD::InputArg MyFlags;
9000         MyFlags.VT = getPointerTy(DL);
9001         MyFlags.ArgVT = EVT(getPointerTy(DL));
9002         MyFlags.Flags.setSwiftError();
9003         CLI.Ins.push_back(MyFlags);
9004       }
9005     }
9006   }
9007 
9008   // Handle all of the outgoing arguments.
9009   CLI.Outs.clear();
9010   CLI.OutVals.clear();
9011   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
9012     SmallVector<EVT, 4> ValueVTs;
9013     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
9014     // FIXME: Split arguments if CLI.IsPostTypeLegalization
9015     Type *FinalType = Args[i].Ty;
9016     if (Args[i].IsByVal)
9017       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
9018     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
9019         FinalType, CLI.CallConv, CLI.IsVarArg);
9020     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
9021          ++Value) {
9022       EVT VT = ValueVTs[Value];
9023       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
9024       SDValue Op = SDValue(Args[i].Node.getNode(),
9025                            Args[i].Node.getResNo() + Value);
9026       ISD::ArgFlagsTy Flags;
9027 
9028       // Certain targets (such as MIPS), may have a different ABI alignment
9029       // for a type depending on the context. Give the target a chance to
9030       // specify the alignment it wants.
9031       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
9032 
9033       if (Args[i].Ty->isPointerTy()) {
9034         Flags.setPointer();
9035         Flags.setPointerAddrSpace(
9036             cast<PointerType>(Args[i].Ty)->getAddressSpace());
9037       }
9038       if (Args[i].IsZExt)
9039         Flags.setZExt();
9040       if (Args[i].IsSExt)
9041         Flags.setSExt();
9042       if (Args[i].IsInReg) {
9043         // If we are using vectorcall calling convention, a structure that is
9044         // passed InReg - is surely an HVA
9045         if (CLI.CallConv == CallingConv::X86_VectorCall &&
9046             isa<StructType>(FinalType)) {
9047           // The first value of a structure is marked
9048           if (0 == Value)
9049             Flags.setHvaStart();
9050           Flags.setHva();
9051         }
9052         // Set InReg Flag
9053         Flags.setInReg();
9054       }
9055       if (Args[i].IsSRet)
9056         Flags.setSRet();
9057       if (Args[i].IsSwiftSelf)
9058         Flags.setSwiftSelf();
9059       if (Args[i].IsSwiftError)
9060         Flags.setSwiftError();
9061       if (Args[i].IsByVal)
9062         Flags.setByVal();
9063       if (Args[i].IsInAlloca) {
9064         Flags.setInAlloca();
9065         // Set the byval flag for CCAssignFn callbacks that don't know about
9066         // inalloca.  This way we can know how many bytes we should've allocated
9067         // and how many bytes a callee cleanup function will pop.  If we port
9068         // inalloca to more targets, we'll have to add custom inalloca handling
9069         // in the various CC lowering callbacks.
9070         Flags.setByVal();
9071       }
9072       if (Args[i].IsByVal || Args[i].IsInAlloca) {
9073         PointerType *Ty = cast<PointerType>(Args[i].Ty);
9074         Type *ElementTy = Ty->getElementType();
9075         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9076         // For ByVal, alignment should come from FE.  BE will guess if this
9077         // info is not there but there are cases it cannot get right.
9078         unsigned FrameAlign;
9079         if (Args[i].Alignment)
9080           FrameAlign = Args[i].Alignment;
9081         else
9082           FrameAlign = getByValTypeAlignment(ElementTy, DL);
9083         Flags.setByValAlign(FrameAlign);
9084       }
9085       if (Args[i].IsNest)
9086         Flags.setNest();
9087       if (NeedsRegBlock)
9088         Flags.setInConsecutiveRegs();
9089       Flags.setOrigAlign(OriginalAlignment);
9090 
9091       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9092                                                  CLI.CallConv, VT);
9093       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9094                                                         CLI.CallConv, VT);
9095       SmallVector<SDValue, 4> Parts(NumParts);
9096       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
9097 
9098       if (Args[i].IsSExt)
9099         ExtendKind = ISD::SIGN_EXTEND;
9100       else if (Args[i].IsZExt)
9101         ExtendKind = ISD::ZERO_EXTEND;
9102 
9103       // Conservatively only handle 'returned' on non-vectors that can be lowered,
9104       // for now.
9105       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
9106           CanLowerReturn) {
9107         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
9108                "unexpected use of 'returned'");
9109         // Before passing 'returned' to the target lowering code, ensure that
9110         // either the register MVT and the actual EVT are the same size or that
9111         // the return value and argument are extended in the same way; in these
9112         // cases it's safe to pass the argument register value unchanged as the
9113         // return register value (although it's at the target's option whether
9114         // to do so)
9115         // TODO: allow code generation to take advantage of partially preserved
9116         // registers rather than clobbering the entire register when the
9117         // parameter extension method is not compatible with the return
9118         // extension method
9119         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
9120             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
9121              CLI.RetZExt == Args[i].IsZExt))
9122           Flags.setReturned();
9123       }
9124 
9125       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
9126                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
9127 
9128       for (unsigned j = 0; j != NumParts; ++j) {
9129         // if it isn't first piece, alignment must be 1
9130         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
9131                                i < CLI.NumFixedArgs,
9132                                i, j*Parts[j].getValueType().getStoreSize());
9133         if (NumParts > 1 && j == 0)
9134           MyFlags.Flags.setSplit();
9135         else if (j != 0) {
9136           MyFlags.Flags.setOrigAlign(1);
9137           if (j == NumParts - 1)
9138             MyFlags.Flags.setSplitEnd();
9139         }
9140 
9141         CLI.Outs.push_back(MyFlags);
9142         CLI.OutVals.push_back(Parts[j]);
9143       }
9144 
9145       if (NeedsRegBlock && Value == NumValues - 1)
9146         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
9147     }
9148   }
9149 
9150   SmallVector<SDValue, 4> InVals;
9151   CLI.Chain = LowerCall(CLI, InVals);
9152 
9153   // Update CLI.InVals to use outside of this function.
9154   CLI.InVals = InVals;
9155 
9156   // Verify that the target's LowerCall behaved as expected.
9157   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
9158          "LowerCall didn't return a valid chain!");
9159   assert((!CLI.IsTailCall || InVals.empty()) &&
9160          "LowerCall emitted a return value for a tail call!");
9161   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
9162          "LowerCall didn't emit the correct number of values!");
9163 
9164   // For a tail call, the return value is merely live-out and there aren't
9165   // any nodes in the DAG representing it. Return a special value to
9166   // indicate that a tail call has been emitted and no more Instructions
9167   // should be processed in the current block.
9168   if (CLI.IsTailCall) {
9169     CLI.DAG.setRoot(CLI.Chain);
9170     return std::make_pair(SDValue(), SDValue());
9171   }
9172 
9173 #ifndef NDEBUG
9174   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
9175     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
9176     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
9177            "LowerCall emitted a value with the wrong type!");
9178   }
9179 #endif
9180 
9181   SmallVector<SDValue, 4> ReturnValues;
9182   if (!CanLowerReturn) {
9183     // The instruction result is the result of loading from the
9184     // hidden sret parameter.
9185     SmallVector<EVT, 1> PVTs;
9186     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
9187 
9188     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
9189     assert(PVTs.size() == 1 && "Pointers should fit in one register");
9190     EVT PtrVT = PVTs[0];
9191 
9192     unsigned NumValues = RetTys.size();
9193     ReturnValues.resize(NumValues);
9194     SmallVector<SDValue, 4> Chains(NumValues);
9195 
9196     // An aggregate return value cannot wrap around the address space, so
9197     // offsets to its parts don't wrap either.
9198     SDNodeFlags Flags;
9199     Flags.setNoUnsignedWrap(true);
9200 
9201     for (unsigned i = 0; i < NumValues; ++i) {
9202       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
9203                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
9204                                                         PtrVT), Flags);
9205       SDValue L = CLI.DAG.getLoad(
9206           RetTys[i], CLI.DL, CLI.Chain, Add,
9207           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
9208                                             DemoteStackIdx, Offsets[i]),
9209           /* Alignment = */ 1);
9210       ReturnValues[i] = L;
9211       Chains[i] = L.getValue(1);
9212     }
9213 
9214     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
9215   } else {
9216     // Collect the legal value parts into potentially illegal values
9217     // that correspond to the original function's return values.
9218     Optional<ISD::NodeType> AssertOp;
9219     if (CLI.RetSExt)
9220       AssertOp = ISD::AssertSext;
9221     else if (CLI.RetZExt)
9222       AssertOp = ISD::AssertZext;
9223     unsigned CurReg = 0;
9224     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
9225       EVT VT = RetTys[I];
9226       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
9227                                                      CLI.CallConv, VT);
9228       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
9229                                                        CLI.CallConv, VT);
9230 
9231       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
9232                                               NumRegs, RegisterVT, VT, nullptr,
9233                                               CLI.CallConv, AssertOp));
9234       CurReg += NumRegs;
9235     }
9236 
9237     // For a function returning void, there is no return value. We can't create
9238     // such a node, so we just return a null return value in that case. In
9239     // that case, nothing will actually look at the value.
9240     if (ReturnValues.empty())
9241       return std::make_pair(SDValue(), CLI.Chain);
9242   }
9243 
9244   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
9245                                 CLI.DAG.getVTList(RetTys), ReturnValues);
9246   return std::make_pair(Res, CLI.Chain);
9247 }
9248 
9249 void TargetLowering::LowerOperationWrapper(SDNode *N,
9250                                            SmallVectorImpl<SDValue> &Results,
9251                                            SelectionDAG &DAG) const {
9252   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
9253     Results.push_back(Res);
9254 }
9255 
9256 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9257   llvm_unreachable("LowerOperation not implemented for this target!");
9258 }
9259 
9260 void
9261 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
9262   SDValue Op = getNonRegisterValue(V);
9263   assert((Op.getOpcode() != ISD::CopyFromReg ||
9264           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
9265          "Copy from a reg to the same reg!");
9266   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
9267 
9268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9269   // If this is an InlineAsm we have to match the registers required, not the
9270   // notional registers required by the type.
9271 
9272   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
9273                    None); // This is not an ABI copy.
9274   SDValue Chain = DAG.getEntryNode();
9275 
9276   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
9277                               FuncInfo.PreferredExtendType.end())
9278                                  ? ISD::ANY_EXTEND
9279                                  : FuncInfo.PreferredExtendType[V];
9280   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
9281   PendingExports.push_back(Chain);
9282 }
9283 
9284 #include "llvm/CodeGen/SelectionDAGISel.h"
9285 
9286 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
9287 /// entry block, return true.  This includes arguments used by switches, since
9288 /// the switch may expand into multiple basic blocks.
9289 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
9290   // With FastISel active, we may be splitting blocks, so force creation
9291   // of virtual registers for all non-dead arguments.
9292   if (FastISel)
9293     return A->use_empty();
9294 
9295   const BasicBlock &Entry = A->getParent()->front();
9296   for (const User *U : A->users())
9297     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
9298       return false;  // Use not in entry block.
9299 
9300   return true;
9301 }
9302 
9303 using ArgCopyElisionMapTy =
9304     DenseMap<const Argument *,
9305              std::pair<const AllocaInst *, const StoreInst *>>;
9306 
9307 /// Scan the entry block of the function in FuncInfo for arguments that look
9308 /// like copies into a local alloca. Record any copied arguments in
9309 /// ArgCopyElisionCandidates.
9310 static void
9311 findArgumentCopyElisionCandidates(const DataLayout &DL,
9312                                   FunctionLoweringInfo *FuncInfo,
9313                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
9314   // Record the state of every static alloca used in the entry block. Argument
9315   // allocas are all used in the entry block, so we need approximately as many
9316   // entries as we have arguments.
9317   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
9318   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
9319   unsigned NumArgs = FuncInfo->Fn->arg_size();
9320   StaticAllocas.reserve(NumArgs * 2);
9321 
9322   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
9323     if (!V)
9324       return nullptr;
9325     V = V->stripPointerCasts();
9326     const auto *AI = dyn_cast<AllocaInst>(V);
9327     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
9328       return nullptr;
9329     auto Iter = StaticAllocas.insert({AI, Unknown});
9330     return &Iter.first->second;
9331   };
9332 
9333   // Look for stores of arguments to static allocas. Look through bitcasts and
9334   // GEPs to handle type coercions, as long as the alloca is fully initialized
9335   // by the store. Any non-store use of an alloca escapes it and any subsequent
9336   // unanalyzed store might write it.
9337   // FIXME: Handle structs initialized with multiple stores.
9338   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
9339     // Look for stores, and handle non-store uses conservatively.
9340     const auto *SI = dyn_cast<StoreInst>(&I);
9341     if (!SI) {
9342       // We will look through cast uses, so ignore them completely.
9343       if (I.isCast())
9344         continue;
9345       // Ignore debug info intrinsics, they don't escape or store to allocas.
9346       if (isa<DbgInfoIntrinsic>(I))
9347         continue;
9348       // This is an unknown instruction. Assume it escapes or writes to all
9349       // static alloca operands.
9350       for (const Use &U : I.operands()) {
9351         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
9352           *Info = StaticAllocaInfo::Clobbered;
9353       }
9354       continue;
9355     }
9356 
9357     // If the stored value is a static alloca, mark it as escaped.
9358     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
9359       *Info = StaticAllocaInfo::Clobbered;
9360 
9361     // Check if the destination is a static alloca.
9362     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
9363     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
9364     if (!Info)
9365       continue;
9366     const AllocaInst *AI = cast<AllocaInst>(Dst);
9367 
9368     // Skip allocas that have been initialized or clobbered.
9369     if (*Info != StaticAllocaInfo::Unknown)
9370       continue;
9371 
9372     // Check if the stored value is an argument, and that this store fully
9373     // initializes the alloca. Don't elide copies from the same argument twice.
9374     const Value *Val = SI->getValueOperand()->stripPointerCasts();
9375     const auto *Arg = dyn_cast<Argument>(Val);
9376     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
9377         Arg->getType()->isEmptyTy() ||
9378         DL.getTypeStoreSize(Arg->getType()) !=
9379             DL.getTypeAllocSize(AI->getAllocatedType()) ||
9380         ArgCopyElisionCandidates.count(Arg)) {
9381       *Info = StaticAllocaInfo::Clobbered;
9382       continue;
9383     }
9384 
9385     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
9386                       << '\n');
9387 
9388     // Mark this alloca and store for argument copy elision.
9389     *Info = StaticAllocaInfo::Elidable;
9390     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
9391 
9392     // Stop scanning if we've seen all arguments. This will happen early in -O0
9393     // builds, which is useful, because -O0 builds have large entry blocks and
9394     // many allocas.
9395     if (ArgCopyElisionCandidates.size() == NumArgs)
9396       break;
9397   }
9398 }
9399 
9400 /// Try to elide argument copies from memory into a local alloca. Succeeds if
9401 /// ArgVal is a load from a suitable fixed stack object.
9402 static void tryToElideArgumentCopy(
9403     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
9404     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
9405     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
9406     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
9407     SDValue ArgVal, bool &ArgHasUses) {
9408   // Check if this is a load from a fixed stack object.
9409   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
9410   if (!LNode)
9411     return;
9412   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
9413   if (!FINode)
9414     return;
9415 
9416   // Check that the fixed stack object is the right size and alignment.
9417   // Look at the alignment that the user wrote on the alloca instead of looking
9418   // at the stack object.
9419   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
9420   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
9421   const AllocaInst *AI = ArgCopyIter->second.first;
9422   int FixedIndex = FINode->getIndex();
9423   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
9424   int OldIndex = AllocaIndex;
9425   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
9426   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
9427     LLVM_DEBUG(
9428         dbgs() << "  argument copy elision failed due to bad fixed stack "
9429                   "object size\n");
9430     return;
9431   }
9432   unsigned RequiredAlignment = AI->getAlignment();
9433   if (!RequiredAlignment) {
9434     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
9435         AI->getAllocatedType());
9436   }
9437   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
9438     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
9439                          "greater than stack argument alignment ("
9440                       << RequiredAlignment << " vs "
9441                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
9442     return;
9443   }
9444 
9445   // Perform the elision. Delete the old stack object and replace its only use
9446   // in the variable info map. Mark the stack object as mutable.
9447   LLVM_DEBUG({
9448     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
9449            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
9450            << '\n';
9451   });
9452   MFI.RemoveStackObject(OldIndex);
9453   MFI.setIsImmutableObjectIndex(FixedIndex, false);
9454   AllocaIndex = FixedIndex;
9455   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
9456   Chains.push_back(ArgVal.getValue(1));
9457 
9458   // Avoid emitting code for the store implementing the copy.
9459   const StoreInst *SI = ArgCopyIter->second.second;
9460   ElidedArgCopyInstrs.insert(SI);
9461 
9462   // Check for uses of the argument again so that we can avoid exporting ArgVal
9463   // if it is't used by anything other than the store.
9464   for (const Value *U : Arg.users()) {
9465     if (U != SI) {
9466       ArgHasUses = true;
9467       break;
9468     }
9469   }
9470 }
9471 
9472 void SelectionDAGISel::LowerArguments(const Function &F) {
9473   SelectionDAG &DAG = SDB->DAG;
9474   SDLoc dl = SDB->getCurSDLoc();
9475   const DataLayout &DL = DAG.getDataLayout();
9476   SmallVector<ISD::InputArg, 16> Ins;
9477 
9478   if (!FuncInfo->CanLowerReturn) {
9479     // Put in an sret pointer parameter before all the other parameters.
9480     SmallVector<EVT, 1> ValueVTs;
9481     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9482                     F.getReturnType()->getPointerTo(
9483                         DAG.getDataLayout().getAllocaAddrSpace()),
9484                     ValueVTs);
9485 
9486     // NOTE: Assuming that a pointer will never break down to more than one VT
9487     // or one register.
9488     ISD::ArgFlagsTy Flags;
9489     Flags.setSRet();
9490     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
9491     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
9492                          ISD::InputArg::NoArgIndex, 0);
9493     Ins.push_back(RetArg);
9494   }
9495 
9496   // Look for stores of arguments to static allocas. Mark such arguments with a
9497   // flag to ask the target to give us the memory location of that argument if
9498   // available.
9499   ArgCopyElisionMapTy ArgCopyElisionCandidates;
9500   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
9501 
9502   // Set up the incoming argument description vector.
9503   for (const Argument &Arg : F.args()) {
9504     unsigned ArgNo = Arg.getArgNo();
9505     SmallVector<EVT, 4> ValueVTs;
9506     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9507     bool isArgValueUsed = !Arg.use_empty();
9508     unsigned PartBase = 0;
9509     Type *FinalType = Arg.getType();
9510     if (Arg.hasAttribute(Attribute::ByVal))
9511       FinalType = cast<PointerType>(FinalType)->getElementType();
9512     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9513         FinalType, F.getCallingConv(), F.isVarArg());
9514     for (unsigned Value = 0, NumValues = ValueVTs.size();
9515          Value != NumValues; ++Value) {
9516       EVT VT = ValueVTs[Value];
9517       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9518       ISD::ArgFlagsTy Flags;
9519 
9520       // Certain targets (such as MIPS), may have a different ABI alignment
9521       // for a type depending on the context. Give the target a chance to
9522       // specify the alignment it wants.
9523       unsigned OriginalAlignment =
9524           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9525 
9526       if (Arg.getType()->isPointerTy()) {
9527         Flags.setPointer();
9528         Flags.setPointerAddrSpace(
9529             cast<PointerType>(Arg.getType())->getAddressSpace());
9530       }
9531       if (Arg.hasAttribute(Attribute::ZExt))
9532         Flags.setZExt();
9533       if (Arg.hasAttribute(Attribute::SExt))
9534         Flags.setSExt();
9535       if (Arg.hasAttribute(Attribute::InReg)) {
9536         // If we are using vectorcall calling convention, a structure that is
9537         // passed InReg - is surely an HVA
9538         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9539             isa<StructType>(Arg.getType())) {
9540           // The first value of a structure is marked
9541           if (0 == Value)
9542             Flags.setHvaStart();
9543           Flags.setHva();
9544         }
9545         // Set InReg Flag
9546         Flags.setInReg();
9547       }
9548       if (Arg.hasAttribute(Attribute::StructRet))
9549         Flags.setSRet();
9550       if (Arg.hasAttribute(Attribute::SwiftSelf))
9551         Flags.setSwiftSelf();
9552       if (Arg.hasAttribute(Attribute::SwiftError))
9553         Flags.setSwiftError();
9554       if (Arg.hasAttribute(Attribute::ByVal))
9555         Flags.setByVal();
9556       if (Arg.hasAttribute(Attribute::InAlloca)) {
9557         Flags.setInAlloca();
9558         // Set the byval flag for CCAssignFn callbacks that don't know about
9559         // inalloca.  This way we can know how many bytes we should've allocated
9560         // and how many bytes a callee cleanup function will pop.  If we port
9561         // inalloca to more targets, we'll have to add custom inalloca handling
9562         // in the various CC lowering callbacks.
9563         Flags.setByVal();
9564       }
9565       if (F.getCallingConv() == CallingConv::X86_INTR) {
9566         // IA Interrupt passes frame (1st parameter) by value in the stack.
9567         if (ArgNo == 0)
9568           Flags.setByVal();
9569       }
9570       if (Flags.isByVal() || Flags.isInAlloca()) {
9571         PointerType *Ty = cast<PointerType>(Arg.getType());
9572         Type *ElementTy = Ty->getElementType();
9573         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9574         // For ByVal, alignment should be passed from FE.  BE will guess if
9575         // this info is not there but there are cases it cannot get right.
9576         unsigned FrameAlign;
9577         if (Arg.getParamAlignment())
9578           FrameAlign = Arg.getParamAlignment();
9579         else
9580           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9581         Flags.setByValAlign(FrameAlign);
9582       }
9583       if (Arg.hasAttribute(Attribute::Nest))
9584         Flags.setNest();
9585       if (NeedsRegBlock)
9586         Flags.setInConsecutiveRegs();
9587       Flags.setOrigAlign(OriginalAlignment);
9588       if (ArgCopyElisionCandidates.count(&Arg))
9589         Flags.setCopyElisionCandidate();
9590 
9591       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9592           *CurDAG->getContext(), F.getCallingConv(), VT);
9593       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9594           *CurDAG->getContext(), F.getCallingConv(), VT);
9595       for (unsigned i = 0; i != NumRegs; ++i) {
9596         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9597                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9598         if (NumRegs > 1 && i == 0)
9599           MyFlags.Flags.setSplit();
9600         // if it isn't first piece, alignment must be 1
9601         else if (i > 0) {
9602           MyFlags.Flags.setOrigAlign(1);
9603           if (i == NumRegs - 1)
9604             MyFlags.Flags.setSplitEnd();
9605         }
9606         Ins.push_back(MyFlags);
9607       }
9608       if (NeedsRegBlock && Value == NumValues - 1)
9609         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9610       PartBase += VT.getStoreSize();
9611     }
9612   }
9613 
9614   // Call the target to set up the argument values.
9615   SmallVector<SDValue, 8> InVals;
9616   SDValue NewRoot = TLI->LowerFormalArguments(
9617       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9618 
9619   // Verify that the target's LowerFormalArguments behaved as expected.
9620   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9621          "LowerFormalArguments didn't return a valid chain!");
9622   assert(InVals.size() == Ins.size() &&
9623          "LowerFormalArguments didn't emit the correct number of values!");
9624   LLVM_DEBUG({
9625     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9626       assert(InVals[i].getNode() &&
9627              "LowerFormalArguments emitted a null value!");
9628       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9629              "LowerFormalArguments emitted a value with the wrong type!");
9630     }
9631   });
9632 
9633   // Update the DAG with the new chain value resulting from argument lowering.
9634   DAG.setRoot(NewRoot);
9635 
9636   // Set up the argument values.
9637   unsigned i = 0;
9638   if (!FuncInfo->CanLowerReturn) {
9639     // Create a virtual register for the sret pointer, and put in a copy
9640     // from the sret argument into it.
9641     SmallVector<EVT, 1> ValueVTs;
9642     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9643                     F.getReturnType()->getPointerTo(
9644                         DAG.getDataLayout().getAllocaAddrSpace()),
9645                     ValueVTs);
9646     MVT VT = ValueVTs[0].getSimpleVT();
9647     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9648     Optional<ISD::NodeType> AssertOp = None;
9649     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9650                                         nullptr, F.getCallingConv(), AssertOp);
9651 
9652     MachineFunction& MF = SDB->DAG.getMachineFunction();
9653     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9654     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9655     FuncInfo->DemoteRegister = SRetReg;
9656     NewRoot =
9657         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9658     DAG.setRoot(NewRoot);
9659 
9660     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9661     ++i;
9662   }
9663 
9664   SmallVector<SDValue, 4> Chains;
9665   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9666   for (const Argument &Arg : F.args()) {
9667     SmallVector<SDValue, 4> ArgValues;
9668     SmallVector<EVT, 4> ValueVTs;
9669     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9670     unsigned NumValues = ValueVTs.size();
9671     if (NumValues == 0)
9672       continue;
9673 
9674     bool ArgHasUses = !Arg.use_empty();
9675 
9676     // Elide the copying store if the target loaded this argument from a
9677     // suitable fixed stack object.
9678     if (Ins[i].Flags.isCopyElisionCandidate()) {
9679       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9680                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9681                              InVals[i], ArgHasUses);
9682     }
9683 
9684     // If this argument is unused then remember its value. It is used to generate
9685     // debugging information.
9686     bool isSwiftErrorArg =
9687         TLI->supportSwiftError() &&
9688         Arg.hasAttribute(Attribute::SwiftError);
9689     if (!ArgHasUses && !isSwiftErrorArg) {
9690       SDB->setUnusedArgValue(&Arg, InVals[i]);
9691 
9692       // Also remember any frame index for use in FastISel.
9693       if (FrameIndexSDNode *FI =
9694           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9695         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9696     }
9697 
9698     for (unsigned Val = 0; Val != NumValues; ++Val) {
9699       EVT VT = ValueVTs[Val];
9700       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9701                                                       F.getCallingConv(), VT);
9702       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9703           *CurDAG->getContext(), F.getCallingConv(), VT);
9704 
9705       // Even an apparant 'unused' swifterror argument needs to be returned. So
9706       // we do generate a copy for it that can be used on return from the
9707       // function.
9708       if (ArgHasUses || isSwiftErrorArg) {
9709         Optional<ISD::NodeType> AssertOp;
9710         if (Arg.hasAttribute(Attribute::SExt))
9711           AssertOp = ISD::AssertSext;
9712         else if (Arg.hasAttribute(Attribute::ZExt))
9713           AssertOp = ISD::AssertZext;
9714 
9715         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9716                                              PartVT, VT, nullptr,
9717                                              F.getCallingConv(), AssertOp));
9718       }
9719 
9720       i += NumParts;
9721     }
9722 
9723     // We don't need to do anything else for unused arguments.
9724     if (ArgValues.empty())
9725       continue;
9726 
9727     // Note down frame index.
9728     if (FrameIndexSDNode *FI =
9729         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9730       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9731 
9732     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9733                                      SDB->getCurSDLoc());
9734 
9735     SDB->setValue(&Arg, Res);
9736     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9737       // We want to associate the argument with the frame index, among
9738       // involved operands, that correspond to the lowest address. The
9739       // getCopyFromParts function, called earlier, is swapping the order of
9740       // the operands to BUILD_PAIR depending on endianness. The result of
9741       // that swapping is that the least significant bits of the argument will
9742       // be in the first operand of the BUILD_PAIR node, and the most
9743       // significant bits will be in the second operand.
9744       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9745       if (LoadSDNode *LNode =
9746           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9747         if (FrameIndexSDNode *FI =
9748             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9749           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9750     }
9751 
9752     // Update the SwiftErrorVRegDefMap.
9753     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9754       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9755       if (TargetRegisterInfo::isVirtualRegister(Reg))
9756         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
9757                                    Reg);
9758     }
9759 
9760     // If this argument is live outside of the entry block, insert a copy from
9761     // wherever we got it to the vreg that other BB's will reference it as.
9762     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9763       // If we can, though, try to skip creating an unnecessary vreg.
9764       // FIXME: This isn't very clean... it would be nice to make this more
9765       // general.  It's also subtly incompatible with the hacks FastISel
9766       // uses with vregs.
9767       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9768       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9769         FuncInfo->ValueMap[&Arg] = Reg;
9770         continue;
9771       }
9772     }
9773     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9774       FuncInfo->InitializeRegForValue(&Arg);
9775       SDB->CopyToExportRegsIfNeeded(&Arg);
9776     }
9777   }
9778 
9779   if (!Chains.empty()) {
9780     Chains.push_back(NewRoot);
9781     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9782   }
9783 
9784   DAG.setRoot(NewRoot);
9785 
9786   assert(i == InVals.size() && "Argument register count mismatch!");
9787 
9788   // If any argument copy elisions occurred and we have debug info, update the
9789   // stale frame indices used in the dbg.declare variable info table.
9790   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9791   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9792     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9793       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9794       if (I != ArgCopyElisionFrameIndexMap.end())
9795         VI.Slot = I->second;
9796     }
9797   }
9798 
9799   // Finally, if the target has anything special to do, allow it to do so.
9800   EmitFunctionEntryCode();
9801 }
9802 
9803 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9804 /// ensure constants are generated when needed.  Remember the virtual registers
9805 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9806 /// directly add them, because expansion might result in multiple MBB's for one
9807 /// BB.  As such, the start of the BB might correspond to a different MBB than
9808 /// the end.
9809 void
9810 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9811   const Instruction *TI = LLVMBB->getTerminator();
9812 
9813   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9814 
9815   // Check PHI nodes in successors that expect a value to be available from this
9816   // block.
9817   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9818     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9819     if (!isa<PHINode>(SuccBB->begin())) continue;
9820     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9821 
9822     // If this terminator has multiple identical successors (common for
9823     // switches), only handle each succ once.
9824     if (!SuccsHandled.insert(SuccMBB).second)
9825       continue;
9826 
9827     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9828 
9829     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9830     // nodes and Machine PHI nodes, but the incoming operands have not been
9831     // emitted yet.
9832     for (const PHINode &PN : SuccBB->phis()) {
9833       // Ignore dead phi's.
9834       if (PN.use_empty())
9835         continue;
9836 
9837       // Skip empty types
9838       if (PN.getType()->isEmptyTy())
9839         continue;
9840 
9841       unsigned Reg;
9842       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9843 
9844       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9845         unsigned &RegOut = ConstantsOut[C];
9846         if (RegOut == 0) {
9847           RegOut = FuncInfo.CreateRegs(C);
9848           CopyValueToVirtualRegister(C, RegOut);
9849         }
9850         Reg = RegOut;
9851       } else {
9852         DenseMap<const Value *, unsigned>::iterator I =
9853           FuncInfo.ValueMap.find(PHIOp);
9854         if (I != FuncInfo.ValueMap.end())
9855           Reg = I->second;
9856         else {
9857           assert(isa<AllocaInst>(PHIOp) &&
9858                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9859                  "Didn't codegen value into a register!??");
9860           Reg = FuncInfo.CreateRegs(PHIOp);
9861           CopyValueToVirtualRegister(PHIOp, Reg);
9862         }
9863       }
9864 
9865       // Remember that this register needs to added to the machine PHI node as
9866       // the input for this MBB.
9867       SmallVector<EVT, 4> ValueVTs;
9868       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9869       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9870       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9871         EVT VT = ValueVTs[vti];
9872         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9873         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9874           FuncInfo.PHINodesToUpdate.push_back(
9875               std::make_pair(&*MBBI++, Reg + i));
9876         Reg += NumRegisters;
9877       }
9878     }
9879   }
9880 
9881   ConstantsOut.clear();
9882 }
9883 
9884 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9885 /// is 0.
9886 MachineBasicBlock *
9887 SelectionDAGBuilder::StackProtectorDescriptor::
9888 AddSuccessorMBB(const BasicBlock *BB,
9889                 MachineBasicBlock *ParentMBB,
9890                 bool IsLikely,
9891                 MachineBasicBlock *SuccMBB) {
9892   // If SuccBB has not been created yet, create it.
9893   if (!SuccMBB) {
9894     MachineFunction *MF = ParentMBB->getParent();
9895     MachineFunction::iterator BBI(ParentMBB);
9896     SuccMBB = MF->CreateMachineBasicBlock(BB);
9897     MF->insert(++BBI, SuccMBB);
9898   }
9899   // Add it as a successor of ParentMBB.
9900   ParentMBB->addSuccessor(
9901       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9902   return SuccMBB;
9903 }
9904 
9905 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9906   MachineFunction::iterator I(MBB);
9907   if (++I == FuncInfo.MF->end())
9908     return nullptr;
9909   return &*I;
9910 }
9911 
9912 /// During lowering new call nodes can be created (such as memset, etc.).
9913 /// Those will become new roots of the current DAG, but complications arise
9914 /// when they are tail calls. In such cases, the call lowering will update
9915 /// the root, but the builder still needs to know that a tail call has been
9916 /// lowered in order to avoid generating an additional return.
9917 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9918   // If the node is null, we do have a tail call.
9919   if (MaybeTC.getNode() != nullptr)
9920     DAG.setRoot(MaybeTC);
9921   else
9922     HasTailCall = true;
9923 }
9924 
9925 uint64_t
9926 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9927                                        unsigned First, unsigned Last) const {
9928   assert(Last >= First);
9929   const APInt &LowCase = Clusters[First].Low->getValue();
9930   const APInt &HighCase = Clusters[Last].High->getValue();
9931   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9932 
9933   // FIXME: A range of consecutive cases has 100% density, but only requires one
9934   // comparison to lower. We should discriminate against such consecutive ranges
9935   // in jump tables.
9936 
9937   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9938 }
9939 
9940 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9941     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9942     unsigned Last) const {
9943   assert(Last >= First);
9944   assert(TotalCases[Last] >= TotalCases[First]);
9945   uint64_t NumCases =
9946       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9947   return NumCases;
9948 }
9949 
9950 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9951                                          unsigned First, unsigned Last,
9952                                          const SwitchInst *SI,
9953                                          MachineBasicBlock *DefaultMBB,
9954                                          CaseCluster &JTCluster) {
9955   assert(First <= Last);
9956 
9957   auto Prob = BranchProbability::getZero();
9958   unsigned NumCmps = 0;
9959   std::vector<MachineBasicBlock*> Table;
9960   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9961 
9962   // Initialize probabilities in JTProbs.
9963   for (unsigned I = First; I <= Last; ++I)
9964     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9965 
9966   for (unsigned I = First; I <= Last; ++I) {
9967     assert(Clusters[I].Kind == CC_Range);
9968     Prob += Clusters[I].Prob;
9969     const APInt &Low = Clusters[I].Low->getValue();
9970     const APInt &High = Clusters[I].High->getValue();
9971     NumCmps += (Low == High) ? 1 : 2;
9972     if (I != First) {
9973       // Fill the gap between this and the previous cluster.
9974       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9975       assert(PreviousHigh.slt(Low));
9976       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9977       for (uint64_t J = 0; J < Gap; J++)
9978         Table.push_back(DefaultMBB);
9979     }
9980     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9981     for (uint64_t J = 0; J < ClusterSize; ++J)
9982       Table.push_back(Clusters[I].MBB);
9983     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9984   }
9985 
9986   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9987   unsigned NumDests = JTProbs.size();
9988   if (TLI.isSuitableForBitTests(
9989           NumDests, NumCmps, Clusters[First].Low->getValue(),
9990           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9991     // Clusters[First..Last] should be lowered as bit tests instead.
9992     return false;
9993   }
9994 
9995   // Create the MBB that will load from and jump through the table.
9996   // Note: We create it here, but it's not inserted into the function yet.
9997   MachineFunction *CurMF = FuncInfo.MF;
9998   MachineBasicBlock *JumpTableMBB =
9999       CurMF->CreateMachineBasicBlock(SI->getParent());
10000 
10001   // Add successors. Note: use table order for determinism.
10002   SmallPtrSet<MachineBasicBlock *, 8> Done;
10003   for (MachineBasicBlock *Succ : Table) {
10004     if (Done.count(Succ))
10005       continue;
10006     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
10007     Done.insert(Succ);
10008   }
10009   JumpTableMBB->normalizeSuccProbs();
10010 
10011   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
10012                      ->createJumpTableIndex(Table);
10013 
10014   // Set up the jump table info.
10015   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
10016   JumpTableHeader JTH(Clusters[First].Low->getValue(),
10017                       Clusters[Last].High->getValue(), SI->getCondition(),
10018                       nullptr, false);
10019   JTCases.emplace_back(std::move(JTH), std::move(JT));
10020 
10021   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
10022                                      JTCases.size() - 1, Prob);
10023   return true;
10024 }
10025 
10026 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
10027                                          const SwitchInst *SI,
10028                                          MachineBasicBlock *DefaultMBB) {
10029 #ifndef NDEBUG
10030   // Clusters must be non-empty, sorted, and only contain Range clusters.
10031   assert(!Clusters.empty());
10032   for (CaseCluster &C : Clusters)
10033     assert(C.Kind == CC_Range);
10034   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
10035     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
10036 #endif
10037 
10038   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10039   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
10040     return;
10041 
10042   const int64_t N = Clusters.size();
10043   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
10044   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
10045 
10046   if (N < 2 || N < MinJumpTableEntries)
10047     return;
10048 
10049   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
10050   SmallVector<unsigned, 8> TotalCases(N);
10051   for (unsigned i = 0; i < N; ++i) {
10052     const APInt &Hi = Clusters[i].High->getValue();
10053     const APInt &Lo = Clusters[i].Low->getValue();
10054     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
10055     if (i != 0)
10056       TotalCases[i] += TotalCases[i - 1];
10057   }
10058 
10059   // Cheap case: the whole range may be suitable for jump table.
10060   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
10061   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
10062   assert(NumCases < UINT64_MAX / 100);
10063   assert(Range >= NumCases);
10064   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
10065     CaseCluster JTCluster;
10066     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
10067       Clusters[0] = JTCluster;
10068       Clusters.resize(1);
10069       return;
10070     }
10071   }
10072 
10073   // The algorithm below is not suitable for -O0.
10074   if (TM.getOptLevel() == CodeGenOpt::None)
10075     return;
10076 
10077   // Split Clusters into minimum number of dense partitions. The algorithm uses
10078   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
10079   // for the Case Statement'" (1994), but builds the MinPartitions array in
10080   // reverse order to make it easier to reconstruct the partitions in ascending
10081   // order. In the choice between two optimal partitionings, it picks the one
10082   // which yields more jump tables.
10083 
10084   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
10085   SmallVector<unsigned, 8> MinPartitions(N);
10086   // LastElement[i] is the last element of the partition starting at i.
10087   SmallVector<unsigned, 8> LastElement(N);
10088   // PartitionsScore[i] is used to break ties when choosing between two
10089   // partitionings resulting in the same number of partitions.
10090   SmallVector<unsigned, 8> PartitionsScore(N);
10091   // For PartitionsScore, a small number of comparisons is considered as good as
10092   // a jump table and a single comparison is considered better than a jump
10093   // table.
10094   enum PartitionScores : unsigned {
10095     NoTable = 0,
10096     Table = 1,
10097     FewCases = 1,
10098     SingleCase = 2
10099   };
10100 
10101   // Base case: There is only one way to partition Clusters[N-1].
10102   MinPartitions[N - 1] = 1;
10103   LastElement[N - 1] = N - 1;
10104   PartitionsScore[N - 1] = PartitionScores::SingleCase;
10105 
10106   // Note: loop indexes are signed to avoid underflow.
10107   for (int64_t i = N - 2; i >= 0; i--) {
10108     // Find optimal partitioning of Clusters[i..N-1].
10109     // Baseline: Put Clusters[i] into a partition on its own.
10110     MinPartitions[i] = MinPartitions[i + 1] + 1;
10111     LastElement[i] = i;
10112     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
10113 
10114     // Search for a solution that results in fewer partitions.
10115     for (int64_t j = N - 1; j > i; j--) {
10116       // Try building a partition from Clusters[i..j].
10117       uint64_t Range = getJumpTableRange(Clusters, i, j);
10118       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
10119       assert(NumCases < UINT64_MAX / 100);
10120       assert(Range >= NumCases);
10121       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
10122         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
10123         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
10124         int64_t NumEntries = j - i + 1;
10125 
10126         if (NumEntries == 1)
10127           Score += PartitionScores::SingleCase;
10128         else if (NumEntries <= SmallNumberOfEntries)
10129           Score += PartitionScores::FewCases;
10130         else if (NumEntries >= MinJumpTableEntries)
10131           Score += PartitionScores::Table;
10132 
10133         // If this leads to fewer partitions, or to the same number of
10134         // partitions with better score, it is a better partitioning.
10135         if (NumPartitions < MinPartitions[i] ||
10136             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
10137           MinPartitions[i] = NumPartitions;
10138           LastElement[i] = j;
10139           PartitionsScore[i] = Score;
10140         }
10141       }
10142     }
10143   }
10144 
10145   // Iterate over the partitions, replacing some with jump tables in-place.
10146   unsigned DstIndex = 0;
10147   for (unsigned First = 0, Last; First < N; First = Last + 1) {
10148     Last = LastElement[First];
10149     assert(Last >= First);
10150     assert(DstIndex <= First);
10151     unsigned NumClusters = Last - First + 1;
10152 
10153     CaseCluster JTCluster;
10154     if (NumClusters >= MinJumpTableEntries &&
10155         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
10156       Clusters[DstIndex++] = JTCluster;
10157     } else {
10158       for (unsigned I = First; I <= Last; ++I)
10159         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
10160     }
10161   }
10162   Clusters.resize(DstIndex);
10163 }
10164 
10165 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
10166                                         unsigned First, unsigned Last,
10167                                         const SwitchInst *SI,
10168                                         CaseCluster &BTCluster) {
10169   assert(First <= Last);
10170   if (First == Last)
10171     return false;
10172 
10173   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
10174   unsigned NumCmps = 0;
10175   for (int64_t I = First; I <= Last; ++I) {
10176     assert(Clusters[I].Kind == CC_Range);
10177     Dests.set(Clusters[I].MBB->getNumber());
10178     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
10179   }
10180   unsigned NumDests = Dests.count();
10181 
10182   APInt Low = Clusters[First].Low->getValue();
10183   APInt High = Clusters[Last].High->getValue();
10184   assert(Low.slt(High));
10185 
10186   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10187   const DataLayout &DL = DAG.getDataLayout();
10188   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
10189     return false;
10190 
10191   APInt LowBound;
10192   APInt CmpRange;
10193 
10194   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
10195   assert(TLI.rangeFitsInWord(Low, High, DL) &&
10196          "Case range must fit in bit mask!");
10197 
10198   // Check if the clusters cover a contiguous range such that no value in the
10199   // range will jump to the default statement.
10200   bool ContiguousRange = true;
10201   for (int64_t I = First + 1; I <= Last; ++I) {
10202     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
10203       ContiguousRange = false;
10204       break;
10205     }
10206   }
10207 
10208   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
10209     // Optimize the case where all the case values fit in a word without having
10210     // to subtract minValue. In this case, we can optimize away the subtraction.
10211     LowBound = APInt::getNullValue(Low.getBitWidth());
10212     CmpRange = High;
10213     ContiguousRange = false;
10214   } else {
10215     LowBound = Low;
10216     CmpRange = High - Low;
10217   }
10218 
10219   CaseBitsVector CBV;
10220   auto TotalProb = BranchProbability::getZero();
10221   for (unsigned i = First; i <= Last; ++i) {
10222     // Find the CaseBits for this destination.
10223     unsigned j;
10224     for (j = 0; j < CBV.size(); ++j)
10225       if (CBV[j].BB == Clusters[i].MBB)
10226         break;
10227     if (j == CBV.size())
10228       CBV.push_back(
10229           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
10230     CaseBits *CB = &CBV[j];
10231 
10232     // Update Mask, Bits and ExtraProb.
10233     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
10234     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
10235     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
10236     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
10237     CB->Bits += Hi - Lo + 1;
10238     CB->ExtraProb += Clusters[i].Prob;
10239     TotalProb += Clusters[i].Prob;
10240   }
10241 
10242   BitTestInfo BTI;
10243   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
10244     // Sort by probability first, number of bits second, bit mask third.
10245     if (a.ExtraProb != b.ExtraProb)
10246       return a.ExtraProb > b.ExtraProb;
10247     if (a.Bits != b.Bits)
10248       return a.Bits > b.Bits;
10249     return a.Mask < b.Mask;
10250   });
10251 
10252   for (auto &CB : CBV) {
10253     MachineBasicBlock *BitTestBB =
10254         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
10255     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
10256   }
10257   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
10258                             SI->getCondition(), -1U, MVT::Other, false,
10259                             ContiguousRange, nullptr, nullptr, std::move(BTI),
10260                             TotalProb);
10261 
10262   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
10263                                     BitTestCases.size() - 1, TotalProb);
10264   return true;
10265 }
10266 
10267 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
10268                                               const SwitchInst *SI) {
10269 // Partition Clusters into as few subsets as possible, where each subset has a
10270 // range that fits in a machine word and has <= 3 unique destinations.
10271 
10272 #ifndef NDEBUG
10273   // Clusters must be sorted and contain Range or JumpTable clusters.
10274   assert(!Clusters.empty());
10275   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
10276   for (const CaseCluster &C : Clusters)
10277     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
10278   for (unsigned i = 1; i < Clusters.size(); ++i)
10279     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
10280 #endif
10281 
10282   // The algorithm below is not suitable for -O0.
10283   if (TM.getOptLevel() == CodeGenOpt::None)
10284     return;
10285 
10286   // If target does not have legal shift left, do not emit bit tests at all.
10287   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10288   const DataLayout &DL = DAG.getDataLayout();
10289 
10290   EVT PTy = TLI.getPointerTy(DL);
10291   if (!TLI.isOperationLegal(ISD::SHL, PTy))
10292     return;
10293 
10294   int BitWidth = PTy.getSizeInBits();
10295   const int64_t N = Clusters.size();
10296 
10297   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
10298   SmallVector<unsigned, 8> MinPartitions(N);
10299   // LastElement[i] is the last element of the partition starting at i.
10300   SmallVector<unsigned, 8> LastElement(N);
10301 
10302   // FIXME: This might not be the best algorithm for finding bit test clusters.
10303 
10304   // Base case: There is only one way to partition Clusters[N-1].
10305   MinPartitions[N - 1] = 1;
10306   LastElement[N - 1] = N - 1;
10307 
10308   // Note: loop indexes are signed to avoid underflow.
10309   for (int64_t i = N - 2; i >= 0; --i) {
10310     // Find optimal partitioning of Clusters[i..N-1].
10311     // Baseline: Put Clusters[i] into a partition on its own.
10312     MinPartitions[i] = MinPartitions[i + 1] + 1;
10313     LastElement[i] = i;
10314 
10315     // Search for a solution that results in fewer partitions.
10316     // Note: the search is limited by BitWidth, reducing time complexity.
10317     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
10318       // Try building a partition from Clusters[i..j].
10319 
10320       // Check the range.
10321       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
10322                                Clusters[j].High->getValue(), DL))
10323         continue;
10324 
10325       // Check nbr of destinations and cluster types.
10326       // FIXME: This works, but doesn't seem very efficient.
10327       bool RangesOnly = true;
10328       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
10329       for (int64_t k = i; k <= j; k++) {
10330         if (Clusters[k].Kind != CC_Range) {
10331           RangesOnly = false;
10332           break;
10333         }
10334         Dests.set(Clusters[k].MBB->getNumber());
10335       }
10336       if (!RangesOnly || Dests.count() > 3)
10337         break;
10338 
10339       // Check if it's a better partition.
10340       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
10341       if (NumPartitions < MinPartitions[i]) {
10342         // Found a better partition.
10343         MinPartitions[i] = NumPartitions;
10344         LastElement[i] = j;
10345       }
10346     }
10347   }
10348 
10349   // Iterate over the partitions, replacing with bit-test clusters in-place.
10350   unsigned DstIndex = 0;
10351   for (unsigned First = 0, Last; First < N; First = Last + 1) {
10352     Last = LastElement[First];
10353     assert(First <= Last);
10354     assert(DstIndex <= First);
10355 
10356     CaseCluster BitTestCluster;
10357     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
10358       Clusters[DstIndex++] = BitTestCluster;
10359     } else {
10360       size_t NumClusters = Last - First + 1;
10361       std::memmove(&Clusters[DstIndex], &Clusters[First],
10362                    sizeof(Clusters[0]) * NumClusters);
10363       DstIndex += NumClusters;
10364     }
10365   }
10366   Clusters.resize(DstIndex);
10367 }
10368 
10369 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
10370                                         MachineBasicBlock *SwitchMBB,
10371                                         MachineBasicBlock *DefaultMBB) {
10372   MachineFunction *CurMF = FuncInfo.MF;
10373   MachineBasicBlock *NextMBB = nullptr;
10374   MachineFunction::iterator BBI(W.MBB);
10375   if (++BBI != FuncInfo.MF->end())
10376     NextMBB = &*BBI;
10377 
10378   unsigned Size = W.LastCluster - W.FirstCluster + 1;
10379 
10380   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10381 
10382   if (Size == 2 && W.MBB == SwitchMBB) {
10383     // If any two of the cases has the same destination, and if one value
10384     // is the same as the other, but has one bit unset that the other has set,
10385     // use bit manipulation to do two compares at once.  For example:
10386     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
10387     // TODO: This could be extended to merge any 2 cases in switches with 3
10388     // cases.
10389     // TODO: Handle cases where W.CaseBB != SwitchBB.
10390     CaseCluster &Small = *W.FirstCluster;
10391     CaseCluster &Big = *W.LastCluster;
10392 
10393     if (Small.Low == Small.High && Big.Low == Big.High &&
10394         Small.MBB == Big.MBB) {
10395       const APInt &SmallValue = Small.Low->getValue();
10396       const APInt &BigValue = Big.Low->getValue();
10397 
10398       // Check that there is only one bit different.
10399       APInt CommonBit = BigValue ^ SmallValue;
10400       if (CommonBit.isPowerOf2()) {
10401         SDValue CondLHS = getValue(Cond);
10402         EVT VT = CondLHS.getValueType();
10403         SDLoc DL = getCurSDLoc();
10404 
10405         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
10406                                  DAG.getConstant(CommonBit, DL, VT));
10407         SDValue Cond = DAG.getSetCC(
10408             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
10409             ISD::SETEQ);
10410 
10411         // Update successor info.
10412         // Both Small and Big will jump to Small.BB, so we sum up the
10413         // probabilities.
10414         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
10415         if (BPI)
10416           addSuccessorWithProb(
10417               SwitchMBB, DefaultMBB,
10418               // The default destination is the first successor in IR.
10419               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
10420         else
10421           addSuccessorWithProb(SwitchMBB, DefaultMBB);
10422 
10423         // Insert the true branch.
10424         SDValue BrCond =
10425             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
10426                         DAG.getBasicBlock(Small.MBB));
10427         // Insert the false branch.
10428         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
10429                              DAG.getBasicBlock(DefaultMBB));
10430 
10431         DAG.setRoot(BrCond);
10432         return;
10433       }
10434     }
10435   }
10436 
10437   if (TM.getOptLevel() != CodeGenOpt::None) {
10438     // Here, we order cases by probability so the most likely case will be
10439     // checked first. However, two clusters can have the same probability in
10440     // which case their relative ordering is non-deterministic. So we use Low
10441     // as a tie-breaker as clusters are guaranteed to never overlap.
10442     llvm::sort(W.FirstCluster, W.LastCluster + 1,
10443                [](const CaseCluster &a, const CaseCluster &b) {
10444       return a.Prob != b.Prob ?
10445              a.Prob > b.Prob :
10446              a.Low->getValue().slt(b.Low->getValue());
10447     });
10448 
10449     // Rearrange the case blocks so that the last one falls through if possible
10450     // without changing the order of probabilities.
10451     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
10452       --I;
10453       if (I->Prob > W.LastCluster->Prob)
10454         break;
10455       if (I->Kind == CC_Range && I->MBB == NextMBB) {
10456         std::swap(*I, *W.LastCluster);
10457         break;
10458       }
10459     }
10460   }
10461 
10462   // Compute total probability.
10463   BranchProbability DefaultProb = W.DefaultProb;
10464   BranchProbability UnhandledProbs = DefaultProb;
10465   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
10466     UnhandledProbs += I->Prob;
10467 
10468   MachineBasicBlock *CurMBB = W.MBB;
10469   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
10470     bool FallthroughUnreachable = false;
10471     MachineBasicBlock *Fallthrough;
10472     if (I == W.LastCluster) {
10473       // For the last cluster, fall through to the default destination.
10474       Fallthrough = DefaultMBB;
10475       FallthroughUnreachable = isa<UnreachableInst>(
10476           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
10477     } else {
10478       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
10479       CurMF->insert(BBI, Fallthrough);
10480       // Put Cond in a virtual register to make it available from the new blocks.
10481       ExportFromCurrentBlock(Cond);
10482     }
10483     UnhandledProbs -= I->Prob;
10484 
10485     switch (I->Kind) {
10486       case CC_JumpTable: {
10487         // FIXME: Optimize away range check based on pivot comparisons.
10488         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
10489         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
10490 
10491         // The jump block hasn't been inserted yet; insert it here.
10492         MachineBasicBlock *JumpMBB = JT->MBB;
10493         CurMF->insert(BBI, JumpMBB);
10494 
10495         auto JumpProb = I->Prob;
10496         auto FallthroughProb = UnhandledProbs;
10497 
10498         // If the default statement is a target of the jump table, we evenly
10499         // distribute the default probability to successors of CurMBB. Also
10500         // update the probability on the edge from JumpMBB to Fallthrough.
10501         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
10502                                               SE = JumpMBB->succ_end();
10503              SI != SE; ++SI) {
10504           if (*SI == DefaultMBB) {
10505             JumpProb += DefaultProb / 2;
10506             FallthroughProb -= DefaultProb / 2;
10507             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
10508             JumpMBB->normalizeSuccProbs();
10509             break;
10510           }
10511         }
10512 
10513         if (FallthroughUnreachable) {
10514           // Skip the range check if the fallthrough block is unreachable.
10515           JTH->OmitRangeCheck = true;
10516         }
10517 
10518         if (!JTH->OmitRangeCheck)
10519           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10520         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10521         CurMBB->normalizeSuccProbs();
10522 
10523         // The jump table header will be inserted in our current block, do the
10524         // range check, and fall through to our fallthrough block.
10525         JTH->HeaderBB = CurMBB;
10526         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10527 
10528         // If we're in the right place, emit the jump table header right now.
10529         if (CurMBB == SwitchMBB) {
10530           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10531           JTH->Emitted = true;
10532         }
10533         break;
10534       }
10535       case CC_BitTests: {
10536         // FIXME: If Fallthrough is unreachable, skip the range check.
10537 
10538         // FIXME: Optimize away range check based on pivot comparisons.
10539         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10540 
10541         // The bit test blocks haven't been inserted yet; insert them here.
10542         for (BitTestCase &BTC : BTB->Cases)
10543           CurMF->insert(BBI, BTC.ThisBB);
10544 
10545         // Fill in fields of the BitTestBlock.
10546         BTB->Parent = CurMBB;
10547         BTB->Default = Fallthrough;
10548 
10549         BTB->DefaultProb = UnhandledProbs;
10550         // If the cases in bit test don't form a contiguous range, we evenly
10551         // distribute the probability on the edge to Fallthrough to two
10552         // successors of CurMBB.
10553         if (!BTB->ContiguousRange) {
10554           BTB->Prob += DefaultProb / 2;
10555           BTB->DefaultProb -= DefaultProb / 2;
10556         }
10557 
10558         // If we're in the right place, emit the bit test header right now.
10559         if (CurMBB == SwitchMBB) {
10560           visitBitTestHeader(*BTB, SwitchMBB);
10561           BTB->Emitted = true;
10562         }
10563         break;
10564       }
10565       case CC_Range: {
10566         const Value *RHS, *LHS, *MHS;
10567         ISD::CondCode CC;
10568         if (I->Low == I->High) {
10569           // Check Cond == I->Low.
10570           CC = ISD::SETEQ;
10571           LHS = Cond;
10572           RHS=I->Low;
10573           MHS = nullptr;
10574         } else {
10575           // Check I->Low <= Cond <= I->High.
10576           CC = ISD::SETLE;
10577           LHS = I->Low;
10578           MHS = Cond;
10579           RHS = I->High;
10580         }
10581 
10582         // If Fallthrough is unreachable, fold away the comparison.
10583         if (FallthroughUnreachable)
10584           CC = ISD::SETTRUE;
10585 
10586         // The false probability is the sum of all unhandled cases.
10587         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10588                      getCurSDLoc(), I->Prob, UnhandledProbs);
10589 
10590         if (CurMBB == SwitchMBB)
10591           visitSwitchCase(CB, SwitchMBB);
10592         else
10593           SwitchCases.push_back(CB);
10594 
10595         break;
10596       }
10597     }
10598     CurMBB = Fallthrough;
10599   }
10600 }
10601 
10602 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10603                                               CaseClusterIt First,
10604                                               CaseClusterIt Last) {
10605   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10606     if (X.Prob != CC.Prob)
10607       return X.Prob > CC.Prob;
10608 
10609     // Ties are broken by comparing the case value.
10610     return X.Low->getValue().slt(CC.Low->getValue());
10611   });
10612 }
10613 
10614 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10615                                         const SwitchWorkListItem &W,
10616                                         Value *Cond,
10617                                         MachineBasicBlock *SwitchMBB) {
10618   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10619          "Clusters not sorted?");
10620 
10621   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10622 
10623   // Balance the tree based on branch probabilities to create a near-optimal (in
10624   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10625   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10626   CaseClusterIt LastLeft = W.FirstCluster;
10627   CaseClusterIt FirstRight = W.LastCluster;
10628   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10629   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10630 
10631   // Move LastLeft and FirstRight towards each other from opposite directions to
10632   // find a partitioning of the clusters which balances the probability on both
10633   // sides. If LeftProb and RightProb are equal, alternate which side is
10634   // taken to ensure 0-probability nodes are distributed evenly.
10635   unsigned I = 0;
10636   while (LastLeft + 1 < FirstRight) {
10637     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10638       LeftProb += (++LastLeft)->Prob;
10639     else
10640       RightProb += (--FirstRight)->Prob;
10641     I++;
10642   }
10643 
10644   while (true) {
10645     // Our binary search tree differs from a typical BST in that ours can have up
10646     // to three values in each leaf. The pivot selection above doesn't take that
10647     // into account, which means the tree might require more nodes and be less
10648     // efficient. We compensate for this here.
10649 
10650     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10651     unsigned NumRight = W.LastCluster - FirstRight + 1;
10652 
10653     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10654       // If one side has less than 3 clusters, and the other has more than 3,
10655       // consider taking a cluster from the other side.
10656 
10657       if (NumLeft < NumRight) {
10658         // Consider moving the first cluster on the right to the left side.
10659         CaseCluster &CC = *FirstRight;
10660         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10661         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10662         if (LeftSideRank <= RightSideRank) {
10663           // Moving the cluster to the left does not demote it.
10664           ++LastLeft;
10665           ++FirstRight;
10666           continue;
10667         }
10668       } else {
10669         assert(NumRight < NumLeft);
10670         // Consider moving the last element on the left to the right side.
10671         CaseCluster &CC = *LastLeft;
10672         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10673         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10674         if (RightSideRank <= LeftSideRank) {
10675           // Moving the cluster to the right does not demot it.
10676           --LastLeft;
10677           --FirstRight;
10678           continue;
10679         }
10680       }
10681     }
10682     break;
10683   }
10684 
10685   assert(LastLeft + 1 == FirstRight);
10686   assert(LastLeft >= W.FirstCluster);
10687   assert(FirstRight <= W.LastCluster);
10688 
10689   // Use the first element on the right as pivot since we will make less-than
10690   // comparisons against it.
10691   CaseClusterIt PivotCluster = FirstRight;
10692   assert(PivotCluster > W.FirstCluster);
10693   assert(PivotCluster <= W.LastCluster);
10694 
10695   CaseClusterIt FirstLeft = W.FirstCluster;
10696   CaseClusterIt LastRight = W.LastCluster;
10697 
10698   const ConstantInt *Pivot = PivotCluster->Low;
10699 
10700   // New blocks will be inserted immediately after the current one.
10701   MachineFunction::iterator BBI(W.MBB);
10702   ++BBI;
10703 
10704   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10705   // we can branch to its destination directly if it's squeezed exactly in
10706   // between the known lower bound and Pivot - 1.
10707   MachineBasicBlock *LeftMBB;
10708   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10709       FirstLeft->Low == W.GE &&
10710       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10711     LeftMBB = FirstLeft->MBB;
10712   } else {
10713     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10714     FuncInfo.MF->insert(BBI, LeftMBB);
10715     WorkList.push_back(
10716         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10717     // Put Cond in a virtual register to make it available from the new blocks.
10718     ExportFromCurrentBlock(Cond);
10719   }
10720 
10721   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10722   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10723   // directly if RHS.High equals the current upper bound.
10724   MachineBasicBlock *RightMBB;
10725   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10726       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10727     RightMBB = FirstRight->MBB;
10728   } else {
10729     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10730     FuncInfo.MF->insert(BBI, RightMBB);
10731     WorkList.push_back(
10732         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10733     // Put Cond in a virtual register to make it available from the new blocks.
10734     ExportFromCurrentBlock(Cond);
10735   }
10736 
10737   // Create the CaseBlock record that will be used to lower the branch.
10738   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10739                getCurSDLoc(), LeftProb, RightProb);
10740 
10741   if (W.MBB == SwitchMBB)
10742     visitSwitchCase(CB, SwitchMBB);
10743   else
10744     SwitchCases.push_back(CB);
10745 }
10746 
10747 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10748 // from the swith statement.
10749 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10750                                             BranchProbability PeeledCaseProb) {
10751   if (PeeledCaseProb == BranchProbability::getOne())
10752     return BranchProbability::getZero();
10753   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10754 
10755   uint32_t Numerator = CaseProb.getNumerator();
10756   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10757   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10758 }
10759 
10760 // Try to peel the top probability case if it exceeds the threshold.
10761 // Return current MachineBasicBlock for the switch statement if the peeling
10762 // does not occur.
10763 // If the peeling is performed, return the newly created MachineBasicBlock
10764 // for the peeled switch statement. Also update Clusters to remove the peeled
10765 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10766 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10767     const SwitchInst &SI, CaseClusterVector &Clusters,
10768     BranchProbability &PeeledCaseProb) {
10769   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10770   // Don't perform if there is only one cluster or optimizing for size.
10771   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10772       TM.getOptLevel() == CodeGenOpt::None ||
10773       SwitchMBB->getParent()->getFunction().hasMinSize())
10774     return SwitchMBB;
10775 
10776   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10777   unsigned PeeledCaseIndex = 0;
10778   bool SwitchPeeled = false;
10779   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10780     CaseCluster &CC = Clusters[Index];
10781     if (CC.Prob < TopCaseProb)
10782       continue;
10783     TopCaseProb = CC.Prob;
10784     PeeledCaseIndex = Index;
10785     SwitchPeeled = true;
10786   }
10787   if (!SwitchPeeled)
10788     return SwitchMBB;
10789 
10790   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10791                     << TopCaseProb << "\n");
10792 
10793   // Record the MBB for the peeled switch statement.
10794   MachineFunction::iterator BBI(SwitchMBB);
10795   ++BBI;
10796   MachineBasicBlock *PeeledSwitchMBB =
10797       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10798   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10799 
10800   ExportFromCurrentBlock(SI.getCondition());
10801   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10802   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10803                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10804   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10805 
10806   Clusters.erase(PeeledCaseIt);
10807   for (CaseCluster &CC : Clusters) {
10808     LLVM_DEBUG(
10809         dbgs() << "Scale the probablity for one cluster, before scaling: "
10810                << CC.Prob << "\n");
10811     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10812     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10813   }
10814   PeeledCaseProb = TopCaseProb;
10815   return PeeledSwitchMBB;
10816 }
10817 
10818 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10819   // Extract cases from the switch.
10820   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10821   CaseClusterVector Clusters;
10822   Clusters.reserve(SI.getNumCases());
10823   for (auto I : SI.cases()) {
10824     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10825     const ConstantInt *CaseVal = I.getCaseValue();
10826     BranchProbability Prob =
10827         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10828             : BranchProbability(1, SI.getNumCases() + 1);
10829     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10830   }
10831 
10832   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10833 
10834   // Cluster adjacent cases with the same destination. We do this at all
10835   // optimization levels because it's cheap to do and will make codegen faster
10836   // if there are many clusters.
10837   sortAndRangeify(Clusters);
10838 
10839   // The branch probablity of the peeled case.
10840   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10841   MachineBasicBlock *PeeledSwitchMBB =
10842       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10843 
10844   // If there is only the default destination, jump there directly.
10845   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10846   if (Clusters.empty()) {
10847     assert(PeeledSwitchMBB == SwitchMBB);
10848     SwitchMBB->addSuccessor(DefaultMBB);
10849     if (DefaultMBB != NextBlock(SwitchMBB)) {
10850       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10851                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10852     }
10853     return;
10854   }
10855 
10856   findJumpTables(Clusters, &SI, DefaultMBB);
10857   findBitTestClusters(Clusters, &SI);
10858 
10859   LLVM_DEBUG({
10860     dbgs() << "Case clusters: ";
10861     for (const CaseCluster &C : Clusters) {
10862       if (C.Kind == CC_JumpTable)
10863         dbgs() << "JT:";
10864       if (C.Kind == CC_BitTests)
10865         dbgs() << "BT:";
10866 
10867       C.Low->getValue().print(dbgs(), true);
10868       if (C.Low != C.High) {
10869         dbgs() << '-';
10870         C.High->getValue().print(dbgs(), true);
10871       }
10872       dbgs() << ' ';
10873     }
10874     dbgs() << '\n';
10875   });
10876 
10877   assert(!Clusters.empty());
10878   SwitchWorkList WorkList;
10879   CaseClusterIt First = Clusters.begin();
10880   CaseClusterIt Last = Clusters.end() - 1;
10881   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10882   // Scale the branchprobability for DefaultMBB if the peel occurs and
10883   // DefaultMBB is not replaced.
10884   if (PeeledCaseProb != BranchProbability::getZero() &&
10885       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10886     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10887   WorkList.push_back(
10888       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10889 
10890   while (!WorkList.empty()) {
10891     SwitchWorkListItem W = WorkList.back();
10892     WorkList.pop_back();
10893     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10894 
10895     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10896         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
10897       // For optimized builds, lower large range as a balanced binary tree.
10898       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10899       continue;
10900     }
10901 
10902     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10903   }
10904 }
10905