xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 2946cd701067404b99c39fb29dc9c74bd7193eb3)
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/TargetFrameLowering.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/CodeGen/WinEHFuncInfo.h"
65 #include "llvm/IR/Argument.h"
66 #include "llvm/IR/Attributes.h"
67 #include "llvm/IR/BasicBlock.h"
68 #include "llvm/IR/CFG.h"
69 #include "llvm/IR/CallSite.h"
70 #include "llvm/IR/CallingConv.h"
71 #include "llvm/IR/Constant.h"
72 #include "llvm/IR/ConstantRange.h"
73 #include "llvm/IR/Constants.h"
74 #include "llvm/IR/DataLayout.h"
75 #include "llvm/IR/DebugInfoMetadata.h"
76 #include "llvm/IR/DebugLoc.h"
77 #include "llvm/IR/DerivedTypes.h"
78 #include "llvm/IR/Function.h"
79 #include "llvm/IR/GetElementPtrTypeIterator.h"
80 #include "llvm/IR/InlineAsm.h"
81 #include "llvm/IR/InstrTypes.h"
82 #include "llvm/IR/Instruction.h"
83 #include "llvm/IR/Instructions.h"
84 #include "llvm/IR/IntrinsicInst.h"
85 #include "llvm/IR/Intrinsics.h"
86 #include "llvm/IR/LLVMContext.h"
87 #include "llvm/IR/Metadata.h"
88 #include "llvm/IR/Module.h"
89 #include "llvm/IR/Operator.h"
90 #include "llvm/IR/PatternMatch.h"
91 #include "llvm/IR/Statepoint.h"
92 #include "llvm/IR/Type.h"
93 #include "llvm/IR/User.h"
94 #include "llvm/IR/Value.h"
95 #include "llvm/MC/MCContext.h"
96 #include "llvm/MC/MCSymbol.h"
97 #include "llvm/Support/AtomicOrdering.h"
98 #include "llvm/Support/BranchProbability.h"
99 #include "llvm/Support/Casting.h"
100 #include "llvm/Support/CodeGen.h"
101 #include "llvm/Support/CommandLine.h"
102 #include "llvm/Support/Compiler.h"
103 #include "llvm/Support/Debug.h"
104 #include "llvm/Support/ErrorHandling.h"
105 #include "llvm/Support/MachineValueType.h"
106 #include "llvm/Support/MathExtras.h"
107 #include "llvm/Support/raw_ostream.h"
108 #include "llvm/Target/TargetIntrinsicInfo.h"
109 #include "llvm/Target/TargetMachine.h"
110 #include "llvm/Target/TargetOptions.h"
111 #include <algorithm>
112 #include <cassert>
113 #include <cstddef>
114 #include <cstdint>
115 #include <cstring>
116 #include <iterator>
117 #include <limits>
118 #include <numeric>
119 #include <tuple>
120 #include <utility>
121 #include <vector>
122 
123 using namespace llvm;
124 using namespace PatternMatch;
125 
126 #define DEBUG_TYPE "isel"
127 
128 /// LimitFloatPrecision - Generate low-precision inline sequences for
129 /// some float libcalls (6, 8 or 12 bits).
130 static unsigned LimitFloatPrecision;
131 
132 static cl::opt<unsigned, true>
133     LimitFPPrecision("limit-float-precision",
134                      cl::desc("Generate low-precision inline sequences "
135                               "for some float libcalls"),
136                      cl::location(LimitFloatPrecision), cl::Hidden,
137                      cl::init(0));
138 
139 static cl::opt<unsigned> SwitchPeelThreshold(
140     "switch-peel-threshold", cl::Hidden, cl::init(66),
141     cl::desc("Set the case probability threshold for peeling the case from a "
142              "switch statement. A value greater than 100 will void this "
143              "optimization"));
144 
145 // Limit the width of DAG chains. This is important in general to prevent
146 // DAG-based analysis from blowing up. For example, alias analysis and
147 // load clustering may not complete in reasonable time. It is difficult to
148 // recognize and avoid this situation within each individual analysis, and
149 // future analyses are likely to have the same behavior. Limiting DAG width is
150 // the safe approach and will be especially important with global DAGs.
151 //
152 // MaxParallelChains default is arbitrarily high to avoid affecting
153 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
154 // sequence over this should have been converted to llvm.memcpy by the
155 // frontend. It is easy to induce this behavior with .ll code such as:
156 // %buffer = alloca [4096 x i8]
157 // %data = load [4096 x i8]* %argPtr
158 // store [4096 x i8] %data, [4096 x i8]* %buffer
159 static const unsigned MaxParallelChains = 64;
160 
161 // Return the calling convention if the Value passed requires ABI mangling as it
162 // is a parameter to a function or a return value from a function which is not
163 // an intrinsic.
164 static Optional<CallingConv::ID> getABIRegCopyCC(const Value *V) {
165   if (auto *R = dyn_cast<ReturnInst>(V))
166     return R->getParent()->getParent()->getCallingConv();
167 
168   if (auto *CI = dyn_cast<CallInst>(V)) {
169     const bool IsInlineAsm = CI->isInlineAsm();
170     const bool IsIndirectFunctionCall =
171         !IsInlineAsm && !CI->getCalledFunction();
172 
173     // It is possible that the call instruction is an inline asm statement or an
174     // indirect function call in which case the return value of
175     // getCalledFunction() would be nullptr.
176     const bool IsInstrinsicCall =
177         !IsInlineAsm && !IsIndirectFunctionCall &&
178         CI->getCalledFunction()->getIntrinsicID() != Intrinsic::not_intrinsic;
179 
180     if (!IsInlineAsm && !IsInstrinsicCall)
181       return CI->getCallingConv();
182   }
183 
184   return None;
185 }
186 
187 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
188                                       const SDValue *Parts, unsigned NumParts,
189                                       MVT PartVT, EVT ValueVT, const Value *V,
190                                       Optional<CallingConv::ID> CC);
191 
192 /// getCopyFromParts - Create a value that contains the specified legal parts
193 /// combined into the value they represent.  If the parts combine to a type
194 /// larger than ValueVT then AssertOp can be used to specify whether the extra
195 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
196 /// (ISD::AssertSext).
197 static SDValue getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL,
198                                 const SDValue *Parts, unsigned NumParts,
199                                 MVT PartVT, EVT ValueVT, const Value *V,
200                                 Optional<CallingConv::ID> CC = None,
201                                 Optional<ISD::NodeType> AssertOp = None) {
202   if (ValueVT.isVector())
203     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
204                                   CC);
205 
206   assert(NumParts > 0 && "No parts to assemble!");
207   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
208   SDValue Val = Parts[0];
209 
210   if (NumParts > 1) {
211     // Assemble the value from multiple parts.
212     if (ValueVT.isInteger()) {
213       unsigned PartBits = PartVT.getSizeInBits();
214       unsigned ValueBits = ValueVT.getSizeInBits();
215 
216       // Assemble the power of 2 part.
217       unsigned RoundParts = NumParts & (NumParts - 1) ?
218         1 << Log2_32(NumParts) : NumParts;
219       unsigned RoundBits = PartBits * RoundParts;
220       EVT RoundVT = RoundBits == ValueBits ?
221         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
222       SDValue Lo, Hi;
223 
224       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
225 
226       if (RoundParts > 2) {
227         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
228                               PartVT, HalfVT, V);
229         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
230                               RoundParts / 2, PartVT, HalfVT, V);
231       } else {
232         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
233         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
234       }
235 
236       if (DAG.getDataLayout().isBigEndian())
237         std::swap(Lo, Hi);
238 
239       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
240 
241       if (RoundParts < NumParts) {
242         // Assemble the trailing non-power-of-2 part.
243         unsigned OddParts = NumParts - RoundParts;
244         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
245         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
246                               OddVT, V, CC);
247 
248         // Combine the round and odd parts.
249         Lo = Val;
250         if (DAG.getDataLayout().isBigEndian())
251           std::swap(Lo, Hi);
252         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
253         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
254         Hi =
255             DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
256                         DAG.getConstant(Lo.getValueSizeInBits(), DL,
257                                         TLI.getPointerTy(DAG.getDataLayout())));
258         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
259         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
260       }
261     } else if (PartVT.isFloatingPoint()) {
262       // FP split into multiple FP parts (for ppcf128)
263       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
264              "Unexpected split");
265       SDValue Lo, Hi;
266       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
267       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
268       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
269         std::swap(Lo, Hi);
270       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
271     } else {
272       // FP split into integer parts (soft fp)
273       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
274              !PartVT.isVector() && "Unexpected split");
275       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
276       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V, CC);
277     }
278   }
279 
280   // There is now one part, held in Val.  Correct it to match ValueVT.
281   // PartEVT is the type of the register class that holds the value.
282   // ValueVT is the type of the inline asm operation.
283   EVT PartEVT = Val.getValueType();
284 
285   if (PartEVT == ValueVT)
286     return Val;
287 
288   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
289       ValueVT.bitsLT(PartEVT)) {
290     // For an FP value in an integer part, we need to truncate to the right
291     // width first.
292     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
293     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
294   }
295 
296   // Handle types that have the same size.
297   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
298     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
299 
300   // Handle types with different sizes.
301   if (PartEVT.isInteger() && ValueVT.isInteger()) {
302     if (ValueVT.bitsLT(PartEVT)) {
303       // For a truncate, see if we have any information to
304       // indicate whether the truncated bits will always be
305       // zero or sign-extension.
306       if (AssertOp.hasValue())
307         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
308                           DAG.getValueType(ValueVT));
309       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
310     }
311     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
312   }
313 
314   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
315     // FP_ROUND's are always exact here.
316     if (ValueVT.bitsLT(Val.getValueType()))
317       return DAG.getNode(
318           ISD::FP_ROUND, DL, ValueVT, Val,
319           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout())));
320 
321     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
322   }
323 
324   llvm_unreachable("Unknown mismatch!");
325 }
326 
327 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
328                                               const Twine &ErrMsg) {
329   const Instruction *I = dyn_cast_or_null<Instruction>(V);
330   if (!V)
331     return Ctx.emitError(ErrMsg);
332 
333   const char *AsmError = ", possible invalid constraint for vector type";
334   if (const CallInst *CI = dyn_cast<CallInst>(I))
335     if (isa<InlineAsm>(CI->getCalledValue()))
336       return Ctx.emitError(I, ErrMsg + AsmError);
337 
338   return Ctx.emitError(I, ErrMsg);
339 }
340 
341 /// getCopyFromPartsVector - Create a value that contains the specified legal
342 /// parts combined into the value they represent.  If the parts combine to a
343 /// type larger than ValueVT then AssertOp can be used to specify whether the
344 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
345 /// ValueVT (ISD::AssertSext).
346 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
347                                       const SDValue *Parts, unsigned NumParts,
348                                       MVT PartVT, EVT ValueVT, const Value *V,
349                                       Optional<CallingConv::ID> CallConv) {
350   assert(ValueVT.isVector() && "Not a vector value");
351   assert(NumParts > 0 && "No parts to assemble!");
352   const bool IsABIRegCopy = CallConv.hasValue();
353 
354   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
355   SDValue Val = Parts[0];
356 
357   // Handle a multi-element vector.
358   if (NumParts > 1) {
359     EVT IntermediateVT;
360     MVT RegisterVT;
361     unsigned NumIntermediates;
362     unsigned NumRegs;
363 
364     if (IsABIRegCopy) {
365       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
366           *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
367           NumIntermediates, RegisterVT);
368     } else {
369       NumRegs =
370           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
371                                      NumIntermediates, RegisterVT);
372     }
373 
374     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
375     NumParts = NumRegs; // Silence a compiler warning.
376     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
377     assert(RegisterVT.getSizeInBits() ==
378            Parts[0].getSimpleValueType().getSizeInBits() &&
379            "Part type sizes don't match!");
380 
381     // Assemble the parts into intermediate operands.
382     SmallVector<SDValue, 8> Ops(NumIntermediates);
383     if (NumIntermediates == NumParts) {
384       // If the register was not expanded, truncate or copy the value,
385       // as appropriate.
386       for (unsigned i = 0; i != NumParts; ++i)
387         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
388                                   PartVT, IntermediateVT, V);
389     } else if (NumParts > 0) {
390       // If the intermediate type was expanded, build the intermediate
391       // operands from the parts.
392       assert(NumParts % NumIntermediates == 0 &&
393              "Must expand into a divisible number of parts!");
394       unsigned Factor = NumParts / NumIntermediates;
395       for (unsigned i = 0; i != NumIntermediates; ++i)
396         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
397                                   PartVT, IntermediateVT, V);
398     }
399 
400     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
401     // intermediate operands.
402     EVT BuiltVectorTy =
403         EVT::getVectorVT(*DAG.getContext(), IntermediateVT.getScalarType(),
404                          (IntermediateVT.isVector()
405                               ? IntermediateVT.getVectorNumElements() * NumParts
406                               : NumIntermediates));
407     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
408                                                 : ISD::BUILD_VECTOR,
409                       DL, BuiltVectorTy, Ops);
410   }
411 
412   // There is now one part, held in Val.  Correct it to match ValueVT.
413   EVT PartEVT = Val.getValueType();
414 
415   if (PartEVT == ValueVT)
416     return Val;
417 
418   if (PartEVT.isVector()) {
419     // If the element type of the source/dest vectors are the same, but the
420     // parts vector has more elements than the value vector, then we have a
421     // vector widening case (e.g. <2 x float> -> <4 x float>).  Extract the
422     // elements we want.
423     if (PartEVT.getVectorElementType() == ValueVT.getVectorElementType()) {
424       assert(PartEVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
425              "Cannot narrow, it would be a lossy transformation");
426       return DAG.getNode(
427           ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
428           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
429     }
430 
431     // Vector/Vector bitcast.
432     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
433       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
434 
435     assert(PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
436       "Cannot handle this kind of promotion");
437     // Promoted vector extract
438     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
439 
440   }
441 
442   // Trivial bitcast if the types are the same size and the destination
443   // vector type is legal.
444   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
445       TLI.isTypeLegal(ValueVT))
446     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
447 
448   if (ValueVT.getVectorNumElements() != 1) {
449      // Certain ABIs require that vectors are passed as integers. For vectors
450      // are the same size, this is an obvious bitcast.
451      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
452        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
453      } else if (ValueVT.getSizeInBits() < PartEVT.getSizeInBits()) {
454        // Bitcast Val back the original type and extract the corresponding
455        // vector we want.
456        unsigned Elts = PartEVT.getSizeInBits() / ValueVT.getScalarSizeInBits();
457        EVT WiderVecType = EVT::getVectorVT(*DAG.getContext(),
458                                            ValueVT.getVectorElementType(), Elts);
459        Val = DAG.getBitcast(WiderVecType, Val);
460        return DAG.getNode(
461            ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
462            DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
463      }
464 
465      diagnosePossiblyInvalidConstraint(
466          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
467      return DAG.getUNDEF(ValueVT);
468   }
469 
470   // Handle cases such as i8 -> <1 x i1>
471   EVT ValueSVT = ValueVT.getVectorElementType();
472   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT)
473     Val = ValueVT.isFloatingPoint() ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
474                                     : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
475 
476   return DAG.getBuildVector(ValueVT, DL, Val);
477 }
478 
479 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
480                                  SDValue Val, SDValue *Parts, unsigned NumParts,
481                                  MVT PartVT, const Value *V,
482                                  Optional<CallingConv::ID> CallConv);
483 
484 /// getCopyToParts - Create a series of nodes that contain the specified value
485 /// split into legal parts.  If the parts contain more bits than Val, then, for
486 /// integers, ExtendKind can be used to specify how to generate the extra bits.
487 static void getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val,
488                            SDValue *Parts, unsigned NumParts, MVT PartVT,
489                            const Value *V,
490                            Optional<CallingConv::ID> CallConv = None,
491                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
492   EVT ValueVT = Val.getValueType();
493 
494   // Handle the vector case separately.
495   if (ValueVT.isVector())
496     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
497                                 CallConv);
498 
499   unsigned PartBits = PartVT.getSizeInBits();
500   unsigned OrigNumParts = NumParts;
501   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
502          "Copying to an illegal type!");
503 
504   if (NumParts == 0)
505     return;
506 
507   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
508   EVT PartEVT = PartVT;
509   if (PartEVT == ValueVT) {
510     assert(NumParts == 1 && "No-op copy with multiple parts!");
511     Parts[0] = Val;
512     return;
513   }
514 
515   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
516     // If the parts cover more bits than the value has, promote the value.
517     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
518       assert(NumParts == 1 && "Do not know what to promote to!");
519       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
520     } else {
521       if (ValueVT.isFloatingPoint()) {
522         // FP values need to be bitcast, then extended if they are being put
523         // into a larger container.
524         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
525         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
526       }
527       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
528              ValueVT.isInteger() &&
529              "Unknown mismatch!");
530       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
531       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
532       if (PartVT == MVT::x86mmx)
533         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
534     }
535   } else if (PartBits == ValueVT.getSizeInBits()) {
536     // Different types of the same size.
537     assert(NumParts == 1 && PartEVT != ValueVT);
538     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
539   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
540     // If the parts cover less bits than value has, truncate the value.
541     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
542            ValueVT.isInteger() &&
543            "Unknown mismatch!");
544     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
545     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
546     if (PartVT == MVT::x86mmx)
547       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
548   }
549 
550   // The value may have changed - recompute ValueVT.
551   ValueVT = Val.getValueType();
552   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
553          "Failed to tile the value with PartVT!");
554 
555   if (NumParts == 1) {
556     if (PartEVT != ValueVT) {
557       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
558                                         "scalar-to-vector conversion failed");
559       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
560     }
561 
562     Parts[0] = Val;
563     return;
564   }
565 
566   // Expand the value into multiple parts.
567   if (NumParts & (NumParts - 1)) {
568     // The number of parts is not a power of 2.  Split off and copy the tail.
569     assert(PartVT.isInteger() && ValueVT.isInteger() &&
570            "Do not know what to expand to!");
571     unsigned RoundParts = 1 << Log2_32(NumParts);
572     unsigned RoundBits = RoundParts * PartBits;
573     unsigned OddParts = NumParts - RoundParts;
574     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
575                                  DAG.getIntPtrConstant(RoundBits, DL));
576     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
577                    CallConv);
578 
579     if (DAG.getDataLayout().isBigEndian())
580       // The odd parts were reversed by getCopyToParts - unreverse them.
581       std::reverse(Parts + RoundParts, Parts + NumParts);
582 
583     NumParts = RoundParts;
584     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
585     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
586   }
587 
588   // The number of parts is a power of 2.  Repeatedly bisect the value using
589   // EXTRACT_ELEMENT.
590   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
591                          EVT::getIntegerVT(*DAG.getContext(),
592                                            ValueVT.getSizeInBits()),
593                          Val);
594 
595   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
596     for (unsigned i = 0; i < NumParts; i += StepSize) {
597       unsigned ThisBits = StepSize * PartBits / 2;
598       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
599       SDValue &Part0 = Parts[i];
600       SDValue &Part1 = Parts[i+StepSize/2];
601 
602       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
603                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
604       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
605                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
606 
607       if (ThisBits == PartBits && ThisVT != PartVT) {
608         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
609         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
610       }
611     }
612   }
613 
614   if (DAG.getDataLayout().isBigEndian())
615     std::reverse(Parts, Parts + OrigNumParts);
616 }
617 
618 static SDValue widenVectorToPartType(SelectionDAG &DAG,
619                                      SDValue Val, const SDLoc &DL, EVT PartVT) {
620   if (!PartVT.isVector())
621     return SDValue();
622 
623   EVT ValueVT = Val.getValueType();
624   unsigned PartNumElts = PartVT.getVectorNumElements();
625   unsigned ValueNumElts = ValueVT.getVectorNumElements();
626   if (PartNumElts > ValueNumElts &&
627       PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
628     EVT ElementVT = PartVT.getVectorElementType();
629     // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
630     // undef elements.
631     SmallVector<SDValue, 16> Ops;
632     DAG.ExtractVectorElements(Val, Ops);
633     SDValue EltUndef = DAG.getUNDEF(ElementVT);
634     for (unsigned i = ValueNumElts, e = PartNumElts; i != e; ++i)
635       Ops.push_back(EltUndef);
636 
637     // FIXME: Use CONCAT for 2x -> 4x.
638     return DAG.getBuildVector(PartVT, DL, Ops);
639   }
640 
641   return SDValue();
642 }
643 
644 /// getCopyToPartsVector - Create a series of nodes that contain the specified
645 /// value split into legal parts.
646 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
647                                  SDValue Val, SDValue *Parts, unsigned NumParts,
648                                  MVT PartVT, const Value *V,
649                                  Optional<CallingConv::ID> CallConv) {
650   EVT ValueVT = Val.getValueType();
651   assert(ValueVT.isVector() && "Not a vector");
652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
653   const bool IsABIRegCopy = CallConv.hasValue();
654 
655   if (NumParts == 1) {
656     EVT PartEVT = PartVT;
657     if (PartEVT == ValueVT) {
658       // Nothing to do.
659     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
660       // Bitconvert vector->vector case.
661       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
662     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
663       Val = Widened;
664     } else if (PartVT.isVector() &&
665                PartEVT.getVectorElementType().bitsGE(
666                  ValueVT.getVectorElementType()) &&
667                PartEVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
668 
669       // Promoted vector extract
670       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
671     } else {
672       if (ValueVT.getVectorNumElements() == 1) {
673         Val = DAG.getNode(
674             ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
675             DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
676       } else {
677         assert(PartVT.getSizeInBits() > ValueVT.getSizeInBits() &&
678                "lossy conversion of vector to scalar type");
679         EVT IntermediateType =
680             EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
681         Val = DAG.getBitcast(IntermediateType, Val);
682         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
683       }
684     }
685 
686     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
687     Parts[0] = Val;
688     return;
689   }
690 
691   // Handle a multi-element vector.
692   EVT IntermediateVT;
693   MVT RegisterVT;
694   unsigned NumIntermediates;
695   unsigned NumRegs;
696   if (IsABIRegCopy) {
697     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
698         *DAG.getContext(), CallConv.getValue(), ValueVT, IntermediateVT,
699         NumIntermediates, RegisterVT);
700   } else {
701     NumRegs =
702         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
703                                    NumIntermediates, RegisterVT);
704   }
705 
706   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
707   NumParts = NumRegs; // Silence a compiler warning.
708   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
709 
710   unsigned IntermediateNumElts = IntermediateVT.isVector() ?
711     IntermediateVT.getVectorNumElements() : 1;
712 
713   // Convert the vector to the appropiate type if necessary.
714   unsigned DestVectorNoElts = NumIntermediates * IntermediateNumElts;
715 
716   EVT BuiltVectorTy = EVT::getVectorVT(
717       *DAG.getContext(), IntermediateVT.getScalarType(), DestVectorNoElts);
718   MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
719   if (ValueVT != BuiltVectorTy) {
720     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy))
721       Val = Widened;
722 
723     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
724   }
725 
726   // Split the vector into intermediate operands.
727   SmallVector<SDValue, 8> Ops(NumIntermediates);
728   for (unsigned i = 0; i != NumIntermediates; ++i) {
729     if (IntermediateVT.isVector()) {
730       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
731                            DAG.getConstant(i * IntermediateNumElts, DL, IdxVT));
732     } else {
733       Ops[i] = DAG.getNode(
734           ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
735           DAG.getConstant(i, DL, IdxVT));
736     }
737   }
738 
739   // Split the intermediate operands into legal parts.
740   if (NumParts == NumIntermediates) {
741     // If the register was not expanded, promote or copy the value,
742     // as appropriate.
743     for (unsigned i = 0; i != NumParts; ++i)
744       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
745   } else if (NumParts > 0) {
746     // If the intermediate type was expanded, split each the value into
747     // legal parts.
748     assert(NumIntermediates != 0 && "division by zero");
749     assert(NumParts % NumIntermediates == 0 &&
750            "Must expand into a divisible number of parts!");
751     unsigned Factor = NumParts / NumIntermediates;
752     for (unsigned i = 0; i != NumIntermediates; ++i)
753       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
754                      CallConv);
755   }
756 }
757 
758 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
759                            EVT valuevt, Optional<CallingConv::ID> CC)
760     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
761       RegCount(1, regs.size()), CallConv(CC) {}
762 
763 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
764                            const DataLayout &DL, unsigned Reg, Type *Ty,
765                            Optional<CallingConv::ID> CC) {
766   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
767 
768   CallConv = CC;
769 
770   for (EVT ValueVT : ValueVTs) {
771     unsigned NumRegs =
772         isABIMangled()
773             ? TLI.getNumRegistersForCallingConv(Context, CC.getValue(), ValueVT)
774             : TLI.getNumRegisters(Context, ValueVT);
775     MVT RegisterVT =
776         isABIMangled()
777             ? TLI.getRegisterTypeForCallingConv(Context, CC.getValue(), ValueVT)
778             : TLI.getRegisterType(Context, ValueVT);
779     for (unsigned i = 0; i != NumRegs; ++i)
780       Regs.push_back(Reg + i);
781     RegVTs.push_back(RegisterVT);
782     RegCount.push_back(NumRegs);
783     Reg += NumRegs;
784   }
785 }
786 
787 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
788                                       FunctionLoweringInfo &FuncInfo,
789                                       const SDLoc &dl, SDValue &Chain,
790                                       SDValue *Flag, const Value *V) const {
791   // A Value with type {} or [0 x %t] needs no registers.
792   if (ValueVTs.empty())
793     return SDValue();
794 
795   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
796 
797   // Assemble the legal parts into the final values.
798   SmallVector<SDValue, 4> Values(ValueVTs.size());
799   SmallVector<SDValue, 8> Parts;
800   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
801     // Copy the legal parts from the registers.
802     EVT ValueVT = ValueVTs[Value];
803     unsigned NumRegs = RegCount[Value];
804     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
805                                           *DAG.getContext(),
806                                           CallConv.getValue(), RegVTs[Value])
807                                     : RegVTs[Value];
808 
809     Parts.resize(NumRegs);
810     for (unsigned i = 0; i != NumRegs; ++i) {
811       SDValue P;
812       if (!Flag) {
813         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
814       } else {
815         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
816         *Flag = P.getValue(2);
817       }
818 
819       Chain = P.getValue(1);
820       Parts[i] = P;
821 
822       // If the source register was virtual and if we know something about it,
823       // add an assert node.
824       if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
825           !RegisterVT.isInteger())
826         continue;
827 
828       const FunctionLoweringInfo::LiveOutInfo *LOI =
829         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
830       if (!LOI)
831         continue;
832 
833       unsigned RegSize = RegisterVT.getScalarSizeInBits();
834       unsigned NumSignBits = LOI->NumSignBits;
835       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
836 
837       if (NumZeroBits == RegSize) {
838         // The current value is a zero.
839         // Explicitly express that as it would be easier for
840         // optimizations to kick in.
841         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
842         continue;
843       }
844 
845       // FIXME: We capture more information than the dag can represent.  For
846       // now, just use the tightest assertzext/assertsext possible.
847       bool isSExt;
848       EVT FromVT(MVT::Other);
849       if (NumZeroBits) {
850         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
851         isSExt = false;
852       } else if (NumSignBits > 1) {
853         FromVT =
854             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
855         isSExt = true;
856       } else {
857         continue;
858       }
859       // Add an assertion node.
860       assert(FromVT != MVT::Other);
861       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
862                              RegisterVT, P, DAG.getValueType(FromVT));
863     }
864 
865     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
866                                      RegisterVT, ValueVT, V, CallConv);
867     Part += NumRegs;
868     Parts.clear();
869   }
870 
871   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
872 }
873 
874 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
875                                  const SDLoc &dl, SDValue &Chain, SDValue *Flag,
876                                  const Value *V,
877                                  ISD::NodeType PreferredExtendType) const {
878   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
879   ISD::NodeType ExtendKind = PreferredExtendType;
880 
881   // Get the list of the values's legal parts.
882   unsigned NumRegs = Regs.size();
883   SmallVector<SDValue, 8> Parts(NumRegs);
884   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
885     unsigned NumParts = RegCount[Value];
886 
887     MVT RegisterVT = isABIMangled() ? TLI.getRegisterTypeForCallingConv(
888                                           *DAG.getContext(),
889                                           CallConv.getValue(), RegVTs[Value])
890                                     : RegVTs[Value];
891 
892     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
893       ExtendKind = ISD::ZERO_EXTEND;
894 
895     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
896                    NumParts, RegisterVT, V, CallConv, ExtendKind);
897     Part += NumParts;
898   }
899 
900   // Copy the parts into the registers.
901   SmallVector<SDValue, 8> Chains(NumRegs);
902   for (unsigned i = 0; i != NumRegs; ++i) {
903     SDValue Part;
904     if (!Flag) {
905       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
906     } else {
907       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
908       *Flag = Part.getValue(1);
909     }
910 
911     Chains[i] = Part.getValue(0);
912   }
913 
914   if (NumRegs == 1 || Flag)
915     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
916     // flagged to it. That is the CopyToReg nodes and the user are considered
917     // a single scheduling unit. If we create a TokenFactor and return it as
918     // chain, then the TokenFactor is both a predecessor (operand) of the
919     // user as well as a successor (the TF operands are flagged to the user).
920     // c1, f1 = CopyToReg
921     // c2, f2 = CopyToReg
922     // c3     = TokenFactor c1, c2
923     // ...
924     //        = op c3, ..., f2
925     Chain = Chains[NumRegs-1];
926   else
927     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
928 }
929 
930 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
931                                         unsigned MatchingIdx, const SDLoc &dl,
932                                         SelectionDAG &DAG,
933                                         std::vector<SDValue> &Ops) const {
934   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
935 
936   unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
937   if (HasMatching)
938     Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
939   else if (!Regs.empty() &&
940            TargetRegisterInfo::isVirtualRegister(Regs.front())) {
941     // Put the register class of the virtual registers in the flag word.  That
942     // way, later passes can recompute register class constraints for inline
943     // assembly as well as normal instructions.
944     // Don't do this for tied operands that can use the regclass information
945     // from the def.
946     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
947     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
948     Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
949   }
950 
951   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
952   Ops.push_back(Res);
953 
954   if (Code == InlineAsm::Kind_Clobber) {
955     // Clobbers should always have a 1:1 mapping with registers, and may
956     // reference registers that have illegal (e.g. vector) types. Hence, we
957     // shouldn't try to apply any sort of splitting logic to them.
958     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
959            "No 1:1 mapping from clobbers to regs?");
960     unsigned SP = TLI.getStackPointerRegisterToSaveRestore();
961     (void)SP;
962     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
963       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
964       assert(
965           (Regs[I] != SP ||
966            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
967           "If we clobbered the stack pointer, MFI should know about it.");
968     }
969     return;
970   }
971 
972   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
973     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
974     MVT RegisterVT = RegVTs[Value];
975     for (unsigned i = 0; i != NumRegs; ++i) {
976       assert(Reg < Regs.size() && "Mismatch in # registers expected");
977       unsigned TheReg = Regs[Reg++];
978       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
979     }
980   }
981 }
982 
983 SmallVector<std::pair<unsigned, unsigned>, 4>
984 RegsForValue::getRegsAndSizes() const {
985   SmallVector<std::pair<unsigned, unsigned>, 4> OutVec;
986   unsigned I = 0;
987   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
988     unsigned RegCount = std::get<0>(CountAndVT);
989     MVT RegisterVT = std::get<1>(CountAndVT);
990     unsigned RegisterSize = RegisterVT.getSizeInBits();
991     for (unsigned E = I + RegCount; I != E; ++I)
992       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
993   }
994   return OutVec;
995 }
996 
997 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
998                                const TargetLibraryInfo *li) {
999   AA = aa;
1000   GFI = gfi;
1001   LibInfo = li;
1002   DL = &DAG.getDataLayout();
1003   Context = DAG.getContext();
1004   LPadToCallSiteMap.clear();
1005 }
1006 
1007 void SelectionDAGBuilder::clear() {
1008   NodeMap.clear();
1009   UnusedArgNodeMap.clear();
1010   PendingLoads.clear();
1011   PendingExports.clear();
1012   CurInst = nullptr;
1013   HasTailCall = false;
1014   SDNodeOrder = LowestSDNodeOrder;
1015   StatepointLowering.clear();
1016 }
1017 
1018 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1019   DanglingDebugInfoMap.clear();
1020 }
1021 
1022 SDValue SelectionDAGBuilder::getRoot() {
1023   if (PendingLoads.empty())
1024     return DAG.getRoot();
1025 
1026   if (PendingLoads.size() == 1) {
1027     SDValue Root = PendingLoads[0];
1028     DAG.setRoot(Root);
1029     PendingLoads.clear();
1030     return Root;
1031   }
1032 
1033   // Otherwise, we have to make a token factor node.
1034   SDValue Root = DAG.getTokenFactor(getCurSDLoc(), PendingLoads);
1035   PendingLoads.clear();
1036   DAG.setRoot(Root);
1037   return Root;
1038 }
1039 
1040 SDValue SelectionDAGBuilder::getControlRoot() {
1041   SDValue Root = DAG.getRoot();
1042 
1043   if (PendingExports.empty())
1044     return Root;
1045 
1046   // Turn all of the CopyToReg chains into one factored node.
1047   if (Root.getOpcode() != ISD::EntryToken) {
1048     unsigned i = 0, e = PendingExports.size();
1049     for (; i != e; ++i) {
1050       assert(PendingExports[i].getNode()->getNumOperands() > 1);
1051       if (PendingExports[i].getNode()->getOperand(0) == Root)
1052         break;  // Don't add the root if we already indirectly depend on it.
1053     }
1054 
1055     if (i == e)
1056       PendingExports.push_back(Root);
1057   }
1058 
1059   Root = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other,
1060                      PendingExports);
1061   PendingExports.clear();
1062   DAG.setRoot(Root);
1063   return Root;
1064 }
1065 
1066 void SelectionDAGBuilder::visit(const Instruction &I) {
1067   // Set up outgoing PHI node register values before emitting the terminator.
1068   if (I.isTerminator()) {
1069     HandlePHINodesInSuccessorBlocks(I.getParent());
1070   }
1071 
1072   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1073   if (!isa<DbgInfoIntrinsic>(I))
1074     ++SDNodeOrder;
1075 
1076   CurInst = &I;
1077 
1078   visit(I.getOpcode(), I);
1079 
1080   if (auto *FPMO = dyn_cast<FPMathOperator>(&I)) {
1081     // Propagate the fast-math-flags of this IR instruction to the DAG node that
1082     // maps to this instruction.
1083     // TODO: We could handle all flags (nsw, etc) here.
1084     // TODO: If an IR instruction maps to >1 node, only the final node will have
1085     //       flags set.
1086     if (SDNode *Node = getNodeForIRValue(&I)) {
1087       SDNodeFlags IncomingFlags;
1088       IncomingFlags.copyFMF(*FPMO);
1089       if (!Node->getFlags().isDefined())
1090         Node->setFlags(IncomingFlags);
1091       else
1092         Node->intersectFlagsWith(IncomingFlags);
1093     }
1094   }
1095 
1096   if (!I.isTerminator() && !HasTailCall &&
1097       !isStatepoint(&I)) // statepoints handle their exports internally
1098     CopyToExportRegsIfNeeded(&I);
1099 
1100   CurInst = nullptr;
1101 }
1102 
1103 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1104   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1105 }
1106 
1107 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1108   // Note: this doesn't use InstVisitor, because it has to work with
1109   // ConstantExpr's in addition to instructions.
1110   switch (Opcode) {
1111   default: llvm_unreachable("Unknown instruction type encountered!");
1112     // Build the switch statement using the Instruction.def file.
1113 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1114     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1115 #include "llvm/IR/Instruction.def"
1116   }
1117 }
1118 
1119 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1120                                                 const DIExpression *Expr) {
1121   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1122     const DbgValueInst *DI = DDI.getDI();
1123     DIVariable *DanglingVariable = DI->getVariable();
1124     DIExpression *DanglingExpr = DI->getExpression();
1125     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1126       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for " << *DI << "\n");
1127       return true;
1128     }
1129     return false;
1130   };
1131 
1132   for (auto &DDIMI : DanglingDebugInfoMap) {
1133     DanglingDebugInfoVector &DDIV = DDIMI.second;
1134     DDIV.erase(remove_if(DDIV, isMatchingDbgValue), DDIV.end());
1135   }
1136 }
1137 
1138 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1139 // generate the debug data structures now that we've seen its definition.
1140 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1141                                                    SDValue Val) {
1142   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1143   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1144     return;
1145 
1146   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1147   for (auto &DDI : DDIV) {
1148     const DbgValueInst *DI = DDI.getDI();
1149     assert(DI && "Ill-formed DanglingDebugInfo");
1150     DebugLoc dl = DDI.getdl();
1151     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1152     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1153     DILocalVariable *Variable = DI->getVariable();
1154     DIExpression *Expr = DI->getExpression();
1155     assert(Variable->isValidLocationForIntrinsic(dl) &&
1156            "Expected inlined-at fields to agree");
1157     SDDbgValue *SDV;
1158     if (Val.getNode()) {
1159       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, dl, false, Val)) {
1160         LLVM_DEBUG(dbgs() << "Resolve dangling debug info [order="
1161                           << DbgSDNodeOrder << "] for:\n  " << *DI << "\n");
1162         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1163         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1164         // inserted after the definition of Val when emitting the instructions
1165         // after ISel. An alternative could be to teach
1166         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1167         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1168                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1169                    << ValSDNodeOrder << "\n");
1170         SDV = getDbgValue(Val, Variable, Expr, dl,
1171                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1172         DAG.AddDbgValue(SDV, Val.getNode(), false);
1173       } else
1174         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for " << *DI
1175                           << "in EmitFuncArgumentDbgValue\n");
1176     } else
1177       LLVM_DEBUG(dbgs() << "Dropping debug info for " << *DI << "\n");
1178   }
1179   DDIV.clear();
1180 }
1181 
1182 /// getCopyFromRegs - If there was virtual register allocated for the value V
1183 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1184 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1185   DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1186   SDValue Result;
1187 
1188   if (It != FuncInfo.ValueMap.end()) {
1189     unsigned InReg = It->second;
1190 
1191     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1192                      DAG.getDataLayout(), InReg, Ty,
1193                      None); // This is not an ABI copy.
1194     SDValue Chain = DAG.getEntryNode();
1195     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1196                                  V);
1197     resolveDanglingDebugInfo(V, Result);
1198   }
1199 
1200   return Result;
1201 }
1202 
1203 /// getValue - Return an SDValue for the given Value.
1204 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1205   // If we already have an SDValue for this value, use it. It's important
1206   // to do this first, so that we don't create a CopyFromReg if we already
1207   // have a regular SDValue.
1208   SDValue &N = NodeMap[V];
1209   if (N.getNode()) return N;
1210 
1211   // If there's a virtual register allocated and initialized for this
1212   // value, use it.
1213   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1214     return copyFromReg;
1215 
1216   // Otherwise create a new SDValue and remember it.
1217   SDValue Val = getValueImpl(V);
1218   NodeMap[V] = Val;
1219   resolveDanglingDebugInfo(V, Val);
1220   return Val;
1221 }
1222 
1223 // Return true if SDValue exists for the given Value
1224 bool SelectionDAGBuilder::findValue(const Value *V) const {
1225   return (NodeMap.find(V) != NodeMap.end()) ||
1226     (FuncInfo.ValueMap.find(V) != FuncInfo.ValueMap.end());
1227 }
1228 
1229 /// getNonRegisterValue - Return an SDValue for the given Value, but
1230 /// don't look in FuncInfo.ValueMap for a virtual register.
1231 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1232   // If we already have an SDValue for this value, use it.
1233   SDValue &N = NodeMap[V];
1234   if (N.getNode()) {
1235     if (isa<ConstantSDNode>(N) || isa<ConstantFPSDNode>(N)) {
1236       // Remove the debug location from the node as the node is about to be used
1237       // in a location which may differ from the original debug location.  This
1238       // is relevant to Constant and ConstantFP nodes because they can appear
1239       // as constant expressions inside PHI nodes.
1240       N->setDebugLoc(DebugLoc());
1241     }
1242     return N;
1243   }
1244 
1245   // Otherwise create a new SDValue and remember it.
1246   SDValue Val = getValueImpl(V);
1247   NodeMap[V] = Val;
1248   resolveDanglingDebugInfo(V, Val);
1249   return Val;
1250 }
1251 
1252 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1253 /// Create an SDValue for the given value.
1254 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1255   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1256 
1257   if (const Constant *C = dyn_cast<Constant>(V)) {
1258     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1259 
1260     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1261       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1262 
1263     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1264       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1265 
1266     if (isa<ConstantPointerNull>(C)) {
1267       unsigned AS = V->getType()->getPointerAddressSpace();
1268       return DAG.getConstant(0, getCurSDLoc(),
1269                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1270     }
1271 
1272     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1273       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1274 
1275     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1276       return DAG.getUNDEF(VT);
1277 
1278     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1279       visit(CE->getOpcode(), *CE);
1280       SDValue N1 = NodeMap[V];
1281       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1282       return N1;
1283     }
1284 
1285     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1286       SmallVector<SDValue, 4> Constants;
1287       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1288            OI != OE; ++OI) {
1289         SDNode *Val = getValue(*OI).getNode();
1290         // If the operand is an empty aggregate, there are no values.
1291         if (!Val) continue;
1292         // Add each leaf value from the operand to the Constants list
1293         // to form a flattened list of all the values.
1294         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1295           Constants.push_back(SDValue(Val, i));
1296       }
1297 
1298       return DAG.getMergeValues(Constants, getCurSDLoc());
1299     }
1300 
1301     if (const ConstantDataSequential *CDS =
1302           dyn_cast<ConstantDataSequential>(C)) {
1303       SmallVector<SDValue, 4> Ops;
1304       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1305         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1306         // Add each leaf value from the operand to the Constants list
1307         // to form a flattened list of all the values.
1308         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1309           Ops.push_back(SDValue(Val, i));
1310       }
1311 
1312       if (isa<ArrayType>(CDS->getType()))
1313         return DAG.getMergeValues(Ops, getCurSDLoc());
1314       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1315     }
1316 
1317     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1318       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1319              "Unknown struct or array constant!");
1320 
1321       SmallVector<EVT, 4> ValueVTs;
1322       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1323       unsigned NumElts = ValueVTs.size();
1324       if (NumElts == 0)
1325         return SDValue(); // empty struct
1326       SmallVector<SDValue, 4> Constants(NumElts);
1327       for (unsigned i = 0; i != NumElts; ++i) {
1328         EVT EltVT = ValueVTs[i];
1329         if (isa<UndefValue>(C))
1330           Constants[i] = DAG.getUNDEF(EltVT);
1331         else if (EltVT.isFloatingPoint())
1332           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1333         else
1334           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1335       }
1336 
1337       return DAG.getMergeValues(Constants, getCurSDLoc());
1338     }
1339 
1340     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1341       return DAG.getBlockAddress(BA, VT);
1342 
1343     VectorType *VecTy = cast<VectorType>(V->getType());
1344     unsigned NumElements = VecTy->getNumElements();
1345 
1346     // Now that we know the number and type of the elements, get that number of
1347     // elements into the Ops array based on what kind of constant it is.
1348     SmallVector<SDValue, 16> Ops;
1349     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1350       for (unsigned i = 0; i != NumElements; ++i)
1351         Ops.push_back(getValue(CV->getOperand(i)));
1352     } else {
1353       assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1354       EVT EltVT =
1355           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1356 
1357       SDValue Op;
1358       if (EltVT.isFloatingPoint())
1359         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1360       else
1361         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1362       Ops.assign(NumElements, Op);
1363     }
1364 
1365     // Create a BUILD_VECTOR node.
1366     return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1367   }
1368 
1369   // If this is a static alloca, generate it as the frameindex instead of
1370   // computation.
1371   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1372     DenseMap<const AllocaInst*, int>::iterator SI =
1373       FuncInfo.StaticAllocaMap.find(AI);
1374     if (SI != FuncInfo.StaticAllocaMap.end())
1375       return DAG.getFrameIndex(SI->second,
1376                                TLI.getFrameIndexTy(DAG.getDataLayout()));
1377   }
1378 
1379   // If this is an instruction which fast-isel has deferred, select it now.
1380   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1381     unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1382 
1383     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1384                      Inst->getType(), getABIRegCopyCC(V));
1385     SDValue Chain = DAG.getEntryNode();
1386     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1387   }
1388 
1389   llvm_unreachable("Can't get register for value!");
1390 }
1391 
1392 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1393   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1394   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1395   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1396   bool IsSEH = isAsynchronousEHPersonality(Pers);
1397   bool IsWasmCXX = Pers == EHPersonality::Wasm_CXX;
1398   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1399   if (!IsSEH)
1400     CatchPadMBB->setIsEHScopeEntry();
1401   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1402   if (IsMSVCCXX || IsCoreCLR)
1403     CatchPadMBB->setIsEHFuncletEntry();
1404   // Wasm does not need catchpads anymore
1405   if (!IsWasmCXX)
1406     DAG.setRoot(DAG.getNode(ISD::CATCHPAD, getCurSDLoc(), MVT::Other,
1407                             getControlRoot()));
1408 }
1409 
1410 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1411   // Update machine-CFG edge.
1412   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1413   FuncInfo.MBB->addSuccessor(TargetMBB);
1414 
1415   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1416   bool IsSEH = isAsynchronousEHPersonality(Pers);
1417   if (IsSEH) {
1418     // If this is not a fall-through branch or optimizations are switched off,
1419     // emit the branch.
1420     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1421         TM.getOptLevel() == CodeGenOpt::None)
1422       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1423                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1424     return;
1425   }
1426 
1427   // Figure out the funclet membership for the catchret's successor.
1428   // This will be used by the FuncletLayout pass to determine how to order the
1429   // BB's.
1430   // A 'catchret' returns to the outer scope's color.
1431   Value *ParentPad = I.getCatchSwitchParentPad();
1432   const BasicBlock *SuccessorColor;
1433   if (isa<ConstantTokenNone>(ParentPad))
1434     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1435   else
1436     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1437   assert(SuccessorColor && "No parent funclet for catchret!");
1438   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1439   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1440 
1441   // Create the terminator node.
1442   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1443                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1444                             DAG.getBasicBlock(SuccessorColorMBB));
1445   DAG.setRoot(Ret);
1446 }
1447 
1448 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1449   // Don't emit any special code for the cleanuppad instruction. It just marks
1450   // the start of an EH scope/funclet.
1451   FuncInfo.MBB->setIsEHScopeEntry();
1452   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1453   if (Pers != EHPersonality::Wasm_CXX) {
1454     FuncInfo.MBB->setIsEHFuncletEntry();
1455     FuncInfo.MBB->setIsCleanupFuncletEntry();
1456   }
1457 }
1458 
1459 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
1460 /// many places it could ultimately go. In the IR, we have a single unwind
1461 /// destination, but in the machine CFG, we enumerate all the possible blocks.
1462 /// This function skips over imaginary basic blocks that hold catchswitch
1463 /// instructions, and finds all the "real" machine
1464 /// basic block destinations. As those destinations may not be successors of
1465 /// EHPadBB, here we also calculate the edge probability to those destinations.
1466 /// The passed-in Prob is the edge probability to EHPadBB.
1467 static void findUnwindDestinations(
1468     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
1469     BranchProbability Prob,
1470     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
1471         &UnwindDests) {
1472   EHPersonality Personality =
1473     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1474   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
1475   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
1476   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
1477   bool IsSEH = isAsynchronousEHPersonality(Personality);
1478 
1479   while (EHPadBB) {
1480     const Instruction *Pad = EHPadBB->getFirstNonPHI();
1481     BasicBlock *NewEHPadBB = nullptr;
1482     if (isa<LandingPadInst>(Pad)) {
1483       // Stop on landingpads. They are not funclets.
1484       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1485       break;
1486     } else if (isa<CleanupPadInst>(Pad)) {
1487       // Stop on cleanup pads. Cleanups are always funclet entries for all known
1488       // personalities.
1489       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
1490       UnwindDests.back().first->setIsEHScopeEntry();
1491       if (!IsWasmCXX)
1492         UnwindDests.back().first->setIsEHFuncletEntry();
1493       break;
1494     } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
1495       // Add the catchpad handlers to the possible destinations.
1496       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
1497         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
1498         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
1499         if (IsMSVCCXX || IsCoreCLR)
1500           UnwindDests.back().first->setIsEHFuncletEntry();
1501         if (!IsSEH)
1502           UnwindDests.back().first->setIsEHScopeEntry();
1503       }
1504       NewEHPadBB = CatchSwitch->getUnwindDest();
1505     } else {
1506       continue;
1507     }
1508 
1509     BranchProbabilityInfo *BPI = FuncInfo.BPI;
1510     if (BPI && NewEHPadBB)
1511       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
1512     EHPadBB = NewEHPadBB;
1513   }
1514 }
1515 
1516 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
1517   // Update successor info.
1518   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
1519   auto UnwindDest = I.getUnwindDest();
1520   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1521   BranchProbability UnwindDestProb =
1522       (BPI && UnwindDest)
1523           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
1524           : BranchProbability::getZero();
1525   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
1526   for (auto &UnwindDest : UnwindDests) {
1527     UnwindDest.first->setIsEHPad();
1528     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
1529   }
1530   FuncInfo.MBB->normalizeSuccProbs();
1531 
1532   // Create the terminator node.
1533   SDValue Ret =
1534       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
1535   DAG.setRoot(Ret);
1536 }
1537 
1538 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
1539   report_fatal_error("visitCatchSwitch not yet implemented!");
1540 }
1541 
1542 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1543   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1544   auto &DL = DAG.getDataLayout();
1545   SDValue Chain = getControlRoot();
1546   SmallVector<ISD::OutputArg, 8> Outs;
1547   SmallVector<SDValue, 8> OutVals;
1548 
1549   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
1550   // lower
1551   //
1552   //   %val = call <ty> @llvm.experimental.deoptimize()
1553   //   ret <ty> %val
1554   //
1555   // differently.
1556   if (I.getParent()->getTerminatingDeoptimizeCall()) {
1557     LowerDeoptimizingReturn();
1558     return;
1559   }
1560 
1561   if (!FuncInfo.CanLowerReturn) {
1562     unsigned DemoteReg = FuncInfo.DemoteRegister;
1563     const Function *F = I.getParent()->getParent();
1564 
1565     // Emit a store of the return value through the virtual register.
1566     // Leave Outs empty so that LowerReturn won't try to load return
1567     // registers the usual way.
1568     SmallVector<EVT, 1> PtrValueVTs;
1569     ComputeValueVTs(TLI, DL,
1570                     F->getReturnType()->getPointerTo(
1571                         DAG.getDataLayout().getAllocaAddrSpace()),
1572                     PtrValueVTs);
1573 
1574     SDValue RetPtr = DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(),
1575                                         DemoteReg, PtrValueVTs[0]);
1576     SDValue RetOp = getValue(I.getOperand(0));
1577 
1578     SmallVector<EVT, 4> ValueVTs;
1579     SmallVector<uint64_t, 4> Offsets;
1580     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1581     unsigned NumValues = ValueVTs.size();
1582 
1583     SmallVector<SDValue, 4> Chains(NumValues);
1584     for (unsigned i = 0; i != NumValues; ++i) {
1585       // An aggregate return value cannot wrap around the address space, so
1586       // offsets to its parts don't wrap either.
1587       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr, Offsets[i]);
1588       Chains[i] = DAG.getStore(
1589           Chain, getCurSDLoc(), SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1590           // FIXME: better loc info would be nice.
1591           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1592     }
1593 
1594     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
1595                         MVT::Other, Chains);
1596   } else if (I.getNumOperands() != 0) {
1597     SmallVector<EVT, 4> ValueVTs;
1598     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
1599     unsigned NumValues = ValueVTs.size();
1600     if (NumValues) {
1601       SDValue RetOp = getValue(I.getOperand(0));
1602 
1603       const Function *F = I.getParent()->getParent();
1604 
1605       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1606       if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1607                                           Attribute::SExt))
1608         ExtendKind = ISD::SIGN_EXTEND;
1609       else if (F->getAttributes().hasAttribute(AttributeList::ReturnIndex,
1610                                                Attribute::ZExt))
1611         ExtendKind = ISD::ZERO_EXTEND;
1612 
1613       LLVMContext &Context = F->getContext();
1614       bool RetInReg = F->getAttributes().hasAttribute(
1615           AttributeList::ReturnIndex, Attribute::InReg);
1616 
1617       for (unsigned j = 0; j != NumValues; ++j) {
1618         EVT VT = ValueVTs[j];
1619 
1620         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1621           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
1622 
1623         CallingConv::ID CC = F->getCallingConv();
1624 
1625         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
1626         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
1627         SmallVector<SDValue, 4> Parts(NumParts);
1628         getCopyToParts(DAG, getCurSDLoc(),
1629                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1630                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
1631 
1632         // 'inreg' on function refers to return value
1633         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1634         if (RetInReg)
1635           Flags.setInReg();
1636 
1637         // Propagate extension type if any
1638         if (ExtendKind == ISD::SIGN_EXTEND)
1639           Flags.setSExt();
1640         else if (ExtendKind == ISD::ZERO_EXTEND)
1641           Flags.setZExt();
1642 
1643         for (unsigned i = 0; i < NumParts; ++i) {
1644           Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1645                                         VT, /*isfixed=*/true, 0, 0));
1646           OutVals.push_back(Parts[i]);
1647         }
1648       }
1649     }
1650   }
1651 
1652   // Push in swifterror virtual register as the last element of Outs. This makes
1653   // sure swifterror virtual register will be returned in the swifterror
1654   // physical register.
1655   const Function *F = I.getParent()->getParent();
1656   if (TLI.supportSwiftError() &&
1657       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
1658     assert(FuncInfo.SwiftErrorArg && "Need a swift error argument");
1659     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1660     Flags.setSwiftError();
1661     Outs.push_back(ISD::OutputArg(Flags, EVT(TLI.getPointerTy(DL)) /*vt*/,
1662                                   EVT(TLI.getPointerTy(DL)) /*argvt*/,
1663                                   true /*isfixed*/, 1 /*origidx*/,
1664                                   0 /*partOffs*/));
1665     // Create SDNode for the swifterror virtual register.
1666     OutVals.push_back(
1667         DAG.getRegister(FuncInfo.getOrCreateSwiftErrorVRegUseAt(
1668                             &I, FuncInfo.MBB, FuncInfo.SwiftErrorArg).first,
1669                         EVT(TLI.getPointerTy(DL))));
1670   }
1671 
1672   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
1673   CallingConv::ID CallConv =
1674     DAG.getMachineFunction().getFunction().getCallingConv();
1675   Chain = DAG.getTargetLoweringInfo().LowerReturn(
1676       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
1677 
1678   // Verify that the target's LowerReturn behaved as expected.
1679   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1680          "LowerReturn didn't return a valid chain!");
1681 
1682   // Update the DAG with the new chain value resulting from return lowering.
1683   DAG.setRoot(Chain);
1684 }
1685 
1686 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1687 /// created for it, emit nodes to copy the value into the virtual
1688 /// registers.
1689 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1690   // Skip empty types
1691   if (V->getType()->isEmptyTy())
1692     return;
1693 
1694   DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1695   if (VMI != FuncInfo.ValueMap.end()) {
1696     assert(!V->use_empty() && "Unused value assigned virtual registers!");
1697     CopyValueToVirtualRegister(V, VMI->second);
1698   }
1699 }
1700 
1701 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1702 /// the current basic block, add it to ValueMap now so that we'll get a
1703 /// CopyTo/FromReg.
1704 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1705   // No need to export constants.
1706   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1707 
1708   // Already exported?
1709   if (FuncInfo.isExportedInst(V)) return;
1710 
1711   unsigned Reg = FuncInfo.InitializeRegForValue(V);
1712   CopyValueToVirtualRegister(V, Reg);
1713 }
1714 
1715 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1716                                                      const BasicBlock *FromBB) {
1717   // The operands of the setcc have to be in this block.  We don't know
1718   // how to export them from some other block.
1719   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1720     // Can export from current BB.
1721     if (VI->getParent() == FromBB)
1722       return true;
1723 
1724     // Is already exported, noop.
1725     return FuncInfo.isExportedInst(V);
1726   }
1727 
1728   // If this is an argument, we can export it if the BB is the entry block or
1729   // if it is already exported.
1730   if (isa<Argument>(V)) {
1731     if (FromBB == &FromBB->getParent()->getEntryBlock())
1732       return true;
1733 
1734     // Otherwise, can only export this if it is already exported.
1735     return FuncInfo.isExportedInst(V);
1736   }
1737 
1738   // Otherwise, constants can always be exported.
1739   return true;
1740 }
1741 
1742 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
1743 BranchProbability
1744 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
1745                                         const MachineBasicBlock *Dst) const {
1746   BranchProbabilityInfo *BPI = FuncInfo.BPI;
1747   const BasicBlock *SrcBB = Src->getBasicBlock();
1748   const BasicBlock *DstBB = Dst->getBasicBlock();
1749   if (!BPI) {
1750     // If BPI is not available, set the default probability as 1 / N, where N is
1751     // the number of successors.
1752     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
1753     return BranchProbability(1, SuccSize);
1754   }
1755   return BPI->getEdgeProbability(SrcBB, DstBB);
1756 }
1757 
1758 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
1759                                                MachineBasicBlock *Dst,
1760                                                BranchProbability Prob) {
1761   if (!FuncInfo.BPI)
1762     Src->addSuccessorWithoutProb(Dst);
1763   else {
1764     if (Prob.isUnknown())
1765       Prob = getEdgeProbability(Src, Dst);
1766     Src->addSuccessor(Dst, Prob);
1767   }
1768 }
1769 
1770 static bool InBlock(const Value *V, const BasicBlock *BB) {
1771   if (const Instruction *I = dyn_cast<Instruction>(V))
1772     return I->getParent() == BB;
1773   return true;
1774 }
1775 
1776 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1777 /// This function emits a branch and is used at the leaves of an OR or an
1778 /// AND operator tree.
1779 void
1780 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1781                                                   MachineBasicBlock *TBB,
1782                                                   MachineBasicBlock *FBB,
1783                                                   MachineBasicBlock *CurBB,
1784                                                   MachineBasicBlock *SwitchBB,
1785                                                   BranchProbability TProb,
1786                                                   BranchProbability FProb,
1787                                                   bool InvertCond) {
1788   const BasicBlock *BB = CurBB->getBasicBlock();
1789 
1790   // If the leaf of the tree is a comparison, merge the condition into
1791   // the caseblock.
1792   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1793     // The operands of the cmp have to be in this block.  We don't know
1794     // how to export them from some other block.  If this is the first block
1795     // of the sequence, no exporting is needed.
1796     if (CurBB == SwitchBB ||
1797         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1798          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1799       ISD::CondCode Condition;
1800       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1801         ICmpInst::Predicate Pred =
1802             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
1803         Condition = getICmpCondCode(Pred);
1804       } else {
1805         const FCmpInst *FC = cast<FCmpInst>(Cond);
1806         FCmpInst::Predicate Pred =
1807             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
1808         Condition = getFCmpCondCode(Pred);
1809         if (TM.Options.NoNaNsFPMath)
1810           Condition = getFCmpCodeWithoutNaN(Condition);
1811       }
1812 
1813       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
1814                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1815       SwitchCases.push_back(CB);
1816       return;
1817     }
1818   }
1819 
1820   // Create a CaseBlock record representing this branch.
1821   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
1822   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
1823                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
1824   SwitchCases.push_back(CB);
1825 }
1826 
1827 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1828                                                MachineBasicBlock *TBB,
1829                                                MachineBasicBlock *FBB,
1830                                                MachineBasicBlock *CurBB,
1831                                                MachineBasicBlock *SwitchBB,
1832                                                Instruction::BinaryOps Opc,
1833                                                BranchProbability TProb,
1834                                                BranchProbability FProb,
1835                                                bool InvertCond) {
1836   // Skip over not part of the tree and remember to invert op and operands at
1837   // next level.
1838   Value *NotCond;
1839   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
1840       InBlock(NotCond, CurBB->getBasicBlock())) {
1841     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
1842                          !InvertCond);
1843     return;
1844   }
1845 
1846   const Instruction *BOp = dyn_cast<Instruction>(Cond);
1847   // Compute the effective opcode for Cond, taking into account whether it needs
1848   // to be inverted, e.g.
1849   //   and (not (or A, B)), C
1850   // gets lowered as
1851   //   and (and (not A, not B), C)
1852   unsigned BOpc = 0;
1853   if (BOp) {
1854     BOpc = BOp->getOpcode();
1855     if (InvertCond) {
1856       if (BOpc == Instruction::And)
1857         BOpc = Instruction::Or;
1858       else if (BOpc == Instruction::Or)
1859         BOpc = Instruction::And;
1860     }
1861   }
1862 
1863   // If this node is not part of the or/and tree, emit it as a branch.
1864   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1865       BOpc != unsigned(Opc) || !BOp->hasOneUse() ||
1866       BOp->getParent() != CurBB->getBasicBlock() ||
1867       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1868       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1869     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
1870                                  TProb, FProb, InvertCond);
1871     return;
1872   }
1873 
1874   //  Create TmpBB after CurBB.
1875   MachineFunction::iterator BBI(CurBB);
1876   MachineFunction &MF = DAG.getMachineFunction();
1877   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1878   CurBB->getParent()->insert(++BBI, TmpBB);
1879 
1880   if (Opc == Instruction::Or) {
1881     // Codegen X | Y as:
1882     // BB1:
1883     //   jmp_if_X TBB
1884     //   jmp TmpBB
1885     // TmpBB:
1886     //   jmp_if_Y TBB
1887     //   jmp FBB
1888     //
1889 
1890     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1891     // The requirement is that
1892     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
1893     //     = TrueProb for original BB.
1894     // Assuming the original probabilities are A and B, one choice is to set
1895     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
1896     // A/(1+B) and 2B/(1+B). This choice assumes that
1897     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
1898     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
1899     // TmpBB, but the math is more complicated.
1900 
1901     auto NewTrueProb = TProb / 2;
1902     auto NewFalseProb = TProb / 2 + FProb;
1903     // Emit the LHS condition.
1904     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc,
1905                          NewTrueProb, NewFalseProb, InvertCond);
1906 
1907     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
1908     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
1909     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1910     // Emit the RHS condition into TmpBB.
1911     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1912                          Probs[0], Probs[1], InvertCond);
1913   } else {
1914     assert(Opc == Instruction::And && "Unknown merge op!");
1915     // Codegen X & Y as:
1916     // BB1:
1917     //   jmp_if_X TmpBB
1918     //   jmp FBB
1919     // TmpBB:
1920     //   jmp_if_Y TBB
1921     //   jmp FBB
1922     //
1923     //  This requires creation of TmpBB after CurBB.
1924 
1925     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
1926     // The requirement is that
1927     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
1928     //     = FalseProb for original BB.
1929     // Assuming the original probabilities are A and B, one choice is to set
1930     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
1931     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
1932     // TrueProb for BB1 * FalseProb for TmpBB.
1933 
1934     auto NewTrueProb = TProb + FProb / 2;
1935     auto NewFalseProb = FProb / 2;
1936     // Emit the LHS condition.
1937     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc,
1938                          NewTrueProb, NewFalseProb, InvertCond);
1939 
1940     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
1941     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
1942     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
1943     // Emit the RHS condition into TmpBB.
1944     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc,
1945                          Probs[0], Probs[1], InvertCond);
1946   }
1947 }
1948 
1949 /// If the set of cases should be emitted as a series of branches, return true.
1950 /// If we should emit this as a bunch of and/or'd together conditions, return
1951 /// false.
1952 bool
1953 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
1954   if (Cases.size() != 2) return true;
1955 
1956   // If this is two comparisons of the same values or'd or and'd together, they
1957   // will get folded into a single comparison, so don't emit two blocks.
1958   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1959        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1960       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1961        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1962     return false;
1963   }
1964 
1965   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1966   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1967   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1968       Cases[0].CC == Cases[1].CC &&
1969       isa<Constant>(Cases[0].CmpRHS) &&
1970       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1971     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1972       return false;
1973     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1974       return false;
1975   }
1976 
1977   return true;
1978 }
1979 
1980 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1981   MachineBasicBlock *BrMBB = FuncInfo.MBB;
1982 
1983   // Update machine-CFG edges.
1984   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1985 
1986   if (I.isUnconditional()) {
1987     // Update machine-CFG edges.
1988     BrMBB->addSuccessor(Succ0MBB);
1989 
1990     // If this is not a fall-through branch or optimizations are switched off,
1991     // emit the branch.
1992     if (Succ0MBB != NextBlock(BrMBB) || TM.getOptLevel() == CodeGenOpt::None)
1993       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
1994                               MVT::Other, getControlRoot(),
1995                               DAG.getBasicBlock(Succ0MBB)));
1996 
1997     return;
1998   }
1999 
2000   // If this condition is one of the special cases we handle, do special stuff
2001   // now.
2002   const Value *CondVal = I.getCondition();
2003   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2004 
2005   // If this is a series of conditions that are or'd or and'd together, emit
2006   // this as a sequence of branches instead of setcc's with and/or operations.
2007   // As long as jumps are not expensive, this should improve performance.
2008   // For example, instead of something like:
2009   //     cmp A, B
2010   //     C = seteq
2011   //     cmp D, E
2012   //     F = setle
2013   //     or C, F
2014   //     jnz foo
2015   // Emit:
2016   //     cmp A, B
2017   //     je foo
2018   //     cmp D, E
2019   //     jle foo
2020   if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
2021     Instruction::BinaryOps Opcode = BOp->getOpcode();
2022     if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp->hasOneUse() &&
2023         !I.getMetadata(LLVMContext::MD_unpredictable) &&
2024         (Opcode == Instruction::And || Opcode == Instruction::Or)) {
2025       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
2026                            Opcode,
2027                            getEdgeProbability(BrMBB, Succ0MBB),
2028                            getEdgeProbability(BrMBB, Succ1MBB),
2029                            /*InvertCond=*/false);
2030       // If the compares in later blocks need to use values not currently
2031       // exported from this block, export them now.  This block should always
2032       // be the first entry.
2033       assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2034 
2035       // Allow some cases to be rejected.
2036       if (ShouldEmitAsBranches(SwitchCases)) {
2037         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
2038           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
2039           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
2040         }
2041 
2042         // Emit the branch for this block.
2043         visitSwitchCase(SwitchCases[0], BrMBB);
2044         SwitchCases.erase(SwitchCases.begin());
2045         return;
2046       }
2047 
2048       // Okay, we decided not to do this, remove any inserted MBB's and clear
2049       // SwitchCases.
2050       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
2051         FuncInfo.MF->erase(SwitchCases[i].ThisBB);
2052 
2053       SwitchCases.clear();
2054     }
2055   }
2056 
2057   // Create a CaseBlock record representing this branch.
2058   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2059                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2060 
2061   // Use visitSwitchCase to actually insert the fast branch sequence for this
2062   // cond branch.
2063   visitSwitchCase(CB, BrMBB);
2064 }
2065 
2066 /// visitSwitchCase - Emits the necessary code to represent a single node in
2067 /// the binary search tree resulting from lowering a switch instruction.
2068 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2069                                           MachineBasicBlock *SwitchBB) {
2070   SDValue Cond;
2071   SDValue CondLHS = getValue(CB.CmpLHS);
2072   SDLoc dl = CB.DL;
2073 
2074   // Build the setcc now.
2075   if (!CB.CmpMHS) {
2076     // Fold "(X == true)" to X and "(X == false)" to !X to
2077     // handle common cases produced by branch lowering.
2078     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2079         CB.CC == ISD::SETEQ)
2080       Cond = CondLHS;
2081     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2082              CB.CC == ISD::SETEQ) {
2083       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2084       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2085     } else
2086       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
2087   } else {
2088     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2089 
2090     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2091     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2092 
2093     SDValue CmpOp = getValue(CB.CmpMHS);
2094     EVT VT = CmpOp.getValueType();
2095 
2096     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2097       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2098                           ISD::SETLE);
2099     } else {
2100       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2101                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2102       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2103                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2104     }
2105   }
2106 
2107   // Update successor info
2108   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2109   // TrueBB and FalseBB are always different unless the incoming IR is
2110   // degenerate. This only happens when running llc on weird IR.
2111   if (CB.TrueBB != CB.FalseBB)
2112     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2113   SwitchBB->normalizeSuccProbs();
2114 
2115   // If the lhs block is the next block, invert the condition so that we can
2116   // fall through to the lhs instead of the rhs block.
2117   if (CB.TrueBB == NextBlock(SwitchBB)) {
2118     std::swap(CB.TrueBB, CB.FalseBB);
2119     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2120     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2121   }
2122 
2123   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2124                                MVT::Other, getControlRoot(), Cond,
2125                                DAG.getBasicBlock(CB.TrueBB));
2126 
2127   // Insert the false branch. Do this even if it's a fall through branch,
2128   // this makes it easier to do DAG optimizations which require inverting
2129   // the branch condition.
2130   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2131                        DAG.getBasicBlock(CB.FalseBB));
2132 
2133   DAG.setRoot(BrCond);
2134 }
2135 
2136 /// visitJumpTable - Emit JumpTable node in the current MBB
2137 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
2138   // Emit the code for the jump table
2139   assert(JT.Reg != -1U && "Should lower JT Header first!");
2140   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2141   SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurSDLoc(),
2142                                      JT.Reg, PTy);
2143   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2144   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurSDLoc(),
2145                                     MVT::Other, Index.getValue(1),
2146                                     Table, Index);
2147   DAG.setRoot(BrJumpTable);
2148 }
2149 
2150 /// visitJumpTableHeader - This function emits necessary code to produce index
2151 /// in the JumpTable from switch case.
2152 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
2153                                                JumpTableHeader &JTH,
2154                                                MachineBasicBlock *SwitchBB) {
2155   SDLoc dl = getCurSDLoc();
2156 
2157   // Subtract the lowest switch case value from the value being switched on and
2158   // conditional branch to default mbb if the result is greater than the
2159   // difference between smallest and largest cases.
2160   SDValue SwitchOp = getValue(JTH.SValue);
2161   EVT VT = SwitchOp.getValueType();
2162   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2163                             DAG.getConstant(JTH.First, dl, VT));
2164 
2165   // The SDNode we just created, which holds the value being switched on minus
2166   // the smallest case value, needs to be copied to a virtual register so it
2167   // can be used as an index into the jump table in a subsequent basic block.
2168   // This value may be smaller or larger than the target's pointer type, and
2169   // therefore require extension or truncating.
2170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2171   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2172 
2173   unsigned JumpTableReg =
2174       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2175   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2176                                     JumpTableReg, SwitchOp);
2177   JT.Reg = JumpTableReg;
2178 
2179   // Emit the range check for the jump table, and branch to the default block
2180   // for the switch statement if the value being switched on exceeds the largest
2181   // case in the switch.
2182   SDValue CMP = DAG.getSetCC(
2183       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2184                                  Sub.getValueType()),
2185       Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
2186 
2187   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2188                                MVT::Other, CopyTo, CMP,
2189                                DAG.getBasicBlock(JT.Default));
2190 
2191   // Avoid emitting unnecessary branches to the next block.
2192   if (JT.MBB != NextBlock(SwitchBB))
2193     BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2194                          DAG.getBasicBlock(JT.MBB));
2195 
2196   DAG.setRoot(BrCond);
2197 }
2198 
2199 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
2200 /// variable if there exists one.
2201 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
2202                                  SDValue &Chain) {
2203   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2204   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2205   MachineFunction &MF = DAG.getMachineFunction();
2206   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
2207   MachineSDNode *Node =
2208       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
2209   if (Global) {
2210     MachinePointerInfo MPInfo(Global);
2211     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
2212                  MachineMemOperand::MODereferenceable;
2213     MachineMemOperand *MemRef = MF.getMachineMemOperand(
2214         MPInfo, Flags, PtrTy.getSizeInBits() / 8, DAG.getEVTAlignment(PtrTy));
2215     DAG.setNodeMemRefs(Node, {MemRef});
2216   }
2217   return SDValue(Node, 0);
2218 }
2219 
2220 /// Codegen a new tail for a stack protector check ParentMBB which has had its
2221 /// tail spliced into a stack protector check success bb.
2222 ///
2223 /// For a high level explanation of how this fits into the stack protector
2224 /// generation see the comment on the declaration of class
2225 /// StackProtectorDescriptor.
2226 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
2227                                                   MachineBasicBlock *ParentBB) {
2228 
2229   // First create the loads to the guard/stack slot for the comparison.
2230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2231   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
2232 
2233   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
2234   int FI = MFI.getStackProtectorIndex();
2235 
2236   SDValue Guard;
2237   SDLoc dl = getCurSDLoc();
2238   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
2239   const Module &M = *ParentBB->getParent()->getFunction().getParent();
2240   unsigned Align = DL->getPrefTypeAlignment(Type::getInt8PtrTy(M.getContext()));
2241 
2242   // Generate code to load the content of the guard slot.
2243   SDValue GuardVal = DAG.getLoad(
2244       PtrTy, dl, DAG.getEntryNode(), StackSlotPtr,
2245       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
2246       MachineMemOperand::MOVolatile);
2247 
2248   if (TLI.useStackGuardXorFP())
2249     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
2250 
2251   // Retrieve guard check function, nullptr if instrumentation is inlined.
2252   if (const Value *GuardCheck = TLI.getSSPStackGuardCheck(M)) {
2253     // The target provides a guard check function to validate the guard value.
2254     // Generate a call to that function with the content of the guard slot as
2255     // argument.
2256     auto *Fn = cast<Function>(GuardCheck);
2257     FunctionType *FnTy = Fn->getFunctionType();
2258     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
2259 
2260     TargetLowering::ArgListTy Args;
2261     TargetLowering::ArgListEntry Entry;
2262     Entry.Node = GuardVal;
2263     Entry.Ty = FnTy->getParamType(0);
2264     if (Fn->hasAttribute(1, Attribute::AttrKind::InReg))
2265       Entry.IsInReg = true;
2266     Args.push_back(Entry);
2267 
2268     TargetLowering::CallLoweringInfo CLI(DAG);
2269     CLI.setDebugLoc(getCurSDLoc())
2270       .setChain(DAG.getEntryNode())
2271       .setCallee(Fn->getCallingConv(), FnTy->getReturnType(),
2272                  getValue(GuardCheck), std::move(Args));
2273 
2274     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
2275     DAG.setRoot(Result.second);
2276     return;
2277   }
2278 
2279   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
2280   // Otherwise, emit a volatile load to retrieve the stack guard value.
2281   SDValue Chain = DAG.getEntryNode();
2282   if (TLI.useLoadStackGuardNode()) {
2283     Guard = getLoadStackGuard(DAG, dl, Chain);
2284   } else {
2285     const Value *IRGuard = TLI.getSDagStackGuard(M);
2286     SDValue GuardPtr = getValue(IRGuard);
2287 
2288     Guard =
2289         DAG.getLoad(PtrTy, dl, Chain, GuardPtr, MachinePointerInfo(IRGuard, 0),
2290                     Align, MachineMemOperand::MOVolatile);
2291   }
2292 
2293   // Perform the comparison via a subtract/getsetcc.
2294   EVT VT = Guard.getValueType();
2295   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, Guard, GuardVal);
2296 
2297   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
2298                                                         *DAG.getContext(),
2299                                                         Sub.getValueType()),
2300                              Sub, DAG.getConstant(0, dl, VT), ISD::SETNE);
2301 
2302   // If the sub is not 0, then we know the guard/stackslot do not equal, so
2303   // branch to failure MBB.
2304   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2305                                MVT::Other, GuardVal.getOperand(0),
2306                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
2307   // Otherwise branch to success MBB.
2308   SDValue Br = DAG.getNode(ISD::BR, dl,
2309                            MVT::Other, BrCond,
2310                            DAG.getBasicBlock(SPD.getSuccessMBB()));
2311 
2312   DAG.setRoot(Br);
2313 }
2314 
2315 /// Codegen the failure basic block for a stack protector check.
2316 ///
2317 /// A failure stack protector machine basic block consists simply of a call to
2318 /// __stack_chk_fail().
2319 ///
2320 /// For a high level explanation of how this fits into the stack protector
2321 /// generation see the comment on the declaration of class
2322 /// StackProtectorDescriptor.
2323 void
2324 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
2325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2326   SDValue Chain =
2327       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
2328                       None, false, getCurSDLoc(), false, false).second;
2329   DAG.setRoot(Chain);
2330 }
2331 
2332 /// visitBitTestHeader - This function emits necessary code to produce value
2333 /// suitable for "bit tests"
2334 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
2335                                              MachineBasicBlock *SwitchBB) {
2336   SDLoc dl = getCurSDLoc();
2337 
2338   // Subtract the minimum value
2339   SDValue SwitchOp = getValue(B.SValue);
2340   EVT VT = SwitchOp.getValueType();
2341   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2342                             DAG.getConstant(B.First, dl, VT));
2343 
2344   // Check range
2345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2346   SDValue RangeCmp = DAG.getSetCC(
2347       dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
2348                                  Sub.getValueType()),
2349       Sub, DAG.getConstant(B.Range, dl, VT), ISD::SETUGT);
2350 
2351   // Determine the type of the test operands.
2352   bool UsePtrType = false;
2353   if (!TLI.isTypeLegal(VT))
2354     UsePtrType = true;
2355   else {
2356     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
2357       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
2358         // Switch table case range are encoded into series of masks.
2359         // Just use pointer type, it's guaranteed to fit.
2360         UsePtrType = true;
2361         break;
2362       }
2363   }
2364   if (UsePtrType) {
2365     VT = TLI.getPointerTy(DAG.getDataLayout());
2366     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
2367   }
2368 
2369   B.RegVT = VT.getSimpleVT();
2370   B.Reg = FuncInfo.CreateReg(B.RegVT);
2371   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
2372 
2373   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
2374 
2375   addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
2376   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
2377   SwitchBB->normalizeSuccProbs();
2378 
2379   SDValue BrRange = DAG.getNode(ISD::BRCOND, dl,
2380                                 MVT::Other, CopyTo, RangeCmp,
2381                                 DAG.getBasicBlock(B.Default));
2382 
2383   // Avoid emitting unnecessary branches to the next block.
2384   if (MBB != NextBlock(SwitchBB))
2385     BrRange = DAG.getNode(ISD::BR, dl, MVT::Other, BrRange,
2386                           DAG.getBasicBlock(MBB));
2387 
2388   DAG.setRoot(BrRange);
2389 }
2390 
2391 /// visitBitTestCase - this function produces one "bit test"
2392 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
2393                                            MachineBasicBlock* NextMBB,
2394                                            BranchProbability BranchProbToNext,
2395                                            unsigned Reg,
2396                                            BitTestCase &B,
2397                                            MachineBasicBlock *SwitchBB) {
2398   SDLoc dl = getCurSDLoc();
2399   MVT VT = BB.RegVT;
2400   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
2401   SDValue Cmp;
2402   unsigned PopCount = countPopulation(B.Mask);
2403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2404   if (PopCount == 1) {
2405     // Testing for a single bit; just compare the shift count with what it
2406     // would need to be to shift a 1 bit in that position.
2407     Cmp = DAG.getSetCC(
2408         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2409         ShiftOp, DAG.getConstant(countTrailingZeros(B.Mask), dl, VT),
2410         ISD::SETEQ);
2411   } else if (PopCount == BB.Range) {
2412     // There is only one zero bit in the range, test for it directly.
2413     Cmp = DAG.getSetCC(
2414         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2415         ShiftOp, DAG.getConstant(countTrailingOnes(B.Mask), dl, VT),
2416         ISD::SETNE);
2417   } else {
2418     // Make desired shift
2419     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
2420                                     DAG.getConstant(1, dl, VT), ShiftOp);
2421 
2422     // Emit bit tests and jumps
2423     SDValue AndOp = DAG.getNode(ISD::AND, dl,
2424                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
2425     Cmp = DAG.getSetCC(
2426         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
2427         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
2428   }
2429 
2430   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
2431   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
2432   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
2433   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
2434   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
2435   // one as they are relative probabilities (and thus work more like weights),
2436   // and hence we need to normalize them to let the sum of them become one.
2437   SwitchBB->normalizeSuccProbs();
2438 
2439   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
2440                               MVT::Other, getControlRoot(),
2441                               Cmp, DAG.getBasicBlock(B.TargetBB));
2442 
2443   // Avoid emitting unnecessary branches to the next block.
2444   if (NextMBB != NextBlock(SwitchBB))
2445     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
2446                         DAG.getBasicBlock(NextMBB));
2447 
2448   DAG.setRoot(BrAnd);
2449 }
2450 
2451 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
2452   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
2453 
2454   // Retrieve successors. Look through artificial IR level blocks like
2455   // catchswitch for successors.
2456   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
2457   const BasicBlock *EHPadBB = I.getSuccessor(1);
2458 
2459   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
2460   // have to do anything here to lower funclet bundles.
2461   assert(!I.hasOperandBundlesOtherThan(
2462              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
2463          "Cannot lower invokes with arbitrary operand bundles yet!");
2464 
2465   const Value *Callee(I.getCalledValue());
2466   const Function *Fn = dyn_cast<Function>(Callee);
2467   if (isa<InlineAsm>(Callee))
2468     visitInlineAsm(&I);
2469   else if (Fn && Fn->isIntrinsic()) {
2470     switch (Fn->getIntrinsicID()) {
2471     default:
2472       llvm_unreachable("Cannot invoke this intrinsic");
2473     case Intrinsic::donothing:
2474       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
2475       break;
2476     case Intrinsic::experimental_patchpoint_void:
2477     case Intrinsic::experimental_patchpoint_i64:
2478       visitPatchpoint(&I, EHPadBB);
2479       break;
2480     case Intrinsic::experimental_gc_statepoint:
2481       LowerStatepoint(ImmutableStatepoint(&I), EHPadBB);
2482       break;
2483     }
2484   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
2485     // Currently we do not lower any intrinsic calls with deopt operand bundles.
2486     // Eventually we will support lowering the @llvm.experimental.deoptimize
2487     // intrinsic, and right now there are no plans to support other intrinsics
2488     // with deopt state.
2489     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
2490   } else {
2491     LowerCallTo(&I, getValue(Callee), false, EHPadBB);
2492   }
2493 
2494   // If the value of the invoke is used outside of its defining block, make it
2495   // available as a virtual register.
2496   // We already took care of the exported value for the statepoint instruction
2497   // during call to the LowerStatepoint.
2498   if (!isStatepoint(I)) {
2499     CopyToExportRegsIfNeeded(&I);
2500   }
2501 
2502   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2503   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2504   BranchProbability EHPadBBProb =
2505       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
2506           : BranchProbability::getZero();
2507   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
2508 
2509   // Update successor info.
2510   addSuccessorWithProb(InvokeMBB, Return);
2511   for (auto &UnwindDest : UnwindDests) {
2512     UnwindDest.first->setIsEHPad();
2513     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
2514   }
2515   InvokeMBB->normalizeSuccProbs();
2516 
2517   // Drop into normal successor.
2518   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
2519                           MVT::Other, getControlRoot(),
2520                           DAG.getBasicBlock(Return)));
2521 }
2522 
2523 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
2524   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
2525 }
2526 
2527 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
2528   assert(FuncInfo.MBB->isEHPad() &&
2529          "Call to landingpad not in landing pad!");
2530 
2531   // If there aren't registers to copy the values into (e.g., during SjLj
2532   // exceptions), then don't bother to create these DAG nodes.
2533   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2534   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
2535   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
2536       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
2537     return;
2538 
2539   // If landingpad's return type is token type, we don't create DAG nodes
2540   // for its exception pointer and selector value. The extraction of exception
2541   // pointer or selector value from token type landingpads is not currently
2542   // supported.
2543   if (LP.getType()->isTokenTy())
2544     return;
2545 
2546   SmallVector<EVT, 2> ValueVTs;
2547   SDLoc dl = getCurSDLoc();
2548   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
2549   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
2550 
2551   // Get the two live-in registers as SDValues. The physregs have already been
2552   // copied into virtual registers.
2553   SDValue Ops[2];
2554   if (FuncInfo.ExceptionPointerVirtReg) {
2555     Ops[0] = DAG.getZExtOrTrunc(
2556         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2557                            FuncInfo.ExceptionPointerVirtReg,
2558                            TLI.getPointerTy(DAG.getDataLayout())),
2559         dl, ValueVTs[0]);
2560   } else {
2561     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
2562   }
2563   Ops[1] = DAG.getZExtOrTrunc(
2564       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2565                          FuncInfo.ExceptionSelectorVirtReg,
2566                          TLI.getPointerTy(DAG.getDataLayout())),
2567       dl, ValueVTs[1]);
2568 
2569   // Merge into one.
2570   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
2571                             DAG.getVTList(ValueVTs), Ops);
2572   setValue(&LP, Res);
2573 }
2574 
2575 void SelectionDAGBuilder::sortAndRangeify(CaseClusterVector &Clusters) {
2576 #ifndef NDEBUG
2577   for (const CaseCluster &CC : Clusters)
2578     assert(CC.Low == CC.High && "Input clusters must be single-case");
2579 #endif
2580 
2581   llvm::sort(Clusters, [](const CaseCluster &a, const CaseCluster &b) {
2582     return a.Low->getValue().slt(b.Low->getValue());
2583   });
2584 
2585   // Merge adjacent clusters with the same destination.
2586   const unsigned N = Clusters.size();
2587   unsigned DstIndex = 0;
2588   for (unsigned SrcIndex = 0; SrcIndex < N; ++SrcIndex) {
2589     CaseCluster &CC = Clusters[SrcIndex];
2590     const ConstantInt *CaseVal = CC.Low;
2591     MachineBasicBlock *Succ = CC.MBB;
2592 
2593     if (DstIndex != 0 && Clusters[DstIndex - 1].MBB == Succ &&
2594         (CaseVal->getValue() - Clusters[DstIndex - 1].High->getValue()) == 1) {
2595       // If this case has the same successor and is a neighbour, merge it into
2596       // the previous cluster.
2597       Clusters[DstIndex - 1].High = CaseVal;
2598       Clusters[DstIndex - 1].Prob += CC.Prob;
2599     } else {
2600       std::memmove(&Clusters[DstIndex++], &Clusters[SrcIndex],
2601                    sizeof(Clusters[SrcIndex]));
2602     }
2603   }
2604   Clusters.resize(DstIndex);
2605 }
2606 
2607 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2608                                            MachineBasicBlock *Last) {
2609   // Update JTCases.
2610   for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2611     if (JTCases[i].first.HeaderBB == First)
2612       JTCases[i].first.HeaderBB = Last;
2613 
2614   // Update BitTestCases.
2615   for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2616     if (BitTestCases[i].Parent == First)
2617       BitTestCases[i].Parent = Last;
2618 }
2619 
2620 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2621   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2622 
2623   // Update machine-CFG edges with unique successors.
2624   SmallSet<BasicBlock*, 32> Done;
2625   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2626     BasicBlock *BB = I.getSuccessor(i);
2627     bool Inserted = Done.insert(BB).second;
2628     if (!Inserted)
2629         continue;
2630 
2631     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
2632     addSuccessorWithProb(IndirectBrMBB, Succ);
2633   }
2634   IndirectBrMBB->normalizeSuccProbs();
2635 
2636   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
2637                           MVT::Other, getControlRoot(),
2638                           getValue(I.getAddress())));
2639 }
2640 
2641 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
2642   if (!DAG.getTarget().Options.TrapUnreachable)
2643     return;
2644 
2645   // We may be able to ignore unreachable behind a noreturn call.
2646   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
2647     const BasicBlock &BB = *I.getParent();
2648     if (&I != &BB.front()) {
2649       BasicBlock::const_iterator PredI =
2650         std::prev(BasicBlock::const_iterator(&I));
2651       if (const CallInst *Call = dyn_cast<CallInst>(&*PredI)) {
2652         if (Call->doesNotReturn())
2653           return;
2654       }
2655     }
2656   }
2657 
2658   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
2659 }
2660 
2661 void SelectionDAGBuilder::visitFSub(const User &I) {
2662   // -0.0 - X --> fneg
2663   Type *Ty = I.getType();
2664   if (isa<Constant>(I.getOperand(0)) &&
2665       I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2666     SDValue Op2 = getValue(I.getOperand(1));
2667     setValue(&I, DAG.getNode(ISD::FNEG, getCurSDLoc(),
2668                              Op2.getValueType(), Op2));
2669     return;
2670   }
2671 
2672   visitBinary(I, ISD::FSUB);
2673 }
2674 
2675 /// Checks if the given instruction performs a vector reduction, in which case
2676 /// we have the freedom to alter the elements in the result as long as the
2677 /// reduction of them stays unchanged.
2678 static bool isVectorReductionOp(const User *I) {
2679   const Instruction *Inst = dyn_cast<Instruction>(I);
2680   if (!Inst || !Inst->getType()->isVectorTy())
2681     return false;
2682 
2683   auto OpCode = Inst->getOpcode();
2684   switch (OpCode) {
2685   case Instruction::Add:
2686   case Instruction::Mul:
2687   case Instruction::And:
2688   case Instruction::Or:
2689   case Instruction::Xor:
2690     break;
2691   case Instruction::FAdd:
2692   case Instruction::FMul:
2693     if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2694       if (FPOp->getFastMathFlags().isFast())
2695         break;
2696     LLVM_FALLTHROUGH;
2697   default:
2698     return false;
2699   }
2700 
2701   unsigned ElemNum = Inst->getType()->getVectorNumElements();
2702   // Ensure the reduction size is a power of 2.
2703   if (!isPowerOf2_32(ElemNum))
2704     return false;
2705 
2706   unsigned ElemNumToReduce = ElemNum;
2707 
2708   // Do DFS search on the def-use chain from the given instruction. We only
2709   // allow four kinds of operations during the search until we reach the
2710   // instruction that extracts the first element from the vector:
2711   //
2712   //   1. The reduction operation of the same opcode as the given instruction.
2713   //
2714   //   2. PHI node.
2715   //
2716   //   3. ShuffleVector instruction together with a reduction operation that
2717   //      does a partial reduction.
2718   //
2719   //   4. ExtractElement that extracts the first element from the vector, and we
2720   //      stop searching the def-use chain here.
2721   //
2722   // 3 & 4 above perform a reduction on all elements of the vector. We push defs
2723   // from 1-3 to the stack to continue the DFS. The given instruction is not
2724   // a reduction operation if we meet any other instructions other than those
2725   // listed above.
2726 
2727   SmallVector<const User *, 16> UsersToVisit{Inst};
2728   SmallPtrSet<const User *, 16> Visited;
2729   bool ReduxExtracted = false;
2730 
2731   while (!UsersToVisit.empty()) {
2732     auto User = UsersToVisit.back();
2733     UsersToVisit.pop_back();
2734     if (!Visited.insert(User).second)
2735       continue;
2736 
2737     for (const auto &U : User->users()) {
2738       auto Inst = dyn_cast<Instruction>(U);
2739       if (!Inst)
2740         return false;
2741 
2742       if (Inst->getOpcode() == OpCode || isa<PHINode>(U)) {
2743         if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(Inst))
2744           if (!isa<PHINode>(FPOp) && !FPOp->getFastMathFlags().isFast())
2745             return false;
2746         UsersToVisit.push_back(U);
2747       } else if (const ShuffleVectorInst *ShufInst =
2748                      dyn_cast<ShuffleVectorInst>(U)) {
2749         // Detect the following pattern: A ShuffleVector instruction together
2750         // with a reduction that do partial reduction on the first and second
2751         // ElemNumToReduce / 2 elements, and store the result in
2752         // ElemNumToReduce / 2 elements in another vector.
2753 
2754         unsigned ResultElements = ShufInst->getType()->getVectorNumElements();
2755         if (ResultElements < ElemNum)
2756           return false;
2757 
2758         if (ElemNumToReduce == 1)
2759           return false;
2760         if (!isa<UndefValue>(U->getOperand(1)))
2761           return false;
2762         for (unsigned i = 0; i < ElemNumToReduce / 2; ++i)
2763           if (ShufInst->getMaskValue(i) != int(i + ElemNumToReduce / 2))
2764             return false;
2765         for (unsigned i = ElemNumToReduce / 2; i < ElemNum; ++i)
2766           if (ShufInst->getMaskValue(i) != -1)
2767             return false;
2768 
2769         // There is only one user of this ShuffleVector instruction, which
2770         // must be a reduction operation.
2771         if (!U->hasOneUse())
2772           return false;
2773 
2774         auto U2 = dyn_cast<Instruction>(*U->user_begin());
2775         if (!U2 || U2->getOpcode() != OpCode)
2776           return false;
2777 
2778         // Check operands of the reduction operation.
2779         if ((U2->getOperand(0) == U->getOperand(0) && U2->getOperand(1) == U) ||
2780             (U2->getOperand(1) == U->getOperand(0) && U2->getOperand(0) == U)) {
2781           UsersToVisit.push_back(U2);
2782           ElemNumToReduce /= 2;
2783         } else
2784           return false;
2785       } else if (isa<ExtractElementInst>(U)) {
2786         // At this moment we should have reduced all elements in the vector.
2787         if (ElemNumToReduce != 1)
2788           return false;
2789 
2790         const ConstantInt *Val = dyn_cast<ConstantInt>(U->getOperand(1));
2791         if (!Val || !Val->isZero())
2792           return false;
2793 
2794         ReduxExtracted = true;
2795       } else
2796         return false;
2797     }
2798   }
2799   return ReduxExtracted;
2800 }
2801 
2802 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
2803   SDNodeFlags Flags;
2804 
2805   SDValue Op = getValue(I.getOperand(0));
2806   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
2807                                     Op, Flags);
2808   setValue(&I, UnNodeValue);
2809 }
2810 
2811 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
2812   SDNodeFlags Flags;
2813   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
2814     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
2815     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
2816   }
2817   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I)) {
2818     Flags.setExact(ExactOp->isExact());
2819   }
2820   if (isVectorReductionOp(&I)) {
2821     Flags.setVectorReduction(true);
2822     LLVM_DEBUG(dbgs() << "Detected a reduction operation:" << I << "\n");
2823   }
2824 
2825   SDValue Op1 = getValue(I.getOperand(0));
2826   SDValue Op2 = getValue(I.getOperand(1));
2827   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
2828                                      Op1, Op2, Flags);
2829   setValue(&I, BinNodeValue);
2830 }
2831 
2832 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2833   SDValue Op1 = getValue(I.getOperand(0));
2834   SDValue Op2 = getValue(I.getOperand(1));
2835 
2836   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
2837       Op1.getValueType(), DAG.getDataLayout());
2838 
2839   // Coerce the shift amount to the right type if we can.
2840   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2841     unsigned ShiftSize = ShiftTy.getSizeInBits();
2842     unsigned Op2Size = Op2.getValueSizeInBits();
2843     SDLoc DL = getCurSDLoc();
2844 
2845     // If the operand is smaller than the shift count type, promote it.
2846     if (ShiftSize > Op2Size)
2847       Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2848 
2849     // If the operand is larger than the shift count type but the shift
2850     // count type has enough bits to represent any shift value, truncate
2851     // it now. This is a common case and it exposes the truncate to
2852     // optimization early.
2853     else if (ShiftSize >= Log2_32_Ceil(Op2.getValueSizeInBits()))
2854       Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2855     // Otherwise we'll need to temporarily settle for some other convenient
2856     // type.  Type legalization will make adjustments once the shiftee is split.
2857     else
2858       Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2859   }
2860 
2861   bool nuw = false;
2862   bool nsw = false;
2863   bool exact = false;
2864 
2865   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
2866 
2867     if (const OverflowingBinaryOperator *OFBinOp =
2868             dyn_cast<const OverflowingBinaryOperator>(&I)) {
2869       nuw = OFBinOp->hasNoUnsignedWrap();
2870       nsw = OFBinOp->hasNoSignedWrap();
2871     }
2872     if (const PossiblyExactOperator *ExactOp =
2873             dyn_cast<const PossiblyExactOperator>(&I))
2874       exact = ExactOp->isExact();
2875   }
2876   SDNodeFlags Flags;
2877   Flags.setExact(exact);
2878   Flags.setNoSignedWrap(nsw);
2879   Flags.setNoUnsignedWrap(nuw);
2880   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
2881                             Flags);
2882   setValue(&I, Res);
2883 }
2884 
2885 void SelectionDAGBuilder::visitSDiv(const User &I) {
2886   SDValue Op1 = getValue(I.getOperand(0));
2887   SDValue Op2 = getValue(I.getOperand(1));
2888 
2889   SDNodeFlags Flags;
2890   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
2891                  cast<PossiblyExactOperator>(&I)->isExact());
2892   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
2893                            Op2, Flags));
2894 }
2895 
2896 void SelectionDAGBuilder::visitICmp(const User &I) {
2897   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2898   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2899     predicate = IC->getPredicate();
2900   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2901     predicate = ICmpInst::Predicate(IC->getPredicate());
2902   SDValue Op1 = getValue(I.getOperand(0));
2903   SDValue Op2 = getValue(I.getOperand(1));
2904   ISD::CondCode Opcode = getICmpCondCode(predicate);
2905 
2906   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2907                                                         I.getType());
2908   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
2909 }
2910 
2911 void SelectionDAGBuilder::visitFCmp(const User &I) {
2912   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2913   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2914     predicate = FC->getPredicate();
2915   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2916     predicate = FCmpInst::Predicate(FC->getPredicate());
2917   SDValue Op1 = getValue(I.getOperand(0));
2918   SDValue Op2 = getValue(I.getOperand(1));
2919 
2920   ISD::CondCode Condition = getFCmpCondCode(predicate);
2921   auto *FPMO = dyn_cast<FPMathOperator>(&I);
2922   if ((FPMO && FPMO->hasNoNaNs()) || TM.Options.NoNaNsFPMath)
2923     Condition = getFCmpCodeWithoutNaN(Condition);
2924 
2925   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
2926                                                         I.getType());
2927   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
2928 }
2929 
2930 // Check if the condition of the select has one use or two users that are both
2931 // selects with the same condition.
2932 static bool hasOnlySelectUsers(const Value *Cond) {
2933   return llvm::all_of(Cond->users(), [](const Value *V) {
2934     return isa<SelectInst>(V);
2935   });
2936 }
2937 
2938 void SelectionDAGBuilder::visitSelect(const User &I) {
2939   SmallVector<EVT, 4> ValueVTs;
2940   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
2941                   ValueVTs);
2942   unsigned NumValues = ValueVTs.size();
2943   if (NumValues == 0) return;
2944 
2945   SmallVector<SDValue, 4> Values(NumValues);
2946   SDValue Cond     = getValue(I.getOperand(0));
2947   SDValue LHSVal   = getValue(I.getOperand(1));
2948   SDValue RHSVal   = getValue(I.getOperand(2));
2949   auto BaseOps = {Cond};
2950   ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2951     ISD::VSELECT : ISD::SELECT;
2952 
2953   // Min/max matching is only viable if all output VTs are the same.
2954   if (is_splat(ValueVTs)) {
2955     EVT VT = ValueVTs[0];
2956     LLVMContext &Ctx = *DAG.getContext();
2957     auto &TLI = DAG.getTargetLoweringInfo();
2958 
2959     // We care about the legality of the operation after it has been type
2960     // legalized.
2961     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal &&
2962            VT != TLI.getTypeToTransformTo(Ctx, VT))
2963       VT = TLI.getTypeToTransformTo(Ctx, VT);
2964 
2965     // If the vselect is legal, assume we want to leave this as a vector setcc +
2966     // vselect. Otherwise, if this is going to be scalarized, we want to see if
2967     // min/max is legal on the scalar type.
2968     bool UseScalarMinMax = VT.isVector() &&
2969       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
2970 
2971     Value *LHS, *RHS;
2972     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
2973     ISD::NodeType Opc = ISD::DELETED_NODE;
2974     switch (SPR.Flavor) {
2975     case SPF_UMAX:    Opc = ISD::UMAX; break;
2976     case SPF_UMIN:    Opc = ISD::UMIN; break;
2977     case SPF_SMAX:    Opc = ISD::SMAX; break;
2978     case SPF_SMIN:    Opc = ISD::SMIN; break;
2979     case SPF_FMINNUM:
2980       switch (SPR.NaNBehavior) {
2981       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2982       case SPNB_RETURNS_NAN:   Opc = ISD::FMINIMUM; break;
2983       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
2984       case SPNB_RETURNS_ANY: {
2985         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT))
2986           Opc = ISD::FMINNUM;
2987         else if (TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT))
2988           Opc = ISD::FMINIMUM;
2989         else if (UseScalarMinMax)
2990           Opc = TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType()) ?
2991             ISD::FMINNUM : ISD::FMINIMUM;
2992         break;
2993       }
2994       }
2995       break;
2996     case SPF_FMAXNUM:
2997       switch (SPR.NaNBehavior) {
2998       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
2999       case SPNB_RETURNS_NAN:   Opc = ISD::FMAXIMUM; break;
3000       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3001       case SPNB_RETURNS_ANY:
3002 
3003         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT))
3004           Opc = ISD::FMAXNUM;
3005         else if (TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT))
3006           Opc = ISD::FMAXIMUM;
3007         else if (UseScalarMinMax)
3008           Opc = TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType()) ?
3009             ISD::FMAXNUM : ISD::FMAXIMUM;
3010         break;
3011       }
3012       break;
3013     default: break;
3014     }
3015 
3016     if (Opc != ISD::DELETED_NODE &&
3017         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3018          (UseScalarMinMax &&
3019           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3020         // If the underlying comparison instruction is used by any other
3021         // instruction, the consumed instructions won't be destroyed, so it is
3022         // not profitable to convert to a min/max.
3023         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3024       OpCode = Opc;
3025       LHSVal = getValue(LHS);
3026       RHSVal = getValue(RHS);
3027       BaseOps = {};
3028     }
3029   }
3030 
3031   for (unsigned i = 0; i != NumValues; ++i) {
3032     SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3033     Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3034     Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3035     Values[i] = DAG.getNode(OpCode, getCurSDLoc(),
3036                             LHSVal.getNode()->getValueType(LHSVal.getResNo()+i),
3037                             Ops);
3038   }
3039 
3040   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3041                            DAG.getVTList(ValueVTs), Values));
3042 }
3043 
3044 void SelectionDAGBuilder::visitTrunc(const User &I) {
3045   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3046   SDValue N = getValue(I.getOperand(0));
3047   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3048                                                         I.getType());
3049   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3050 }
3051 
3052 void SelectionDAGBuilder::visitZExt(const User &I) {
3053   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3054   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3055   SDValue N = getValue(I.getOperand(0));
3056   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3057                                                         I.getType());
3058   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N));
3059 }
3060 
3061 void SelectionDAGBuilder::visitSExt(const User &I) {
3062   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3063   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3064   SDValue N = getValue(I.getOperand(0));
3065   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3066                                                         I.getType());
3067   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3068 }
3069 
3070 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3071   // FPTrunc is never a no-op cast, no need to check
3072   SDValue N = getValue(I.getOperand(0));
3073   SDLoc dl = getCurSDLoc();
3074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3075   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3076   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3077                            DAG.getTargetConstant(
3078                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3079 }
3080 
3081 void SelectionDAGBuilder::visitFPExt(const User &I) {
3082   // FPExt is never a no-op cast, no need to check
3083   SDValue N = getValue(I.getOperand(0));
3084   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3085                                                         I.getType());
3086   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3087 }
3088 
3089 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3090   // FPToUI is never a no-op cast, no need to check
3091   SDValue N = getValue(I.getOperand(0));
3092   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3093                                                         I.getType());
3094   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3095 }
3096 
3097 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3098   // FPToSI is never a no-op cast, no need to check
3099   SDValue N = getValue(I.getOperand(0));
3100   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3101                                                         I.getType());
3102   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3103 }
3104 
3105 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3106   // UIToFP is never a no-op cast, no need to check
3107   SDValue N = getValue(I.getOperand(0));
3108   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3109                                                         I.getType());
3110   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3111 }
3112 
3113 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3114   // SIToFP is never a no-op cast, no need to check
3115   SDValue N = getValue(I.getOperand(0));
3116   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3117                                                         I.getType());
3118   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3119 }
3120 
3121 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3122   // What to do depends on the size of the integer and the size of the pointer.
3123   // We can either truncate, zero extend, or no-op, accordingly.
3124   SDValue N = getValue(I.getOperand(0));
3125   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3126                                                         I.getType());
3127   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3128 }
3129 
3130 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3131   // What to do depends on the size of the integer and the size of the pointer.
3132   // We can either truncate, zero extend, or no-op, accordingly.
3133   SDValue N = getValue(I.getOperand(0));
3134   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3135                                                         I.getType());
3136   setValue(&I, DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT));
3137 }
3138 
3139 void SelectionDAGBuilder::visitBitCast(const User &I) {
3140   SDValue N = getValue(I.getOperand(0));
3141   SDLoc dl = getCurSDLoc();
3142   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3143                                                         I.getType());
3144 
3145   // BitCast assures us that source and destination are the same size so this is
3146   // either a BITCAST or a no-op.
3147   if (DestVT != N.getValueType())
3148     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3149                              DestVT, N)); // convert types.
3150   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3151   // might fold any kind of constant expression to an integer constant and that
3152   // is not what we are looking for. Only recognize a bitcast of a genuine
3153   // constant integer as an opaque constant.
3154   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3155     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3156                                  /*isOpaque*/true));
3157   else
3158     setValue(&I, N);            // noop cast.
3159 }
3160 
3161 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3163   const Value *SV = I.getOperand(0);
3164   SDValue N = getValue(SV);
3165   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3166 
3167   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3168   unsigned DestAS = I.getType()->getPointerAddressSpace();
3169 
3170   if (!TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
3171     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3172 
3173   setValue(&I, N);
3174 }
3175 
3176 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3178   SDValue InVec = getValue(I.getOperand(0));
3179   SDValue InVal = getValue(I.getOperand(1));
3180   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3181                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3182   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3183                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3184                            InVec, InVal, InIdx));
3185 }
3186 
3187 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3188   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3189   SDValue InVec = getValue(I.getOperand(0));
3190   SDValue InIdx = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3191                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3192   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3193                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3194                            InVec, InIdx));
3195 }
3196 
3197 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3198   SDValue Src1 = getValue(I.getOperand(0));
3199   SDValue Src2 = getValue(I.getOperand(1));
3200   SDLoc DL = getCurSDLoc();
3201 
3202   SmallVector<int, 8> Mask;
3203   ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
3204   unsigned MaskNumElts = Mask.size();
3205 
3206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3207   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3208   EVT SrcVT = Src1.getValueType();
3209   unsigned SrcNumElts = SrcVT.getVectorNumElements();
3210 
3211   if (SrcNumElts == MaskNumElts) {
3212     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
3213     return;
3214   }
3215 
3216   // Normalize the shuffle vector since mask and vector length don't match.
3217   if (SrcNumElts < MaskNumElts) {
3218     // Mask is longer than the source vectors. We can use concatenate vector to
3219     // make the mask and vectors lengths match.
3220 
3221     if (MaskNumElts % SrcNumElts == 0) {
3222       // Mask length is a multiple of the source vector length.
3223       // Check if the shuffle is some kind of concatenation of the input
3224       // vectors.
3225       unsigned NumConcat = MaskNumElts / SrcNumElts;
3226       bool IsConcat = true;
3227       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
3228       for (unsigned i = 0; i != MaskNumElts; ++i) {
3229         int Idx = Mask[i];
3230         if (Idx < 0)
3231           continue;
3232         // Ensure the indices in each SrcVT sized piece are sequential and that
3233         // the same source is used for the whole piece.
3234         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
3235             (ConcatSrcs[i / SrcNumElts] >= 0 &&
3236              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
3237           IsConcat = false;
3238           break;
3239         }
3240         // Remember which source this index came from.
3241         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
3242       }
3243 
3244       // The shuffle is concatenating multiple vectors together. Just emit
3245       // a CONCAT_VECTORS operation.
3246       if (IsConcat) {
3247         SmallVector<SDValue, 8> ConcatOps;
3248         for (auto Src : ConcatSrcs) {
3249           if (Src < 0)
3250             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
3251           else if (Src == 0)
3252             ConcatOps.push_back(Src1);
3253           else
3254             ConcatOps.push_back(Src2);
3255         }
3256         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
3257         return;
3258       }
3259     }
3260 
3261     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
3262     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
3263     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
3264                                     PaddedMaskNumElts);
3265 
3266     // Pad both vectors with undefs to make them the same length as the mask.
3267     SDValue UndefVal = DAG.getUNDEF(SrcVT);
3268 
3269     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
3270     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
3271     MOps1[0] = Src1;
3272     MOps2[0] = Src2;
3273 
3274     Src1 = Src1.isUndef()
3275                ? DAG.getUNDEF(PaddedVT)
3276                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
3277     Src2 = Src2.isUndef()
3278                ? DAG.getUNDEF(PaddedVT)
3279                : DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
3280 
3281     // Readjust mask for new input vector length.
3282     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
3283     for (unsigned i = 0; i != MaskNumElts; ++i) {
3284       int Idx = Mask[i];
3285       if (Idx >= (int)SrcNumElts)
3286         Idx -= SrcNumElts - PaddedMaskNumElts;
3287       MappedOps[i] = Idx;
3288     }
3289 
3290     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
3291 
3292     // If the concatenated vector was padded, extract a subvector with the
3293     // correct number of elements.
3294     if (MaskNumElts != PaddedMaskNumElts)
3295       Result = DAG.getNode(
3296           ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
3297           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3298 
3299     setValue(&I, Result);
3300     return;
3301   }
3302 
3303   if (SrcNumElts > MaskNumElts) {
3304     // Analyze the access pattern of the vector to see if we can extract
3305     // two subvectors and do the shuffle.
3306     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
3307     bool CanExtract = true;
3308     for (int Idx : Mask) {
3309       unsigned Input = 0;
3310       if (Idx < 0)
3311         continue;
3312 
3313       if (Idx >= (int)SrcNumElts) {
3314         Input = 1;
3315         Idx -= SrcNumElts;
3316       }
3317 
3318       // If all the indices come from the same MaskNumElts sized portion of
3319       // the sources we can use extract. Also make sure the extract wouldn't
3320       // extract past the end of the source.
3321       int NewStartIdx = alignDown(Idx, MaskNumElts);
3322       if (NewStartIdx + MaskNumElts > SrcNumElts ||
3323           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
3324         CanExtract = false;
3325       // Make sure we always update StartIdx as we use it to track if all
3326       // elements are undef.
3327       StartIdx[Input] = NewStartIdx;
3328     }
3329 
3330     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
3331       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
3332       return;
3333     }
3334     if (CanExtract) {
3335       // Extract appropriate subvector and generate a vector shuffle
3336       for (unsigned Input = 0; Input < 2; ++Input) {
3337         SDValue &Src = Input == 0 ? Src1 : Src2;
3338         if (StartIdx[Input] < 0)
3339           Src = DAG.getUNDEF(VT);
3340         else {
3341           Src = DAG.getNode(
3342               ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
3343               DAG.getConstant(StartIdx[Input], DL,
3344                               TLI.getVectorIdxTy(DAG.getDataLayout())));
3345         }
3346       }
3347 
3348       // Calculate new mask.
3349       SmallVector<int, 8> MappedOps(Mask.begin(), Mask.end());
3350       for (int &Idx : MappedOps) {
3351         if (Idx >= (int)SrcNumElts)
3352           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3353         else if (Idx >= 0)
3354           Idx -= StartIdx[0];
3355       }
3356 
3357       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
3358       return;
3359     }
3360   }
3361 
3362   // We can't use either concat vectors or extract subvectors so fall back to
3363   // replacing the shuffle with extract and build vector.
3364   // to insert and build vector.
3365   EVT EltVT = VT.getVectorElementType();
3366   EVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
3367   SmallVector<SDValue,8> Ops;
3368   for (int Idx : Mask) {
3369     SDValue Res;
3370 
3371     if (Idx < 0) {
3372       Res = DAG.getUNDEF(EltVT);
3373     } else {
3374       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3375       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
3376 
3377       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
3378                         EltVT, Src, DAG.getConstant(Idx, DL, IdxVT));
3379     }
3380 
3381     Ops.push_back(Res);
3382   }
3383 
3384   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
3385 }
3386 
3387 void SelectionDAGBuilder::visitInsertValue(const User &I) {
3388   ArrayRef<unsigned> Indices;
3389   if (const InsertValueInst *IV = dyn_cast<InsertValueInst>(&I))
3390     Indices = IV->getIndices();
3391   else
3392     Indices = cast<ConstantExpr>(&I)->getIndices();
3393 
3394   const Value *Op0 = I.getOperand(0);
3395   const Value *Op1 = I.getOperand(1);
3396   Type *AggTy = I.getType();
3397   Type *ValTy = Op1->getType();
3398   bool IntoUndef = isa<UndefValue>(Op0);
3399   bool FromUndef = isa<UndefValue>(Op1);
3400 
3401   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3402 
3403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3404   SmallVector<EVT, 4> AggValueVTs;
3405   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
3406   SmallVector<EVT, 4> ValValueVTs;
3407   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3408 
3409   unsigned NumAggValues = AggValueVTs.size();
3410   unsigned NumValValues = ValValueVTs.size();
3411   SmallVector<SDValue, 4> Values(NumAggValues);
3412 
3413   // Ignore an insertvalue that produces an empty object
3414   if (!NumAggValues) {
3415     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3416     return;
3417   }
3418 
3419   SDValue Agg = getValue(Op0);
3420   unsigned i = 0;
3421   // Copy the beginning value(s) from the original aggregate.
3422   for (; i != LinearIndex; ++i)
3423     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3424                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3425   // Copy values from the inserted value(s).
3426   if (NumValValues) {
3427     SDValue Val = getValue(Op1);
3428     for (; i != LinearIndex + NumValValues; ++i)
3429       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3430                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3431   }
3432   // Copy remaining value(s) from the original aggregate.
3433   for (; i != NumAggValues; ++i)
3434     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3435                 SDValue(Agg.getNode(), Agg.getResNo() + i);
3436 
3437   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3438                            DAG.getVTList(AggValueVTs), Values));
3439 }
3440 
3441 void SelectionDAGBuilder::visitExtractValue(const User &I) {
3442   ArrayRef<unsigned> Indices;
3443   if (const ExtractValueInst *EV = dyn_cast<ExtractValueInst>(&I))
3444     Indices = EV->getIndices();
3445   else
3446     Indices = cast<ConstantExpr>(&I)->getIndices();
3447 
3448   const Value *Op0 = I.getOperand(0);
3449   Type *AggTy = Op0->getType();
3450   Type *ValTy = I.getType();
3451   bool OutOfUndef = isa<UndefValue>(Op0);
3452 
3453   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
3454 
3455   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3456   SmallVector<EVT, 4> ValValueVTs;
3457   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
3458 
3459   unsigned NumValValues = ValValueVTs.size();
3460 
3461   // Ignore a extractvalue that produces an empty object
3462   if (!NumValValues) {
3463     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3464     return;
3465   }
3466 
3467   SmallVector<SDValue, 4> Values(NumValValues);
3468 
3469   SDValue Agg = getValue(Op0);
3470   // Copy out the selected value(s).
3471   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3472     Values[i - LinearIndex] =
3473       OutOfUndef ?
3474         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
3475         SDValue(Agg.getNode(), Agg.getResNo() + i);
3476 
3477   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3478                            DAG.getVTList(ValValueVTs), Values));
3479 }
3480 
3481 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
3482   Value *Op0 = I.getOperand(0);
3483   // Note that the pointer operand may be a vector of pointers. Take the scalar
3484   // element which holds a pointer.
3485   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
3486   SDValue N = getValue(Op0);
3487   SDLoc dl = getCurSDLoc();
3488 
3489   // Normalize Vector GEP - all scalar operands should be converted to the
3490   // splat vector.
3491   unsigned VectorWidth = I.getType()->isVectorTy() ?
3492     cast<VectorType>(I.getType())->getVectorNumElements() : 0;
3493 
3494   if (VectorWidth && !N.getValueType().isVector()) {
3495     LLVMContext &Context = *DAG.getContext();
3496     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorWidth);
3497     N = DAG.getSplatBuildVector(VT, dl, N);
3498   }
3499 
3500   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
3501        GTI != E; ++GTI) {
3502     const Value *Idx = GTI.getOperand();
3503     if (StructType *StTy = GTI.getStructTypeOrNull()) {
3504       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
3505       if (Field) {
3506         // N = N + Offset
3507         uint64_t Offset = DL->getStructLayout(StTy)->getElementOffset(Field);
3508 
3509         // In an inbounds GEP with an offset that is nonnegative even when
3510         // interpreted as signed, assume there is no unsigned overflow.
3511         SDNodeFlags Flags;
3512         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
3513           Flags.setNoUnsignedWrap(true);
3514 
3515         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
3516                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
3517       }
3518     } else {
3519       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
3520       MVT IdxTy = MVT::getIntegerVT(IdxSize);
3521       APInt ElementSize(IdxSize, DL->getTypeAllocSize(GTI.getIndexedType()));
3522 
3523       // If this is a scalar constant or a splat vector of constants,
3524       // handle it quickly.
3525       const auto *CI = dyn_cast<ConstantInt>(Idx);
3526       if (!CI && isa<ConstantDataVector>(Idx) &&
3527           cast<ConstantDataVector>(Idx)->getSplatValue())
3528         CI = cast<ConstantInt>(cast<ConstantDataVector>(Idx)->getSplatValue());
3529 
3530       if (CI) {
3531         if (CI->isZero())
3532           continue;
3533         APInt Offs = ElementSize * CI->getValue().sextOrTrunc(IdxSize);
3534         LLVMContext &Context = *DAG.getContext();
3535         SDValue OffsVal = VectorWidth ?
3536           DAG.getConstant(Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorWidth)) :
3537           DAG.getConstant(Offs, dl, IdxTy);
3538 
3539         // In an inbouds GEP with an offset that is nonnegative even when
3540         // interpreted as signed, assume there is no unsigned overflow.
3541         SDNodeFlags Flags;
3542         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
3543           Flags.setNoUnsignedWrap(true);
3544 
3545         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
3546         continue;
3547       }
3548 
3549       // N = N + Idx * ElementSize;
3550       SDValue IdxN = getValue(Idx);
3551 
3552       if (!IdxN.getValueType().isVector() && VectorWidth) {
3553         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(), VectorWidth);
3554         IdxN = DAG.getSplatBuildVector(VT, dl, IdxN);
3555       }
3556 
3557       // If the index is smaller or larger than intptr_t, truncate or extend
3558       // it.
3559       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
3560 
3561       // If this is a multiply by a power of two, turn it into a shl
3562       // immediately.  This is a very common case.
3563       if (ElementSize != 1) {
3564         if (ElementSize.isPowerOf2()) {
3565           unsigned Amt = ElementSize.logBase2();
3566           IdxN = DAG.getNode(ISD::SHL, dl,
3567                              N.getValueType(), IdxN,
3568                              DAG.getConstant(Amt, dl, IdxN.getValueType()));
3569         } else {
3570           SDValue Scale = DAG.getConstant(ElementSize, dl, IdxN.getValueType());
3571           IdxN = DAG.getNode(ISD::MUL, dl,
3572                              N.getValueType(), IdxN, Scale);
3573         }
3574       }
3575 
3576       N = DAG.getNode(ISD::ADD, dl,
3577                       N.getValueType(), N, IdxN);
3578     }
3579   }
3580 
3581   setValue(&I, N);
3582 }
3583 
3584 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
3585   // If this is a fixed sized alloca in the entry block of the function,
3586   // allocate it statically on the stack.
3587   if (FuncInfo.StaticAllocaMap.count(&I))
3588     return;   // getValue will auto-populate this.
3589 
3590   SDLoc dl = getCurSDLoc();
3591   Type *Ty = I.getAllocatedType();
3592   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3593   auto &DL = DAG.getDataLayout();
3594   uint64_t TySize = DL.getTypeAllocSize(Ty);
3595   unsigned Align =
3596       std::max((unsigned)DL.getPrefTypeAlignment(Ty), I.getAlignment());
3597 
3598   SDValue AllocSize = getValue(I.getArraySize());
3599 
3600   EVT IntPtr = TLI.getPointerTy(DAG.getDataLayout(), DL.getAllocaAddrSpace());
3601   if (AllocSize.getValueType() != IntPtr)
3602     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
3603 
3604   AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr,
3605                           AllocSize,
3606                           DAG.getConstant(TySize, dl, IntPtr));
3607 
3608   // Handle alignment.  If the requested alignment is less than or equal to
3609   // the stack alignment, ignore it.  If the size is greater than or equal to
3610   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3611   unsigned StackAlign =
3612       DAG.getSubtarget().getFrameLowering()->getStackAlignment();
3613   if (Align <= StackAlign)
3614     Align = 0;
3615 
3616   // Round the size of the allocation up to the stack alignment size
3617   // by add SA-1 to the size. This doesn't overflow because we're computing
3618   // an address inside an alloca.
3619   SDNodeFlags Flags;
3620   Flags.setNoUnsignedWrap(true);
3621   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
3622                           DAG.getConstant(StackAlign - 1, dl, IntPtr), Flags);
3623 
3624   // Mask out the low bits for alignment purposes.
3625   AllocSize =
3626       DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
3627                   DAG.getConstant(~(uint64_t)(StackAlign - 1), dl, IntPtr));
3628 
3629   SDValue Ops[] = {getRoot(), AllocSize, DAG.getConstant(Align, dl, IntPtr)};
3630   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3631   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
3632   setValue(&I, DSA);
3633   DAG.setRoot(DSA.getValue(1));
3634 
3635   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
3636 }
3637 
3638 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3639   if (I.isAtomic())
3640     return visitAtomicLoad(I);
3641 
3642   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3643   const Value *SV = I.getOperand(0);
3644   if (TLI.supportSwiftError()) {
3645     // Swifterror values can come from either a function parameter with
3646     // swifterror attribute or an alloca with swifterror attribute.
3647     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
3648       if (Arg->hasSwiftErrorAttr())
3649         return visitLoadFromSwiftError(I);
3650     }
3651 
3652     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
3653       if (Alloca->isSwiftError())
3654         return visitLoadFromSwiftError(I);
3655     }
3656   }
3657 
3658   SDValue Ptr = getValue(SV);
3659 
3660   Type *Ty = I.getType();
3661 
3662   bool isVolatile = I.isVolatile();
3663   bool isNonTemporal = I.getMetadata(LLVMContext::MD_nontemporal) != nullptr;
3664   bool isInvariant = I.getMetadata(LLVMContext::MD_invariant_load) != nullptr;
3665   bool isDereferenceable = isDereferenceablePointer(SV, DAG.getDataLayout());
3666   unsigned Alignment = I.getAlignment();
3667 
3668   AAMDNodes AAInfo;
3669   I.getAAMetadata(AAInfo);
3670   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
3671 
3672   SmallVector<EVT, 4> ValueVTs;
3673   SmallVector<uint64_t, 4> Offsets;
3674   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &Offsets);
3675   unsigned NumValues = ValueVTs.size();
3676   if (NumValues == 0)
3677     return;
3678 
3679   SDValue Root;
3680   bool ConstantMemory = false;
3681   if (isVolatile || NumValues > MaxParallelChains)
3682     // Serialize volatile loads with other side effects.
3683     Root = getRoot();
3684   else if (AA &&
3685            AA->pointsToConstantMemory(MemoryLocation(
3686                SV,
3687                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3688                AAInfo))) {
3689     // Do not serialize (non-volatile) loads of constant memory with anything.
3690     Root = DAG.getEntryNode();
3691     ConstantMemory = true;
3692   } else {
3693     // Do not serialize non-volatile loads against each other.
3694     Root = DAG.getRoot();
3695   }
3696 
3697   SDLoc dl = getCurSDLoc();
3698 
3699   if (isVolatile)
3700     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
3701 
3702   // An aggregate load cannot wrap around the address space, so offsets to its
3703   // parts don't wrap either.
3704   SDNodeFlags Flags;
3705   Flags.setNoUnsignedWrap(true);
3706 
3707   SmallVector<SDValue, 4> Values(NumValues);
3708   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3709   EVT PtrVT = Ptr.getValueType();
3710   unsigned ChainI = 0;
3711   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3712     // Serializing loads here may result in excessive register pressure, and
3713     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3714     // could recover a bit by hoisting nodes upward in the chain by recognizing
3715     // they are side-effect free or do not alias. The optimizer should really
3716     // avoid this case by converting large object/array copies to llvm.memcpy
3717     // (MaxParallelChains should always remain as failsafe).
3718     if (ChainI == MaxParallelChains) {
3719       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3720       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3721                                   makeArrayRef(Chains.data(), ChainI));
3722       Root = Chain;
3723       ChainI = 0;
3724     }
3725     SDValue A = DAG.getNode(ISD::ADD, dl,
3726                             PtrVT, Ptr,
3727                             DAG.getConstant(Offsets[i], dl, PtrVT),
3728                             Flags);
3729     auto MMOFlags = MachineMemOperand::MONone;
3730     if (isVolatile)
3731       MMOFlags |= MachineMemOperand::MOVolatile;
3732     if (isNonTemporal)
3733       MMOFlags |= MachineMemOperand::MONonTemporal;
3734     if (isInvariant)
3735       MMOFlags |= MachineMemOperand::MOInvariant;
3736     if (isDereferenceable)
3737       MMOFlags |= MachineMemOperand::MODereferenceable;
3738     MMOFlags |= TLI.getMMOFlags(I);
3739 
3740     SDValue L = DAG.getLoad(ValueVTs[i], dl, Root, A,
3741                             MachinePointerInfo(SV, Offsets[i]), Alignment,
3742                             MMOFlags, AAInfo, Ranges);
3743 
3744     Values[i] = L;
3745     Chains[ChainI] = L.getValue(1);
3746   }
3747 
3748   if (!ConstantMemory) {
3749     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3750                                 makeArrayRef(Chains.data(), ChainI));
3751     if (isVolatile)
3752       DAG.setRoot(Chain);
3753     else
3754       PendingLoads.push_back(Chain);
3755   }
3756 
3757   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
3758                            DAG.getVTList(ValueVTs), Values));
3759 }
3760 
3761 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
3762   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3763          "call visitStoreToSwiftError when backend supports swifterror");
3764 
3765   SmallVector<EVT, 4> ValueVTs;
3766   SmallVector<uint64_t, 4> Offsets;
3767   const Value *SrcV = I.getOperand(0);
3768   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3769                   SrcV->getType(), ValueVTs, &Offsets);
3770   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3771          "expect a single EVT for swifterror");
3772 
3773   SDValue Src = getValue(SrcV);
3774   // Create a virtual register, then update the virtual register.
3775   unsigned VReg; bool CreatedVReg;
3776   std::tie(VReg, CreatedVReg) = FuncInfo.getOrCreateSwiftErrorVRegDefAt(&I);
3777   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
3778   // Chain can be getRoot or getControlRoot.
3779   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
3780                                       SDValue(Src.getNode(), Src.getResNo()));
3781   DAG.setRoot(CopyNode);
3782   if (CreatedVReg)
3783     FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, I.getOperand(1), VReg);
3784 }
3785 
3786 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
3787   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
3788          "call visitLoadFromSwiftError when backend supports swifterror");
3789 
3790   assert(!I.isVolatile() &&
3791          I.getMetadata(LLVMContext::MD_nontemporal) == nullptr &&
3792          I.getMetadata(LLVMContext::MD_invariant_load) == nullptr &&
3793          "Support volatile, non temporal, invariant for load_from_swift_error");
3794 
3795   const Value *SV = I.getOperand(0);
3796   Type *Ty = I.getType();
3797   AAMDNodes AAInfo;
3798   I.getAAMetadata(AAInfo);
3799   assert(
3800       (!AA ||
3801        !AA->pointsToConstantMemory(MemoryLocation(
3802            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
3803            AAInfo))) &&
3804       "load_from_swift_error should not be constant memory");
3805 
3806   SmallVector<EVT, 4> ValueVTs;
3807   SmallVector<uint64_t, 4> Offsets;
3808   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
3809                   ValueVTs, &Offsets);
3810   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
3811          "expect a single EVT for swifterror");
3812 
3813   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
3814   SDValue L = DAG.getCopyFromReg(
3815       getRoot(), getCurSDLoc(),
3816       FuncInfo.getOrCreateSwiftErrorVRegUseAt(&I, FuncInfo.MBB, SV).first,
3817       ValueVTs[0]);
3818 
3819   setValue(&I, L);
3820 }
3821 
3822 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3823   if (I.isAtomic())
3824     return visitAtomicStore(I);
3825 
3826   const Value *SrcV = I.getOperand(0);
3827   const Value *PtrV = I.getOperand(1);
3828 
3829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3830   if (TLI.supportSwiftError()) {
3831     // Swifterror values can come from either a function parameter with
3832     // swifterror attribute or an alloca with swifterror attribute.
3833     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
3834       if (Arg->hasSwiftErrorAttr())
3835         return visitStoreToSwiftError(I);
3836     }
3837 
3838     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
3839       if (Alloca->isSwiftError())
3840         return visitStoreToSwiftError(I);
3841     }
3842   }
3843 
3844   SmallVector<EVT, 4> ValueVTs;
3845   SmallVector<uint64_t, 4> Offsets;
3846   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
3847                   SrcV->getType(), ValueVTs, &Offsets);
3848   unsigned NumValues = ValueVTs.size();
3849   if (NumValues == 0)
3850     return;
3851 
3852   // Get the lowered operands. Note that we do this after
3853   // checking if NumResults is zero, because with zero results
3854   // the operands won't have values in the map.
3855   SDValue Src = getValue(SrcV);
3856   SDValue Ptr = getValue(PtrV);
3857 
3858   SDValue Root = getRoot();
3859   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
3860   SDLoc dl = getCurSDLoc();
3861   EVT PtrVT = Ptr.getValueType();
3862   unsigned Alignment = I.getAlignment();
3863   AAMDNodes AAInfo;
3864   I.getAAMetadata(AAInfo);
3865 
3866   auto MMOFlags = MachineMemOperand::MONone;
3867   if (I.isVolatile())
3868     MMOFlags |= MachineMemOperand::MOVolatile;
3869   if (I.getMetadata(LLVMContext::MD_nontemporal) != nullptr)
3870     MMOFlags |= MachineMemOperand::MONonTemporal;
3871   MMOFlags |= TLI.getMMOFlags(I);
3872 
3873   // An aggregate load cannot wrap around the address space, so offsets to its
3874   // parts don't wrap either.
3875   SDNodeFlags Flags;
3876   Flags.setNoUnsignedWrap(true);
3877 
3878   unsigned ChainI = 0;
3879   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3880     // See visitLoad comments.
3881     if (ChainI == MaxParallelChains) {
3882       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3883                                   makeArrayRef(Chains.data(), ChainI));
3884       Root = Chain;
3885       ChainI = 0;
3886     }
3887     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3888                               DAG.getConstant(Offsets[i], dl, PtrVT), Flags);
3889     SDValue St = DAG.getStore(
3890         Root, dl, SDValue(Src.getNode(), Src.getResNo() + i), Add,
3891         MachinePointerInfo(PtrV, Offsets[i]), Alignment, MMOFlags, AAInfo);
3892     Chains[ChainI] = St;
3893   }
3894 
3895   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3896                                   makeArrayRef(Chains.data(), ChainI));
3897   DAG.setRoot(StoreNode);
3898 }
3899 
3900 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
3901                                            bool IsCompressing) {
3902   SDLoc sdl = getCurSDLoc();
3903 
3904   auto getMaskedStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3905                            unsigned& Alignment) {
3906     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
3907     Src0 = I.getArgOperand(0);
3908     Ptr = I.getArgOperand(1);
3909     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
3910     Mask = I.getArgOperand(3);
3911   };
3912   auto getCompressingStoreOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
3913                            unsigned& Alignment) {
3914     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
3915     Src0 = I.getArgOperand(0);
3916     Ptr = I.getArgOperand(1);
3917     Mask = I.getArgOperand(2);
3918     Alignment = 0;
3919   };
3920 
3921   Value  *PtrOperand, *MaskOperand, *Src0Operand;
3922   unsigned Alignment;
3923   if (IsCompressing)
3924     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3925   else
3926     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
3927 
3928   SDValue Ptr = getValue(PtrOperand);
3929   SDValue Src0 = getValue(Src0Operand);
3930   SDValue Mask = getValue(MaskOperand);
3931 
3932   EVT VT = Src0.getValueType();
3933   if (!Alignment)
3934     Alignment = DAG.getEVTAlignment(VT);
3935 
3936   AAMDNodes AAInfo;
3937   I.getAAMetadata(AAInfo);
3938 
3939   MachineMemOperand *MMO =
3940     DAG.getMachineFunction().
3941     getMachineMemOperand(MachinePointerInfo(PtrOperand),
3942                           MachineMemOperand::MOStore,  VT.getStoreSize(),
3943                           Alignment, AAInfo);
3944   SDValue StoreNode = DAG.getMaskedStore(getRoot(), sdl, Src0, Ptr, Mask, VT,
3945                                          MMO, false /* Truncating */,
3946                                          IsCompressing);
3947   DAG.setRoot(StoreNode);
3948   setValue(&I, StoreNode);
3949 }
3950 
3951 // Get a uniform base for the Gather/Scatter intrinsic.
3952 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
3953 // We try to represent it as a base pointer + vector of indices.
3954 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
3955 // The first operand of the GEP may be a single pointer or a vector of pointers
3956 // Example:
3957 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
3958 //  or
3959 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
3960 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
3961 //
3962 // When the first GEP operand is a single pointer - it is the uniform base we
3963 // are looking for. If first operand of the GEP is a splat vector - we
3964 // extract the splat value and use it as a uniform base.
3965 // In all other cases the function returns 'false'.
3966 static bool getUniformBase(const Value* &Ptr, SDValue& Base, SDValue& Index,
3967                            SDValue &Scale, SelectionDAGBuilder* SDB) {
3968   SelectionDAG& DAG = SDB->DAG;
3969   LLVMContext &Context = *DAG.getContext();
3970 
3971   assert(Ptr->getType()->isVectorTy() && "Uexpected pointer type");
3972   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
3973   if (!GEP)
3974     return false;
3975 
3976   const Value *GEPPtr = GEP->getPointerOperand();
3977   if (!GEPPtr->getType()->isVectorTy())
3978     Ptr = GEPPtr;
3979   else if (!(Ptr = getSplatValue(GEPPtr)))
3980     return false;
3981 
3982   unsigned FinalIndex = GEP->getNumOperands() - 1;
3983   Value *IndexVal = GEP->getOperand(FinalIndex);
3984 
3985   // Ensure all the other indices are 0.
3986   for (unsigned i = 1; i < FinalIndex; ++i) {
3987     auto *C = dyn_cast<ConstantInt>(GEP->getOperand(i));
3988     if (!C || !C->isZero())
3989       return false;
3990   }
3991 
3992   // The operands of the GEP may be defined in another basic block.
3993   // In this case we'll not find nodes for the operands.
3994   if (!SDB->findValue(Ptr) || !SDB->findValue(IndexVal))
3995     return false;
3996 
3997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3998   const DataLayout &DL = DAG.getDataLayout();
3999   Scale = DAG.getTargetConstant(DL.getTypeAllocSize(GEP->getResultElementType()),
4000                                 SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4001   Base = SDB->getValue(Ptr);
4002   Index = SDB->getValue(IndexVal);
4003 
4004   if (!Index.getValueType().isVector()) {
4005     unsigned GEPWidth = GEP->getType()->getVectorNumElements();
4006     EVT VT = EVT::getVectorVT(Context, Index.getValueType(), GEPWidth);
4007     Index = DAG.getSplatBuildVector(VT, SDLoc(Index), Index);
4008   }
4009   return true;
4010 }
4011 
4012 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4013   SDLoc sdl = getCurSDLoc();
4014 
4015   // llvm.masked.scatter.*(Src0, Ptrs, alignemt, Mask)
4016   const Value *Ptr = I.getArgOperand(1);
4017   SDValue Src0 = getValue(I.getArgOperand(0));
4018   SDValue Mask = getValue(I.getArgOperand(3));
4019   EVT VT = Src0.getValueType();
4020   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(2)))->getZExtValue();
4021   if (!Alignment)
4022     Alignment = DAG.getEVTAlignment(VT);
4023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4024 
4025   AAMDNodes AAInfo;
4026   I.getAAMetadata(AAInfo);
4027 
4028   SDValue Base;
4029   SDValue Index;
4030   SDValue Scale;
4031   const Value *BasePtr = Ptr;
4032   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4033 
4034   const Value *MemOpBasePtr = UniformBase ? BasePtr : nullptr;
4035   MachineMemOperand *MMO = DAG.getMachineFunction().
4036     getMachineMemOperand(MachinePointerInfo(MemOpBasePtr),
4037                          MachineMemOperand::MOStore,  VT.getStoreSize(),
4038                          Alignment, AAInfo);
4039   if (!UniformBase) {
4040     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4041     Index = getValue(Ptr);
4042     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4043   }
4044   SDValue Ops[] = { getRoot(), Src0, Mask, Base, Index, Scale };
4045   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4046                                          Ops, MMO);
4047   DAG.setRoot(Scatter);
4048   setValue(&I, Scatter);
4049 }
4050 
4051 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4052   SDLoc sdl = getCurSDLoc();
4053 
4054   auto getMaskedLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4055                            unsigned& Alignment) {
4056     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4057     Ptr = I.getArgOperand(0);
4058     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4059     Mask = I.getArgOperand(2);
4060     Src0 = I.getArgOperand(3);
4061   };
4062   auto getExpandingLoadOps = [&](Value* &Ptr, Value* &Mask, Value* &Src0,
4063                            unsigned& Alignment) {
4064     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4065     Ptr = I.getArgOperand(0);
4066     Alignment = 0;
4067     Mask = I.getArgOperand(1);
4068     Src0 = I.getArgOperand(2);
4069   };
4070 
4071   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4072   unsigned Alignment;
4073   if (IsExpanding)
4074     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4075   else
4076     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4077 
4078   SDValue Ptr = getValue(PtrOperand);
4079   SDValue Src0 = getValue(Src0Operand);
4080   SDValue Mask = getValue(MaskOperand);
4081 
4082   EVT VT = Src0.getValueType();
4083   if (!Alignment)
4084     Alignment = DAG.getEVTAlignment(VT);
4085 
4086   AAMDNodes AAInfo;
4087   I.getAAMetadata(AAInfo);
4088   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4089 
4090   // Do not serialize masked loads of constant memory with anything.
4091   bool AddToChain =
4092       !AA || !AA->pointsToConstantMemory(MemoryLocation(
4093                  PtrOperand,
4094                  LocationSize::precise(
4095                      DAG.getDataLayout().getTypeStoreSize(I.getType())),
4096                  AAInfo));
4097   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4098 
4099   MachineMemOperand *MMO =
4100     DAG.getMachineFunction().
4101     getMachineMemOperand(MachinePointerInfo(PtrOperand),
4102                           MachineMemOperand::MOLoad,  VT.getStoreSize(),
4103                           Alignment, AAInfo, Ranges);
4104 
4105   SDValue Load = DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Mask, Src0, VT, MMO,
4106                                    ISD::NON_EXTLOAD, IsExpanding);
4107   if (AddToChain)
4108     PendingLoads.push_back(Load.getValue(1));
4109   setValue(&I, Load);
4110 }
4111 
4112 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4113   SDLoc sdl = getCurSDLoc();
4114 
4115   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4116   const Value *Ptr = I.getArgOperand(0);
4117   SDValue Src0 = getValue(I.getArgOperand(3));
4118   SDValue Mask = getValue(I.getArgOperand(2));
4119 
4120   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4121   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4122   unsigned Alignment = (cast<ConstantInt>(I.getArgOperand(1)))->getZExtValue();
4123   if (!Alignment)
4124     Alignment = DAG.getEVTAlignment(VT);
4125 
4126   AAMDNodes AAInfo;
4127   I.getAAMetadata(AAInfo);
4128   const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
4129 
4130   SDValue Root = DAG.getRoot();
4131   SDValue Base;
4132   SDValue Index;
4133   SDValue Scale;
4134   const Value *BasePtr = Ptr;
4135   bool UniformBase = getUniformBase(BasePtr, Base, Index, Scale, this);
4136   bool ConstantMemory = false;
4137   if (UniformBase && AA &&
4138       AA->pointsToConstantMemory(
4139           MemoryLocation(BasePtr,
4140                          LocationSize::precise(
4141                              DAG.getDataLayout().getTypeStoreSize(I.getType())),
4142                          AAInfo))) {
4143     // Do not serialize (non-volatile) loads of constant memory with anything.
4144     Root = DAG.getEntryNode();
4145     ConstantMemory = true;
4146   }
4147 
4148   MachineMemOperand *MMO =
4149     DAG.getMachineFunction().
4150     getMachineMemOperand(MachinePointerInfo(UniformBase ? BasePtr : nullptr),
4151                          MachineMemOperand::MOLoad,  VT.getStoreSize(),
4152                          Alignment, AAInfo, Ranges);
4153 
4154   if (!UniformBase) {
4155     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4156     Index = getValue(Ptr);
4157     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4158   }
4159   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4160   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4161                                        Ops, MMO);
4162 
4163   SDValue OutChain = Gather.getValue(1);
4164   if (!ConstantMemory)
4165     PendingLoads.push_back(OutChain);
4166   setValue(&I, Gather);
4167 }
4168 
4169 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4170   SDLoc dl = getCurSDLoc();
4171   AtomicOrdering SuccessOrder = I.getSuccessOrdering();
4172   AtomicOrdering FailureOrder = I.getFailureOrdering();
4173   SyncScope::ID SSID = I.getSyncScopeID();
4174 
4175   SDValue InChain = getRoot();
4176 
4177   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4178   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
4179   SDValue L = DAG.getAtomicCmpSwap(
4180       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, MemVT, VTs, InChain,
4181       getValue(I.getPointerOperand()), getValue(I.getCompareOperand()),
4182       getValue(I.getNewValOperand()), MachinePointerInfo(I.getPointerOperand()),
4183       /*Alignment=*/ 0, SuccessOrder, FailureOrder, SSID);
4184 
4185   SDValue OutChain = L.getValue(2);
4186 
4187   setValue(&I, L);
4188   DAG.setRoot(OutChain);
4189 }
4190 
4191 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
4192   SDLoc dl = getCurSDLoc();
4193   ISD::NodeType NT;
4194   switch (I.getOperation()) {
4195   default: llvm_unreachable("Unknown atomicrmw operation");
4196   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
4197   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
4198   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
4199   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
4200   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
4201   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
4202   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
4203   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
4204   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
4205   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
4206   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
4207   }
4208   AtomicOrdering Order = I.getOrdering();
4209   SyncScope::ID SSID = I.getSyncScopeID();
4210 
4211   SDValue InChain = getRoot();
4212 
4213   SDValue L =
4214     DAG.getAtomic(NT, dl,
4215                   getValue(I.getValOperand()).getSimpleValueType(),
4216                   InChain,
4217                   getValue(I.getPointerOperand()),
4218                   getValue(I.getValOperand()),
4219                   I.getPointerOperand(),
4220                   /* Alignment=*/ 0, Order, SSID);
4221 
4222   SDValue OutChain = L.getValue(1);
4223 
4224   setValue(&I, L);
4225   DAG.setRoot(OutChain);
4226 }
4227 
4228 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
4229   SDLoc dl = getCurSDLoc();
4230   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4231   SDValue Ops[3];
4232   Ops[0] = getRoot();
4233   Ops[1] = DAG.getConstant((unsigned)I.getOrdering(), dl,
4234                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4235   Ops[2] = DAG.getConstant(I.getSyncScopeID(), dl,
4236                            TLI.getFenceOperandTy(DAG.getDataLayout()));
4237   DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops));
4238 }
4239 
4240 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
4241   SDLoc dl = getCurSDLoc();
4242   AtomicOrdering Order = I.getOrdering();
4243   SyncScope::ID SSID = I.getSyncScopeID();
4244 
4245   SDValue InChain = getRoot();
4246 
4247   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4248   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4249 
4250   if (!TLI.supportsUnalignedAtomics() &&
4251       I.getAlignment() < VT.getStoreSize())
4252     report_fatal_error("Cannot generate unaligned atomic load");
4253 
4254   MachineMemOperand *MMO =
4255       DAG.getMachineFunction().
4256       getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()),
4257                            MachineMemOperand::MOVolatile |
4258                            MachineMemOperand::MOLoad,
4259                            VT.getStoreSize(),
4260                            I.getAlignment() ? I.getAlignment() :
4261                                               DAG.getEVTAlignment(VT),
4262                            AAMDNodes(), nullptr, SSID, Order);
4263 
4264   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
4265   SDValue L =
4266       DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
4267                     getValue(I.getPointerOperand()), MMO);
4268 
4269   SDValue OutChain = L.getValue(1);
4270 
4271   setValue(&I, L);
4272   DAG.setRoot(OutChain);
4273 }
4274 
4275 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
4276   SDLoc dl = getCurSDLoc();
4277 
4278   AtomicOrdering Order = I.getOrdering();
4279   SyncScope::ID SSID = I.getSyncScopeID();
4280 
4281   SDValue InChain = getRoot();
4282 
4283   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4284   EVT VT =
4285       TLI.getValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
4286 
4287   if (I.getAlignment() < VT.getStoreSize())
4288     report_fatal_error("Cannot generate unaligned atomic store");
4289 
4290   SDValue OutChain =
4291     DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
4292                   InChain,
4293                   getValue(I.getPointerOperand()),
4294                   getValue(I.getValueOperand()),
4295                   I.getPointerOperand(), I.getAlignment(),
4296                   Order, SSID);
4297 
4298   DAG.setRoot(OutChain);
4299 }
4300 
4301 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
4302 /// node.
4303 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
4304                                                unsigned Intrinsic) {
4305   // Ignore the callsite's attributes. A specific call site may be marked with
4306   // readnone, but the lowering code will expect the chain based on the
4307   // definition.
4308   const Function *F = I.getCalledFunction();
4309   bool HasChain = !F->doesNotAccessMemory();
4310   bool OnlyLoad = HasChain && F->onlyReadsMemory();
4311 
4312   // Build the operand list.
4313   SmallVector<SDValue, 8> Ops;
4314   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
4315     if (OnlyLoad) {
4316       // We don't need to serialize loads against other loads.
4317       Ops.push_back(DAG.getRoot());
4318     } else {
4319       Ops.push_back(getRoot());
4320     }
4321   }
4322 
4323   // Info is set by getTgtMemInstrinsic
4324   TargetLowering::IntrinsicInfo Info;
4325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4326   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
4327                                                DAG.getMachineFunction(),
4328                                                Intrinsic);
4329 
4330   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
4331   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
4332       Info.opc == ISD::INTRINSIC_W_CHAIN)
4333     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
4334                                         TLI.getPointerTy(DAG.getDataLayout())));
4335 
4336   // Add all operands of the call to the operand list.
4337   for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
4338     SDValue Op = getValue(I.getArgOperand(i));
4339     Ops.push_back(Op);
4340   }
4341 
4342   SmallVector<EVT, 4> ValueVTs;
4343   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
4344 
4345   if (HasChain)
4346     ValueVTs.push_back(MVT::Other);
4347 
4348   SDVTList VTs = DAG.getVTList(ValueVTs);
4349 
4350   // Create the node.
4351   SDValue Result;
4352   if (IsTgtIntrinsic) {
4353     // This is target intrinsic that touches memory
4354     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs,
4355       Ops, Info.memVT,
4356       MachinePointerInfo(Info.ptrVal, Info.offset), Info.align,
4357       Info.flags, Info.size);
4358   } else if (!HasChain) {
4359     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
4360   } else if (!I.getType()->isVoidTy()) {
4361     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
4362   } else {
4363     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
4364   }
4365 
4366   if (HasChain) {
4367     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
4368     if (OnlyLoad)
4369       PendingLoads.push_back(Chain);
4370     else
4371       DAG.setRoot(Chain);
4372   }
4373 
4374   if (!I.getType()->isVoidTy()) {
4375     if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
4376       EVT VT = TLI.getValueType(DAG.getDataLayout(), PTy);
4377       Result = DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT, Result);
4378     } else
4379       Result = lowerRangeToAssertZExt(DAG, I, Result);
4380 
4381     setValue(&I, Result);
4382   }
4383 }
4384 
4385 /// GetSignificand - Get the significand and build it into a floating-point
4386 /// number with exponent of 1:
4387 ///
4388 ///   Op = (Op & 0x007fffff) | 0x3f800000;
4389 ///
4390 /// where Op is the hexadecimal representation of floating point value.
4391 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
4392   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4393                            DAG.getConstant(0x007fffff, dl, MVT::i32));
4394   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
4395                            DAG.getConstant(0x3f800000, dl, MVT::i32));
4396   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
4397 }
4398 
4399 /// GetExponent - Get the exponent:
4400 ///
4401 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
4402 ///
4403 /// where Op is the hexadecimal representation of floating point value.
4404 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
4405                            const TargetLowering &TLI, const SDLoc &dl) {
4406   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
4407                            DAG.getConstant(0x7f800000, dl, MVT::i32));
4408   SDValue t1 = DAG.getNode(
4409       ISD::SRL, dl, MVT::i32, t0,
4410       DAG.getConstant(23, dl, TLI.getPointerTy(DAG.getDataLayout())));
4411   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
4412                            DAG.getConstant(127, dl, MVT::i32));
4413   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
4414 }
4415 
4416 /// getF32Constant - Get 32-bit floating point constant.
4417 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
4418                               const SDLoc &dl) {
4419   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
4420                            MVT::f32);
4421 }
4422 
4423 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
4424                                        SelectionDAG &DAG) {
4425   // TODO: What fast-math-flags should be set on the floating-point nodes?
4426 
4427   //   IntegerPartOfX = ((int32_t)(t0);
4428   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
4429 
4430   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
4431   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4432   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
4433 
4434   //   IntegerPartOfX <<= 23;
4435   IntegerPartOfX = DAG.getNode(
4436       ISD::SHL, dl, MVT::i32, IntegerPartOfX,
4437       DAG.getConstant(23, dl, DAG.getTargetLoweringInfo().getPointerTy(
4438                                   DAG.getDataLayout())));
4439 
4440   SDValue TwoToFractionalPartOfX;
4441   if (LimitFloatPrecision <= 6) {
4442     // For floating-point precision of 6:
4443     //
4444     //   TwoToFractionalPartOfX =
4445     //     0.997535578f +
4446     //       (0.735607626f + 0.252464424f * x) * x;
4447     //
4448     // error 0.0144103317, which is 6 bits
4449     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4450                              getF32Constant(DAG, 0x3e814304, dl));
4451     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4452                              getF32Constant(DAG, 0x3f3c50c8, dl));
4453     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4454     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4455                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
4456   } else if (LimitFloatPrecision <= 12) {
4457     // For floating-point precision of 12:
4458     //
4459     //   TwoToFractionalPartOfX =
4460     //     0.999892986f +
4461     //       (0.696457318f +
4462     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
4463     //
4464     // error 0.000107046256, which is 13 to 14 bits
4465     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4466                              getF32Constant(DAG, 0x3da235e3, dl));
4467     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4468                              getF32Constant(DAG, 0x3e65b8f3, dl));
4469     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4470     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4471                              getF32Constant(DAG, 0x3f324b07, dl));
4472     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4473     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4474                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
4475   } else { // LimitFloatPrecision <= 18
4476     // For floating-point precision of 18:
4477     //
4478     //   TwoToFractionalPartOfX =
4479     //     0.999999982f +
4480     //       (0.693148872f +
4481     //         (0.240227044f +
4482     //           (0.554906021e-1f +
4483     //             (0.961591928e-2f +
4484     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4485     // error 2.47208000*10^(-7), which is better than 18 bits
4486     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4487                              getF32Constant(DAG, 0x3924b03e, dl));
4488     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4489                              getF32Constant(DAG, 0x3ab24b87, dl));
4490     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4491     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4492                              getF32Constant(DAG, 0x3c1d8c17, dl));
4493     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4494     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4495                              getF32Constant(DAG, 0x3d634a1d, dl));
4496     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4497     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4498                              getF32Constant(DAG, 0x3e75fe14, dl));
4499     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4500     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4501                               getF32Constant(DAG, 0x3f317234, dl));
4502     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4503     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4504                                          getF32Constant(DAG, 0x3f800000, dl));
4505   }
4506 
4507   // Add the exponent into the result in integer domain.
4508   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
4509   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4510                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
4511 }
4512 
4513 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
4514 /// limited-precision mode.
4515 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4516                          const TargetLowering &TLI) {
4517   if (Op.getValueType() == MVT::f32 &&
4518       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4519 
4520     // Put the exponent in the right bit position for later addition to the
4521     // final result:
4522     //
4523     //   #define LOG2OFe 1.4426950f
4524     //   t0 = Op * LOG2OFe
4525 
4526     // TODO: What fast-math-flags should be set here?
4527     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
4528                              getF32Constant(DAG, 0x3fb8aa3b, dl));
4529     return getLimitedPrecisionExp2(t0, dl, DAG);
4530   }
4531 
4532   // No special expansion.
4533   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
4534 }
4535 
4536 /// expandLog - Lower a log intrinsic. Handles the special sequences for
4537 /// limited-precision mode.
4538 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4539                          const TargetLowering &TLI) {
4540   // TODO: What fast-math-flags should be set on the floating-point nodes?
4541 
4542   if (Op.getValueType() == MVT::f32 &&
4543       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4544     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4545 
4546     // Scale the exponent by log(2) [0.69314718f].
4547     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4548     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4549                                         getF32Constant(DAG, 0x3f317218, dl));
4550 
4551     // Get the significand and build it into a floating-point number with
4552     // exponent of 1.
4553     SDValue X = GetSignificand(DAG, Op1, dl);
4554 
4555     SDValue LogOfMantissa;
4556     if (LimitFloatPrecision <= 6) {
4557       // For floating-point precision of 6:
4558       //
4559       //   LogofMantissa =
4560       //     -1.1609546f +
4561       //       (1.4034025f - 0.23903021f * x) * x;
4562       //
4563       // error 0.0034276066, which is better than 8 bits
4564       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4565                                getF32Constant(DAG, 0xbe74c456, dl));
4566       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4567                                getF32Constant(DAG, 0x3fb3a2b1, dl));
4568       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4569       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4570                                   getF32Constant(DAG, 0x3f949a29, dl));
4571     } else if (LimitFloatPrecision <= 12) {
4572       // For floating-point precision of 12:
4573       //
4574       //   LogOfMantissa =
4575       //     -1.7417939f +
4576       //       (2.8212026f +
4577       //         (-1.4699568f +
4578       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
4579       //
4580       // error 0.000061011436, which is 14 bits
4581       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4582                                getF32Constant(DAG, 0xbd67b6d6, dl));
4583       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4584                                getF32Constant(DAG, 0x3ee4f4b8, dl));
4585       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4586       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4587                                getF32Constant(DAG, 0x3fbc278b, dl));
4588       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4589       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4590                                getF32Constant(DAG, 0x40348e95, dl));
4591       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4592       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4593                                   getF32Constant(DAG, 0x3fdef31a, dl));
4594     } else { // LimitFloatPrecision <= 18
4595       // For floating-point precision of 18:
4596       //
4597       //   LogOfMantissa =
4598       //     -2.1072184f +
4599       //       (4.2372794f +
4600       //         (-3.7029485f +
4601       //           (2.2781945f +
4602       //             (-0.87823314f +
4603       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
4604       //
4605       // error 0.0000023660568, which is better than 18 bits
4606       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4607                                getF32Constant(DAG, 0xbc91e5ac, dl));
4608       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4609                                getF32Constant(DAG, 0x3e4350aa, dl));
4610       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4611       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4612                                getF32Constant(DAG, 0x3f60d3e3, dl));
4613       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4614       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4615                                getF32Constant(DAG, 0x4011cdf0, dl));
4616       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4617       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4618                                getF32Constant(DAG, 0x406cfd1c, dl));
4619       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4620       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4621                                getF32Constant(DAG, 0x408797cb, dl));
4622       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4623       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4624                                   getF32Constant(DAG, 0x4006dcab, dl));
4625     }
4626 
4627     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
4628   }
4629 
4630   // No special expansion.
4631   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
4632 }
4633 
4634 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
4635 /// limited-precision mode.
4636 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4637                           const TargetLowering &TLI) {
4638   // TODO: What fast-math-flags should be set on the floating-point nodes?
4639 
4640   if (Op.getValueType() == MVT::f32 &&
4641       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4642     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4643 
4644     // Get the exponent.
4645     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
4646 
4647     // Get the significand and build it into a floating-point number with
4648     // exponent of 1.
4649     SDValue X = GetSignificand(DAG, Op1, dl);
4650 
4651     // Different possible minimax approximations of significand in
4652     // floating-point for various degrees of accuracy over [1,2].
4653     SDValue Log2ofMantissa;
4654     if (LimitFloatPrecision <= 6) {
4655       // For floating-point precision of 6:
4656       //
4657       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
4658       //
4659       // error 0.0049451742, which is more than 7 bits
4660       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4661                                getF32Constant(DAG, 0xbeb08fe0, dl));
4662       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4663                                getF32Constant(DAG, 0x40019463, dl));
4664       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4665       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4666                                    getF32Constant(DAG, 0x3fd6633d, dl));
4667     } else if (LimitFloatPrecision <= 12) {
4668       // For floating-point precision of 12:
4669       //
4670       //   Log2ofMantissa =
4671       //     -2.51285454f +
4672       //       (4.07009056f +
4673       //         (-2.12067489f +
4674       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
4675       //
4676       // error 0.0000876136000, which is better than 13 bits
4677       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4678                                getF32Constant(DAG, 0xbda7262e, dl));
4679       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4680                                getF32Constant(DAG, 0x3f25280b, dl));
4681       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4682       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4683                                getF32Constant(DAG, 0x4007b923, dl));
4684       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4685       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4686                                getF32Constant(DAG, 0x40823e2f, dl));
4687       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4688       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4689                                    getF32Constant(DAG, 0x4020d29c, dl));
4690     } else { // LimitFloatPrecision <= 18
4691       // For floating-point precision of 18:
4692       //
4693       //   Log2ofMantissa =
4694       //     -3.0400495f +
4695       //       (6.1129976f +
4696       //         (-5.3420409f +
4697       //           (3.2865683f +
4698       //             (-1.2669343f +
4699       //               (0.27515199f -
4700       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
4701       //
4702       // error 0.0000018516, which is better than 18 bits
4703       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4704                                getF32Constant(DAG, 0xbcd2769e, dl));
4705       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4706                                getF32Constant(DAG, 0x3e8ce0b9, dl));
4707       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4708       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4709                                getF32Constant(DAG, 0x3fa22ae7, dl));
4710       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4711       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4712                                getF32Constant(DAG, 0x40525723, dl));
4713       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4714       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
4715                                getF32Constant(DAG, 0x40aaf200, dl));
4716       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4717       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4718                                getF32Constant(DAG, 0x40c39dad, dl));
4719       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4720       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4721                                    getF32Constant(DAG, 0x4042902c, dl));
4722     }
4723 
4724     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
4725   }
4726 
4727   // No special expansion.
4728   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
4729 }
4730 
4731 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
4732 /// limited-precision mode.
4733 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4734                            const TargetLowering &TLI) {
4735   // TODO: What fast-math-flags should be set on the floating-point nodes?
4736 
4737   if (Op.getValueType() == MVT::f32 &&
4738       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4739     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
4740 
4741     // Scale the exponent by log10(2) [0.30102999f].
4742     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
4743     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
4744                                         getF32Constant(DAG, 0x3e9a209a, dl));
4745 
4746     // Get the significand and build it into a floating-point number with
4747     // exponent of 1.
4748     SDValue X = GetSignificand(DAG, Op1, dl);
4749 
4750     SDValue Log10ofMantissa;
4751     if (LimitFloatPrecision <= 6) {
4752       // For floating-point precision of 6:
4753       //
4754       //   Log10ofMantissa =
4755       //     -0.50419619f +
4756       //       (0.60948995f - 0.10380950f * x) * x;
4757       //
4758       // error 0.0014886165, which is 6 bits
4759       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4760                                getF32Constant(DAG, 0xbdd49a13, dl));
4761       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
4762                                getF32Constant(DAG, 0x3f1c0789, dl));
4763       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4764       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4765                                     getF32Constant(DAG, 0x3f011300, dl));
4766     } else if (LimitFloatPrecision <= 12) {
4767       // For floating-point precision of 12:
4768       //
4769       //   Log10ofMantissa =
4770       //     -0.64831180f +
4771       //       (0.91751397f +
4772       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4773       //
4774       // error 0.00019228036, which is better than 12 bits
4775       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4776                                getF32Constant(DAG, 0x3d431f31, dl));
4777       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4778                                getF32Constant(DAG, 0x3ea21fb2, dl));
4779       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4780       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4781                                getF32Constant(DAG, 0x3f6ae232, dl));
4782       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4783       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4784                                     getF32Constant(DAG, 0x3f25f7c3, dl));
4785     } else { // LimitFloatPrecision <= 18
4786       // For floating-point precision of 18:
4787       //
4788       //   Log10ofMantissa =
4789       //     -0.84299375f +
4790       //       (1.5327582f +
4791       //         (-1.0688956f +
4792       //           (0.49102474f +
4793       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4794       //
4795       // error 0.0000037995730, which is better than 18 bits
4796       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
4797                                getF32Constant(DAG, 0x3c5d51ce, dl));
4798       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
4799                                getF32Constant(DAG, 0x3e00685a, dl));
4800       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4801       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
4802                                getF32Constant(DAG, 0x3efb6798, dl));
4803       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4804       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4805                                getF32Constant(DAG, 0x3f88d192, dl));
4806       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4807       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4808                                getF32Constant(DAG, 0x3fc4316c, dl));
4809       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4810       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4811                                     getF32Constant(DAG, 0x3f57ce70, dl));
4812     }
4813 
4814     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
4815   }
4816 
4817   // No special expansion.
4818   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
4819 }
4820 
4821 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4822 /// limited-precision mode.
4823 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
4824                           const TargetLowering &TLI) {
4825   if (Op.getValueType() == MVT::f32 &&
4826       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
4827     return getLimitedPrecisionExp2(Op, dl, DAG);
4828 
4829   // No special expansion.
4830   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
4831 }
4832 
4833 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
4834 /// limited-precision mode with x == 10.0f.
4835 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
4836                          SelectionDAG &DAG, const TargetLowering &TLI) {
4837   bool IsExp10 = false;
4838   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
4839       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4840     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4841       APFloat Ten(10.0f);
4842       IsExp10 = LHSC->isExactlyValue(Ten);
4843     }
4844   }
4845 
4846   // TODO: What fast-math-flags should be set on the FMUL node?
4847   if (IsExp10) {
4848     // Put the exponent in the right bit position for later addition to the
4849     // final result:
4850     //
4851     //   #define LOG2OF10 3.3219281f
4852     //   t0 = Op * LOG2OF10;
4853     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
4854                              getF32Constant(DAG, 0x40549a78, dl));
4855     return getLimitedPrecisionExp2(t0, dl, DAG);
4856   }
4857 
4858   // No special expansion.
4859   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
4860 }
4861 
4862 /// ExpandPowI - Expand a llvm.powi intrinsic.
4863 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
4864                           SelectionDAG &DAG) {
4865   // If RHS is a constant, we can expand this out to a multiplication tree,
4866   // otherwise we end up lowering to a call to __powidf2 (for example).  When
4867   // optimizing for size, we only want to do this if the expansion would produce
4868   // a small number of multiplies, otherwise we do the full expansion.
4869   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4870     // Get the exponent as a positive value.
4871     unsigned Val = RHSC->getSExtValue();
4872     if ((int)Val < 0) Val = -Val;
4873 
4874     // powi(x, 0) -> 1.0
4875     if (Val == 0)
4876       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
4877 
4878     const Function &F = DAG.getMachineFunction().getFunction();
4879     if (!F.optForSize() ||
4880         // If optimizing for size, don't insert too many multiplies.
4881         // This inserts up to 5 multiplies.
4882         countPopulation(Val) + Log2_32(Val) < 7) {
4883       // We use the simple binary decomposition method to generate the multiply
4884       // sequence.  There are more optimal ways to do this (for example,
4885       // powi(x,15) generates one more multiply than it should), but this has
4886       // the benefit of being both really simple and much better than a libcall.
4887       SDValue Res;  // Logically starts equal to 1.0
4888       SDValue CurSquare = LHS;
4889       // TODO: Intrinsics should have fast-math-flags that propagate to these
4890       // nodes.
4891       while (Val) {
4892         if (Val & 1) {
4893           if (Res.getNode())
4894             Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4895           else
4896             Res = CurSquare;  // 1.0*CurSquare.
4897         }
4898 
4899         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4900                                 CurSquare, CurSquare);
4901         Val >>= 1;
4902       }
4903 
4904       // If the original was negative, invert the result, producing 1/(x*x*x).
4905       if (RHSC->getSExtValue() < 0)
4906         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4907                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
4908       return Res;
4909     }
4910   }
4911 
4912   // Otherwise, expand to a libcall.
4913   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4914 }
4915 
4916 // getUnderlyingArgReg - Find underlying register used for a truncated or
4917 // bitcasted argument.
4918 static unsigned getUnderlyingArgReg(const SDValue &N) {
4919   switch (N.getOpcode()) {
4920   case ISD::CopyFromReg:
4921     return cast<RegisterSDNode>(N.getOperand(1))->getReg();
4922   case ISD::BITCAST:
4923   case ISD::AssertZext:
4924   case ISD::AssertSext:
4925   case ISD::TRUNCATE:
4926     return getUnderlyingArgReg(N.getOperand(0));
4927   default:
4928     return 0;
4929   }
4930 }
4931 
4932 /// If the DbgValueInst is a dbg_value of a function argument, create the
4933 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
4934 /// instruction selection, they will be inserted to the entry BB.
4935 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
4936     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
4937     DILocation *DL, bool IsDbgDeclare, const SDValue &N) {
4938   const Argument *Arg = dyn_cast<Argument>(V);
4939   if (!Arg)
4940     return false;
4941 
4942   MachineFunction &MF = DAG.getMachineFunction();
4943   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
4944 
4945   bool IsIndirect = false;
4946   Optional<MachineOperand> Op;
4947   // Some arguments' frame index is recorded during argument lowering.
4948   int FI = FuncInfo.getArgumentFrameIndex(Arg);
4949   if (FI != std::numeric_limits<int>::max())
4950     Op = MachineOperand::CreateFI(FI);
4951 
4952   if (!Op && N.getNode()) {
4953     unsigned Reg = getUnderlyingArgReg(N);
4954     if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4955       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4956       unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4957       if (PR)
4958         Reg = PR;
4959     }
4960     if (Reg) {
4961       Op = MachineOperand::CreateReg(Reg, false);
4962       IsIndirect = IsDbgDeclare;
4963     }
4964   }
4965 
4966   if (!Op && N.getNode())
4967     // Check if frame index is available.
4968     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4969       if (FrameIndexSDNode *FINode =
4970           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
4971         Op = MachineOperand::CreateFI(FINode->getIndex());
4972 
4973   if (!Op) {
4974     // Check if ValueMap has reg number.
4975     DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4976     if (VMI != FuncInfo.ValueMap.end()) {
4977       const auto &TLI = DAG.getTargetLoweringInfo();
4978       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
4979                        V->getType(), getABIRegCopyCC(V));
4980       if (RFV.occupiesMultipleRegs()) {
4981         unsigned Offset = 0;
4982         for (auto RegAndSize : RFV.getRegsAndSizes()) {
4983           Op = MachineOperand::CreateReg(RegAndSize.first, false);
4984           auto FragmentExpr = DIExpression::createFragmentExpression(
4985               Expr, Offset, RegAndSize.second);
4986           if (!FragmentExpr)
4987             continue;
4988           FuncInfo.ArgDbgValues.push_back(
4989               BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsDbgDeclare,
4990                       Op->getReg(), Variable, *FragmentExpr));
4991           Offset += RegAndSize.second;
4992         }
4993         return true;
4994       }
4995       Op = MachineOperand::CreateReg(VMI->second, false);
4996       IsIndirect = IsDbgDeclare;
4997     }
4998   }
4999 
5000   if (!Op)
5001     return false;
5002 
5003   assert(Variable->isValidLocationForIntrinsic(DL) &&
5004          "Expected inlined-at fields to agree");
5005   IsIndirect = (Op->isReg()) ? IsIndirect : true;
5006   FuncInfo.ArgDbgValues.push_back(
5007       BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
5008               *Op, Variable, Expr));
5009 
5010   return true;
5011 }
5012 
5013 /// Return the appropriate SDDbgValue based on N.
5014 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
5015                                              DILocalVariable *Variable,
5016                                              DIExpression *Expr,
5017                                              const DebugLoc &dl,
5018                                              unsigned DbgSDNodeOrder) {
5019   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
5020     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
5021     // stack slot locations.
5022     //
5023     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
5024     // debug values here after optimization:
5025     //
5026     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
5027     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
5028     //
5029     // Both describe the direct values of their associated variables.
5030     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
5031                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5032   }
5033   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
5034                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
5035 }
5036 
5037 // VisualStudio defines setjmp as _setjmp
5038 #if defined(_MSC_VER) && defined(setjmp) && \
5039                          !defined(setjmp_undefined_for_msvc)
5040 #  pragma push_macro("setjmp")
5041 #  undef setjmp
5042 #  define setjmp_undefined_for_msvc
5043 #endif
5044 
5045 /// Lower the call to the specified intrinsic function. If we want to emit this
5046 /// as a call to a named external function, return the name. Otherwise, lower it
5047 /// and return null.
5048 const char *
5049 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
5050   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5051   SDLoc sdl = getCurSDLoc();
5052   DebugLoc dl = getCurDebugLoc();
5053   SDValue Res;
5054 
5055   switch (Intrinsic) {
5056   default:
5057     // By default, turn this into a target intrinsic node.
5058     visitTargetIntrinsic(I, Intrinsic);
5059     return nullptr;
5060   case Intrinsic::vastart:  visitVAStart(I); return nullptr;
5061   case Intrinsic::vaend:    visitVAEnd(I); return nullptr;
5062   case Intrinsic::vacopy:   visitVACopy(I); return nullptr;
5063   case Intrinsic::returnaddress:
5064     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
5065                              TLI.getPointerTy(DAG.getDataLayout()),
5066                              getValue(I.getArgOperand(0))));
5067     return nullptr;
5068   case Intrinsic::addressofreturnaddress:
5069     setValue(&I, DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
5070                              TLI.getPointerTy(DAG.getDataLayout())));
5071     return nullptr;
5072   case Intrinsic::sponentry:
5073     setValue(&I, DAG.getNode(ISD::SPONENTRY, sdl,
5074                              TLI.getPointerTy(DAG.getDataLayout())));
5075     return nullptr;
5076   case Intrinsic::frameaddress:
5077     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
5078                              TLI.getPointerTy(DAG.getDataLayout()),
5079                              getValue(I.getArgOperand(0))));
5080     return nullptr;
5081   case Intrinsic::read_register: {
5082     Value *Reg = I.getArgOperand(0);
5083     SDValue Chain = getRoot();
5084     SDValue RegName =
5085         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5086     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5087     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
5088       DAG.getVTList(VT, MVT::Other), Chain, RegName);
5089     setValue(&I, Res);
5090     DAG.setRoot(Res.getValue(1));
5091     return nullptr;
5092   }
5093   case Intrinsic::write_register: {
5094     Value *Reg = I.getArgOperand(0);
5095     Value *RegValue = I.getArgOperand(1);
5096     SDValue Chain = getRoot();
5097     SDValue RegName =
5098         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
5099     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
5100                             RegName, getValue(RegValue)));
5101     return nullptr;
5102   }
5103   case Intrinsic::setjmp:
5104     return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
5105   case Intrinsic::longjmp:
5106     return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
5107   case Intrinsic::memcpy: {
5108     const auto &MCI = cast<MemCpyInst>(I);
5109     SDValue Op1 = getValue(I.getArgOperand(0));
5110     SDValue Op2 = getValue(I.getArgOperand(1));
5111     SDValue Op3 = getValue(I.getArgOperand(2));
5112     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
5113     unsigned DstAlign = std::max<unsigned>(MCI.getDestAlignment(), 1);
5114     unsigned SrcAlign = std::max<unsigned>(MCI.getSourceAlignment(), 1);
5115     unsigned Align = MinAlign(DstAlign, SrcAlign);
5116     bool isVol = MCI.isVolatile();
5117     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5118     // FIXME: Support passing different dest/src alignments to the memcpy DAG
5119     // node.
5120     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5121                                false, isTC,
5122                                MachinePointerInfo(I.getArgOperand(0)),
5123                                MachinePointerInfo(I.getArgOperand(1)));
5124     updateDAGForMaybeTailCall(MC);
5125     return nullptr;
5126   }
5127   case Intrinsic::memset: {
5128     const auto &MSI = cast<MemSetInst>(I);
5129     SDValue Op1 = getValue(I.getArgOperand(0));
5130     SDValue Op2 = getValue(I.getArgOperand(1));
5131     SDValue Op3 = getValue(I.getArgOperand(2));
5132     // @llvm.memset defines 0 and 1 to both mean no alignment.
5133     unsigned Align = std::max<unsigned>(MSI.getDestAlignment(), 1);
5134     bool isVol = MSI.isVolatile();
5135     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5136     SDValue MS = DAG.getMemset(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5137                                isTC, MachinePointerInfo(I.getArgOperand(0)));
5138     updateDAGForMaybeTailCall(MS);
5139     return nullptr;
5140   }
5141   case Intrinsic::memmove: {
5142     const auto &MMI = cast<MemMoveInst>(I);
5143     SDValue Op1 = getValue(I.getArgOperand(0));
5144     SDValue Op2 = getValue(I.getArgOperand(1));
5145     SDValue Op3 = getValue(I.getArgOperand(2));
5146     // @llvm.memmove defines 0 and 1 to both mean no alignment.
5147     unsigned DstAlign = std::max<unsigned>(MMI.getDestAlignment(), 1);
5148     unsigned SrcAlign = std::max<unsigned>(MMI.getSourceAlignment(), 1);
5149     unsigned Align = MinAlign(DstAlign, SrcAlign);
5150     bool isVol = MMI.isVolatile();
5151     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5152     // FIXME: Support passing different dest/src alignments to the memmove DAG
5153     // node.
5154     SDValue MM = DAG.getMemmove(getRoot(), sdl, Op1, Op2, Op3, Align, isVol,
5155                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
5156                                 MachinePointerInfo(I.getArgOperand(1)));
5157     updateDAGForMaybeTailCall(MM);
5158     return nullptr;
5159   }
5160   case Intrinsic::memcpy_element_unordered_atomic: {
5161     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
5162     SDValue Dst = getValue(MI.getRawDest());
5163     SDValue Src = getValue(MI.getRawSource());
5164     SDValue Length = getValue(MI.getLength());
5165 
5166     unsigned DstAlign = MI.getDestAlignment();
5167     unsigned SrcAlign = MI.getSourceAlignment();
5168     Type *LengthTy = MI.getLength()->getType();
5169     unsigned ElemSz = MI.getElementSizeInBytes();
5170     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5171     SDValue MC = DAG.getAtomicMemcpy(getRoot(), sdl, Dst, DstAlign, Src,
5172                                      SrcAlign, Length, LengthTy, ElemSz, isTC,
5173                                      MachinePointerInfo(MI.getRawDest()),
5174                                      MachinePointerInfo(MI.getRawSource()));
5175     updateDAGForMaybeTailCall(MC);
5176     return nullptr;
5177   }
5178   case Intrinsic::memmove_element_unordered_atomic: {
5179     auto &MI = cast<AtomicMemMoveInst>(I);
5180     SDValue Dst = getValue(MI.getRawDest());
5181     SDValue Src = getValue(MI.getRawSource());
5182     SDValue Length = getValue(MI.getLength());
5183 
5184     unsigned DstAlign = MI.getDestAlignment();
5185     unsigned SrcAlign = MI.getSourceAlignment();
5186     Type *LengthTy = MI.getLength()->getType();
5187     unsigned ElemSz = MI.getElementSizeInBytes();
5188     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5189     SDValue MC = DAG.getAtomicMemmove(getRoot(), sdl, Dst, DstAlign, Src,
5190                                       SrcAlign, Length, LengthTy, ElemSz, isTC,
5191                                       MachinePointerInfo(MI.getRawDest()),
5192                                       MachinePointerInfo(MI.getRawSource()));
5193     updateDAGForMaybeTailCall(MC);
5194     return nullptr;
5195   }
5196   case Intrinsic::memset_element_unordered_atomic: {
5197     auto &MI = cast<AtomicMemSetInst>(I);
5198     SDValue Dst = getValue(MI.getRawDest());
5199     SDValue Val = getValue(MI.getValue());
5200     SDValue Length = getValue(MI.getLength());
5201 
5202     unsigned DstAlign = MI.getDestAlignment();
5203     Type *LengthTy = MI.getLength()->getType();
5204     unsigned ElemSz = MI.getElementSizeInBytes();
5205     bool isTC = I.isTailCall() && isInTailCallPosition(&I, DAG.getTarget());
5206     SDValue MC = DAG.getAtomicMemset(getRoot(), sdl, Dst, DstAlign, Val, Length,
5207                                      LengthTy, ElemSz, isTC,
5208                                      MachinePointerInfo(MI.getRawDest()));
5209     updateDAGForMaybeTailCall(MC);
5210     return nullptr;
5211   }
5212   case Intrinsic::dbg_addr:
5213   case Intrinsic::dbg_declare: {
5214     const auto &DI = cast<DbgVariableIntrinsic>(I);
5215     DILocalVariable *Variable = DI.getVariable();
5216     DIExpression *Expression = DI.getExpression();
5217     dropDanglingDebugInfo(Variable, Expression);
5218     assert(Variable && "Missing variable");
5219 
5220     // Check if address has undef value.
5221     const Value *Address = DI.getVariableLocation();
5222     if (!Address || isa<UndefValue>(Address) ||
5223         (Address->use_empty() && !isa<Argument>(Address))) {
5224       LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5225       return nullptr;
5226     }
5227 
5228     bool isParameter = Variable->isParameter() || isa<Argument>(Address);
5229 
5230     // Check if this variable can be described by a frame index, typically
5231     // either as a static alloca or a byval parameter.
5232     int FI = std::numeric_limits<int>::max();
5233     if (const auto *AI =
5234             dyn_cast<AllocaInst>(Address->stripInBoundsConstantOffsets())) {
5235       if (AI->isStaticAlloca()) {
5236         auto I = FuncInfo.StaticAllocaMap.find(AI);
5237         if (I != FuncInfo.StaticAllocaMap.end())
5238           FI = I->second;
5239       }
5240     } else if (const auto *Arg = dyn_cast<Argument>(
5241                    Address->stripInBoundsConstantOffsets())) {
5242       FI = FuncInfo.getArgumentFrameIndex(Arg);
5243     }
5244 
5245     // llvm.dbg.addr is control dependent and always generates indirect
5246     // DBG_VALUE instructions. llvm.dbg.declare is handled as a frame index in
5247     // the MachineFunction variable table.
5248     if (FI != std::numeric_limits<int>::max()) {
5249       if (Intrinsic == Intrinsic::dbg_addr) {
5250         SDDbgValue *SDV = DAG.getFrameIndexDbgValue(
5251             Variable, Expression, FI, /*IsIndirect*/ true, dl, SDNodeOrder);
5252         DAG.AddDbgValue(SDV, getRoot().getNode(), isParameter);
5253       }
5254       return nullptr;
5255     }
5256 
5257     SDValue &N = NodeMap[Address];
5258     if (!N.getNode() && isa<Argument>(Address))
5259       // Check unused arguments map.
5260       N = UnusedArgNodeMap[Address];
5261     SDDbgValue *SDV;
5262     if (N.getNode()) {
5263       if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
5264         Address = BCI->getOperand(0);
5265       // Parameters are handled specially.
5266       auto FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
5267       if (isParameter && FINode) {
5268         // Byval parameter. We have a frame index at this point.
5269         SDV =
5270             DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
5271                                       /*IsIndirect*/ true, dl, SDNodeOrder);
5272       } else if (isa<Argument>(Address)) {
5273         // Address is an argument, so try to emit its dbg value using
5274         // virtual register info from the FuncInfo.ValueMap.
5275         EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true, N);
5276         return nullptr;
5277       } else {
5278         SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
5279                               true, dl, SDNodeOrder);
5280       }
5281       DAG.AddDbgValue(SDV, N.getNode(), isParameter);
5282     } else {
5283       // If Address is an argument then try to emit its dbg value using
5284       // virtual register info from the FuncInfo.ValueMap.
5285       if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, dl, true,
5286                                     N)) {
5287         LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
5288       }
5289     }
5290     return nullptr;
5291   }
5292   case Intrinsic::dbg_label: {
5293     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
5294     DILabel *Label = DI.getLabel();
5295     assert(Label && "Missing label");
5296 
5297     SDDbgLabel *SDV;
5298     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
5299     DAG.AddDbgLabel(SDV);
5300     return nullptr;
5301   }
5302   case Intrinsic::dbg_value: {
5303     const DbgValueInst &DI = cast<DbgValueInst>(I);
5304     assert(DI.getVariable() && "Missing variable");
5305 
5306     DILocalVariable *Variable = DI.getVariable();
5307     DIExpression *Expression = DI.getExpression();
5308     dropDanglingDebugInfo(Variable, Expression);
5309     const Value *V = DI.getValue();
5310     if (!V)
5311       return nullptr;
5312 
5313     SDDbgValue *SDV;
5314     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
5315         isa<ConstantPointerNull>(V)) {
5316       SDV = DAG.getConstantDbgValue(Variable, Expression, V, dl, SDNodeOrder);
5317       DAG.AddDbgValue(SDV, nullptr, false);
5318       return nullptr;
5319     }
5320 
5321     // Do not use getValue() in here; we don't want to generate code at
5322     // this point if it hasn't been done yet.
5323     SDValue N = NodeMap[V];
5324     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
5325       N = UnusedArgNodeMap[V];
5326     if (N.getNode()) {
5327       if (EmitFuncArgumentDbgValue(V, Variable, Expression, dl, false, N))
5328         return nullptr;
5329       SDV = getDbgValue(N, Variable, Expression, dl, SDNodeOrder);
5330       DAG.AddDbgValue(SDV, N.getNode(), false);
5331       return nullptr;
5332     }
5333 
5334     // The value is not used in this block yet (or it would have an SDNode).
5335     // We still want the value to appear for the user if possible -- if it has
5336     // an associated VReg, we can refer to that instead.
5337     if (!isa<Argument>(V)) {
5338       auto VMI = FuncInfo.ValueMap.find(V);
5339       if (VMI != FuncInfo.ValueMap.end()) {
5340         unsigned Reg = VMI->second;
5341         // If this is a PHI node, it may be split up into several MI PHI nodes
5342         // (in FunctionLoweringInfo::set).
5343         RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
5344                          V->getType(), None);
5345         if (RFV.occupiesMultipleRegs()) {
5346           unsigned Offset = 0;
5347           unsigned BitsToDescribe = 0;
5348           if (auto VarSize = Variable->getSizeInBits())
5349             BitsToDescribe = *VarSize;
5350           if (auto Fragment = Expression->getFragmentInfo())
5351             BitsToDescribe = Fragment->SizeInBits;
5352           for (auto RegAndSize : RFV.getRegsAndSizes()) {
5353             unsigned RegisterSize = RegAndSize.second;
5354             // Bail out if all bits are described already.
5355             if (Offset >= BitsToDescribe)
5356               break;
5357             unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
5358                 ? BitsToDescribe - Offset
5359                 : RegisterSize;
5360             auto FragmentExpr = DIExpression::createFragmentExpression(
5361                 Expression, Offset, FragmentSize);
5362             if (!FragmentExpr)
5363                 continue;
5364             SDV = DAG.getVRegDbgValue(Variable, *FragmentExpr, RegAndSize.first,
5365                                       false, dl, SDNodeOrder);
5366             DAG.AddDbgValue(SDV, nullptr, false);
5367             Offset += RegisterSize;
5368           }
5369         } else {
5370           SDV = DAG.getVRegDbgValue(Variable, Expression, Reg, false, dl,
5371                                     SDNodeOrder);
5372           DAG.AddDbgValue(SDV, nullptr, false);
5373         }
5374         return nullptr;
5375       }
5376     }
5377 
5378     // TODO: When we get here we will either drop the dbg.value completely, or
5379     // we try to move it forward by letting it dangle for awhile. So we should
5380     // probably add an extra DbgValue to the DAG here, with a reference to
5381     // "noreg", to indicate that we have lost the debug location for the
5382     // variable.
5383 
5384     if (!V->use_empty() ) {
5385       // Do not call getValue(V) yet, as we don't want to generate code.
5386       // Remember it for later.
5387       DanglingDebugInfoMap[V].emplace_back(&DI, dl, SDNodeOrder);
5388       return nullptr;
5389     }
5390 
5391     LLVM_DEBUG(dbgs() << "Dropping debug location info for:\n  " << DI << "\n");
5392     LLVM_DEBUG(dbgs() << "  Last seen at:\n    " << *V << "\n");
5393     return nullptr;
5394   }
5395 
5396   case Intrinsic::eh_typeid_for: {
5397     // Find the type id for the given typeinfo.
5398     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
5399     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
5400     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
5401     setValue(&I, Res);
5402     return nullptr;
5403   }
5404 
5405   case Intrinsic::eh_return_i32:
5406   case Intrinsic::eh_return_i64:
5407     DAG.getMachineFunction().setCallsEHReturn(true);
5408     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
5409                             MVT::Other,
5410                             getControlRoot(),
5411                             getValue(I.getArgOperand(0)),
5412                             getValue(I.getArgOperand(1))));
5413     return nullptr;
5414   case Intrinsic::eh_unwind_init:
5415     DAG.getMachineFunction().setCallsUnwindInit(true);
5416     return nullptr;
5417   case Intrinsic::eh_dwarf_cfa:
5418     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
5419                              TLI.getPointerTy(DAG.getDataLayout()),
5420                              getValue(I.getArgOperand(0))));
5421     return nullptr;
5422   case Intrinsic::eh_sjlj_callsite: {
5423     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5424     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
5425     assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
5426     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
5427 
5428     MMI.setCurrentCallSite(CI->getZExtValue());
5429     return nullptr;
5430   }
5431   case Intrinsic::eh_sjlj_functioncontext: {
5432     // Get and store the index of the function context.
5433     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
5434     AllocaInst *FnCtx =
5435       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
5436     int FI = FuncInfo.StaticAllocaMap[FnCtx];
5437     MFI.setFunctionContextIndex(FI);
5438     return nullptr;
5439   }
5440   case Intrinsic::eh_sjlj_setjmp: {
5441     SDValue Ops[2];
5442     Ops[0] = getRoot();
5443     Ops[1] = getValue(I.getArgOperand(0));
5444     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
5445                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
5446     setValue(&I, Op.getValue(0));
5447     DAG.setRoot(Op.getValue(1));
5448     return nullptr;
5449   }
5450   case Intrinsic::eh_sjlj_longjmp:
5451     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
5452                             getRoot(), getValue(I.getArgOperand(0))));
5453     return nullptr;
5454   case Intrinsic::eh_sjlj_setup_dispatch:
5455     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
5456                             getRoot()));
5457     return nullptr;
5458   case Intrinsic::masked_gather:
5459     visitMaskedGather(I);
5460     return nullptr;
5461   case Intrinsic::masked_load:
5462     visitMaskedLoad(I);
5463     return nullptr;
5464   case Intrinsic::masked_scatter:
5465     visitMaskedScatter(I);
5466     return nullptr;
5467   case Intrinsic::masked_store:
5468     visitMaskedStore(I);
5469     return nullptr;
5470   case Intrinsic::masked_expandload:
5471     visitMaskedLoad(I, true /* IsExpanding */);
5472     return nullptr;
5473   case Intrinsic::masked_compressstore:
5474     visitMaskedStore(I, true /* IsCompressing */);
5475     return nullptr;
5476   case Intrinsic::x86_mmx_pslli_w:
5477   case Intrinsic::x86_mmx_pslli_d:
5478   case Intrinsic::x86_mmx_pslli_q:
5479   case Intrinsic::x86_mmx_psrli_w:
5480   case Intrinsic::x86_mmx_psrli_d:
5481   case Intrinsic::x86_mmx_psrli_q:
5482   case Intrinsic::x86_mmx_psrai_w:
5483   case Intrinsic::x86_mmx_psrai_d: {
5484     SDValue ShAmt = getValue(I.getArgOperand(1));
5485     if (isa<ConstantSDNode>(ShAmt)) {
5486       visitTargetIntrinsic(I, Intrinsic);
5487       return nullptr;
5488     }
5489     unsigned NewIntrinsic = 0;
5490     EVT ShAmtVT = MVT::v2i32;
5491     switch (Intrinsic) {
5492     case Intrinsic::x86_mmx_pslli_w:
5493       NewIntrinsic = Intrinsic::x86_mmx_psll_w;
5494       break;
5495     case Intrinsic::x86_mmx_pslli_d:
5496       NewIntrinsic = Intrinsic::x86_mmx_psll_d;
5497       break;
5498     case Intrinsic::x86_mmx_pslli_q:
5499       NewIntrinsic = Intrinsic::x86_mmx_psll_q;
5500       break;
5501     case Intrinsic::x86_mmx_psrli_w:
5502       NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
5503       break;
5504     case Intrinsic::x86_mmx_psrli_d:
5505       NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
5506       break;
5507     case Intrinsic::x86_mmx_psrli_q:
5508       NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
5509       break;
5510     case Intrinsic::x86_mmx_psrai_w:
5511       NewIntrinsic = Intrinsic::x86_mmx_psra_w;
5512       break;
5513     case Intrinsic::x86_mmx_psrai_d:
5514       NewIntrinsic = Intrinsic::x86_mmx_psra_d;
5515       break;
5516     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5517     }
5518 
5519     // The vector shift intrinsics with scalars uses 32b shift amounts but
5520     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
5521     // to be zero.
5522     // We must do this early because v2i32 is not a legal type.
5523     SDValue ShOps[2];
5524     ShOps[0] = ShAmt;
5525     ShOps[1] = DAG.getConstant(0, sdl, MVT::i32);
5526     ShAmt =  DAG.getBuildVector(ShAmtVT, sdl, ShOps);
5527     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5528     ShAmt = DAG.getNode(ISD::BITCAST, sdl, DestVT, ShAmt);
5529     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, sdl, DestVT,
5530                        DAG.getConstant(NewIntrinsic, sdl, MVT::i32),
5531                        getValue(I.getArgOperand(0)), ShAmt);
5532     setValue(&I, Res);
5533     return nullptr;
5534   }
5535   case Intrinsic::powi:
5536     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
5537                             getValue(I.getArgOperand(1)), DAG));
5538     return nullptr;
5539   case Intrinsic::log:
5540     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5541     return nullptr;
5542   case Intrinsic::log2:
5543     setValue(&I, expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5544     return nullptr;
5545   case Intrinsic::log10:
5546     setValue(&I, expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5547     return nullptr;
5548   case Intrinsic::exp:
5549     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5550     return nullptr;
5551   case Intrinsic::exp2:
5552     setValue(&I, expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI));
5553     return nullptr;
5554   case Intrinsic::pow:
5555     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
5556                            getValue(I.getArgOperand(1)), DAG, TLI));
5557     return nullptr;
5558   case Intrinsic::sqrt:
5559   case Intrinsic::fabs:
5560   case Intrinsic::sin:
5561   case Intrinsic::cos:
5562   case Intrinsic::floor:
5563   case Intrinsic::ceil:
5564   case Intrinsic::trunc:
5565   case Intrinsic::rint:
5566   case Intrinsic::nearbyint:
5567   case Intrinsic::round:
5568   case Intrinsic::canonicalize: {
5569     unsigned Opcode;
5570     switch (Intrinsic) {
5571     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
5572     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
5573     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
5574     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
5575     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
5576     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
5577     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
5578     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
5579     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
5580     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
5581     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
5582     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
5583     }
5584 
5585     setValue(&I, DAG.getNode(Opcode, sdl,
5586                              getValue(I.getArgOperand(0)).getValueType(),
5587                              getValue(I.getArgOperand(0))));
5588     return nullptr;
5589   }
5590   case Intrinsic::minnum: {
5591     auto VT = getValue(I.getArgOperand(0)).getValueType();
5592     unsigned Opc =
5593         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMINIMUM, VT)
5594             ? ISD::FMINIMUM
5595             : ISD::FMINNUM;
5596     setValue(&I, DAG.getNode(Opc, sdl, VT,
5597                              getValue(I.getArgOperand(0)),
5598                              getValue(I.getArgOperand(1))));
5599     return nullptr;
5600   }
5601   case Intrinsic::maxnum: {
5602     auto VT = getValue(I.getArgOperand(0)).getValueType();
5603     unsigned Opc =
5604         I.hasNoNaNs() && TLI.isOperationLegalOrCustom(ISD::FMAXIMUM, VT)
5605             ? ISD::FMAXIMUM
5606             : ISD::FMAXNUM;
5607     setValue(&I, DAG.getNode(Opc, sdl, VT,
5608                              getValue(I.getArgOperand(0)),
5609                              getValue(I.getArgOperand(1))));
5610     return nullptr;
5611   }
5612   case Intrinsic::minimum:
5613     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
5614                              getValue(I.getArgOperand(0)).getValueType(),
5615                              getValue(I.getArgOperand(0)),
5616                              getValue(I.getArgOperand(1))));
5617     return nullptr;
5618   case Intrinsic::maximum:
5619     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
5620                              getValue(I.getArgOperand(0)).getValueType(),
5621                              getValue(I.getArgOperand(0)),
5622                              getValue(I.getArgOperand(1))));
5623     return nullptr;
5624   case Intrinsic::copysign:
5625     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
5626                              getValue(I.getArgOperand(0)).getValueType(),
5627                              getValue(I.getArgOperand(0)),
5628                              getValue(I.getArgOperand(1))));
5629     return nullptr;
5630   case Intrinsic::fma:
5631     setValue(&I, DAG.getNode(ISD::FMA, sdl,
5632                              getValue(I.getArgOperand(0)).getValueType(),
5633                              getValue(I.getArgOperand(0)),
5634                              getValue(I.getArgOperand(1)),
5635                              getValue(I.getArgOperand(2))));
5636     return nullptr;
5637   case Intrinsic::experimental_constrained_fadd:
5638   case Intrinsic::experimental_constrained_fsub:
5639   case Intrinsic::experimental_constrained_fmul:
5640   case Intrinsic::experimental_constrained_fdiv:
5641   case Intrinsic::experimental_constrained_frem:
5642   case Intrinsic::experimental_constrained_fma:
5643   case Intrinsic::experimental_constrained_sqrt:
5644   case Intrinsic::experimental_constrained_pow:
5645   case Intrinsic::experimental_constrained_powi:
5646   case Intrinsic::experimental_constrained_sin:
5647   case Intrinsic::experimental_constrained_cos:
5648   case Intrinsic::experimental_constrained_exp:
5649   case Intrinsic::experimental_constrained_exp2:
5650   case Intrinsic::experimental_constrained_log:
5651   case Intrinsic::experimental_constrained_log10:
5652   case Intrinsic::experimental_constrained_log2:
5653   case Intrinsic::experimental_constrained_rint:
5654   case Intrinsic::experimental_constrained_nearbyint:
5655   case Intrinsic::experimental_constrained_maxnum:
5656   case Intrinsic::experimental_constrained_minnum:
5657   case Intrinsic::experimental_constrained_ceil:
5658   case Intrinsic::experimental_constrained_floor:
5659   case Intrinsic::experimental_constrained_round:
5660   case Intrinsic::experimental_constrained_trunc:
5661     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
5662     return nullptr;
5663   case Intrinsic::fmuladd: {
5664     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5665     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
5666         TLI.isFMAFasterThanFMulAndFAdd(VT)) {
5667       setValue(&I, DAG.getNode(ISD::FMA, sdl,
5668                                getValue(I.getArgOperand(0)).getValueType(),
5669                                getValue(I.getArgOperand(0)),
5670                                getValue(I.getArgOperand(1)),
5671                                getValue(I.getArgOperand(2))));
5672     } else {
5673       // TODO: Intrinsic calls should have fast-math-flags.
5674       SDValue Mul = DAG.getNode(ISD::FMUL, sdl,
5675                                 getValue(I.getArgOperand(0)).getValueType(),
5676                                 getValue(I.getArgOperand(0)),
5677                                 getValue(I.getArgOperand(1)));
5678       SDValue Add = DAG.getNode(ISD::FADD, sdl,
5679                                 getValue(I.getArgOperand(0)).getValueType(),
5680                                 Mul,
5681                                 getValue(I.getArgOperand(2)));
5682       setValue(&I, Add);
5683     }
5684     return nullptr;
5685   }
5686   case Intrinsic::convert_to_fp16:
5687     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
5688                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
5689                                          getValue(I.getArgOperand(0)),
5690                                          DAG.getTargetConstant(0, sdl,
5691                                                                MVT::i32))));
5692     return nullptr;
5693   case Intrinsic::convert_from_fp16:
5694     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
5695                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
5696                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
5697                                          getValue(I.getArgOperand(0)))));
5698     return nullptr;
5699   case Intrinsic::pcmarker: {
5700     SDValue Tmp = getValue(I.getArgOperand(0));
5701     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
5702     return nullptr;
5703   }
5704   case Intrinsic::readcyclecounter: {
5705     SDValue Op = getRoot();
5706     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
5707                       DAG.getVTList(MVT::i64, MVT::Other), Op);
5708     setValue(&I, Res);
5709     DAG.setRoot(Res.getValue(1));
5710     return nullptr;
5711   }
5712   case Intrinsic::bitreverse:
5713     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
5714                              getValue(I.getArgOperand(0)).getValueType(),
5715                              getValue(I.getArgOperand(0))));
5716     return nullptr;
5717   case Intrinsic::bswap:
5718     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
5719                              getValue(I.getArgOperand(0)).getValueType(),
5720                              getValue(I.getArgOperand(0))));
5721     return nullptr;
5722   case Intrinsic::cttz: {
5723     SDValue Arg = getValue(I.getArgOperand(0));
5724     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5725     EVT Ty = Arg.getValueType();
5726     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5727                              sdl, Ty, Arg));
5728     return nullptr;
5729   }
5730   case Intrinsic::ctlz: {
5731     SDValue Arg = getValue(I.getArgOperand(0));
5732     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
5733     EVT Ty = Arg.getValueType();
5734     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5735                              sdl, Ty, Arg));
5736     return nullptr;
5737   }
5738   case Intrinsic::ctpop: {
5739     SDValue Arg = getValue(I.getArgOperand(0));
5740     EVT Ty = Arg.getValueType();
5741     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
5742     return nullptr;
5743   }
5744   case Intrinsic::fshl:
5745   case Intrinsic::fshr: {
5746     bool IsFSHL = Intrinsic == Intrinsic::fshl;
5747     SDValue X = getValue(I.getArgOperand(0));
5748     SDValue Y = getValue(I.getArgOperand(1));
5749     SDValue Z = getValue(I.getArgOperand(2));
5750     EVT VT = X.getValueType();
5751     SDValue BitWidthC = DAG.getConstant(VT.getScalarSizeInBits(), sdl, VT);
5752     SDValue Zero = DAG.getConstant(0, sdl, VT);
5753     SDValue ShAmt = DAG.getNode(ISD::UREM, sdl, VT, Z, BitWidthC);
5754 
5755     auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
5756     if (TLI.isOperationLegalOrCustom(FunnelOpcode, VT)) {
5757       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
5758       return nullptr;
5759     }
5760 
5761     // When X == Y, this is rotate. If the data type has a power-of-2 size, we
5762     // avoid the select that is necessary in the general case to filter out
5763     // the 0-shift possibility that leads to UB.
5764     if (X == Y && isPowerOf2_32(VT.getScalarSizeInBits())) {
5765       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
5766       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
5767         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
5768         return nullptr;
5769       }
5770 
5771       // Some targets only rotate one way. Try the opposite direction.
5772       RotateOpcode = IsFSHL ? ISD::ROTR : ISD::ROTL;
5773       if (TLI.isOperationLegalOrCustom(RotateOpcode, VT)) {
5774         // Negate the shift amount because it is safe to ignore the high bits.
5775         SDValue NegShAmt = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5776         setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, NegShAmt));
5777         return nullptr;
5778       }
5779 
5780       // fshl (rotl): (X << (Z % BW)) | (X >> ((0 - Z) % BW))
5781       // fshr (rotr): (X << ((0 - Z) % BW)) | (X >> (Z % BW))
5782       SDValue NegZ = DAG.getNode(ISD::SUB, sdl, VT, Zero, Z);
5783       SDValue NShAmt = DAG.getNode(ISD::UREM, sdl, VT, NegZ, BitWidthC);
5784       SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : NShAmt);
5785       SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, X, IsFSHL ? NShAmt : ShAmt);
5786       setValue(&I, DAG.getNode(ISD::OR, sdl, VT, ShX, ShY));
5787       return nullptr;
5788     }
5789 
5790     // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5791     // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5792     SDValue InvShAmt = DAG.getNode(ISD::SUB, sdl, VT, BitWidthC, ShAmt);
5793     SDValue ShX = DAG.getNode(ISD::SHL, sdl, VT, X, IsFSHL ? ShAmt : InvShAmt);
5794     SDValue ShY = DAG.getNode(ISD::SRL, sdl, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5795     SDValue Or = DAG.getNode(ISD::OR, sdl, VT, ShX, ShY);
5796 
5797     // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5798     // and that is undefined. We must compare and select to avoid UB.
5799     EVT CCVT = MVT::i1;
5800     if (VT.isVector())
5801       CCVT = EVT::getVectorVT(*Context, CCVT, VT.getVectorNumElements());
5802 
5803     // For fshl, 0-shift returns the 1st arg (X).
5804     // For fshr, 0-shift returns the 2nd arg (Y).
5805     SDValue IsZeroShift = DAG.getSetCC(sdl, CCVT, ShAmt, Zero, ISD::SETEQ);
5806     setValue(&I, DAG.getSelect(sdl, VT, IsZeroShift, IsFSHL ? X : Y, Or));
5807     return nullptr;
5808   }
5809   case Intrinsic::sadd_sat: {
5810     SDValue Op1 = getValue(I.getArgOperand(0));
5811     SDValue Op2 = getValue(I.getArgOperand(1));
5812     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5813     return nullptr;
5814   }
5815   case Intrinsic::uadd_sat: {
5816     SDValue Op1 = getValue(I.getArgOperand(0));
5817     SDValue Op2 = getValue(I.getArgOperand(1));
5818     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
5819     return nullptr;
5820   }
5821   case Intrinsic::ssub_sat: {
5822     SDValue Op1 = getValue(I.getArgOperand(0));
5823     SDValue Op2 = getValue(I.getArgOperand(1));
5824     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5825     return nullptr;
5826   }
5827   case Intrinsic::usub_sat: {
5828     SDValue Op1 = getValue(I.getArgOperand(0));
5829     SDValue Op2 = getValue(I.getArgOperand(1));
5830     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
5831     return nullptr;
5832   }
5833   case Intrinsic::smul_fix: {
5834     SDValue Op1 = getValue(I.getArgOperand(0));
5835     SDValue Op2 = getValue(I.getArgOperand(1));
5836     SDValue Op3 = getValue(I.getArgOperand(2));
5837     setValue(&I,
5838              DAG.getNode(ISD::SMULFIX, sdl, Op1.getValueType(), Op1, Op2, Op3));
5839     return nullptr;
5840   }
5841   case Intrinsic::stacksave: {
5842     SDValue Op = getRoot();
5843     Res = DAG.getNode(
5844         ISD::STACKSAVE, sdl,
5845         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Op);
5846     setValue(&I, Res);
5847     DAG.setRoot(Res.getValue(1));
5848     return nullptr;
5849   }
5850   case Intrinsic::stackrestore:
5851     Res = getValue(I.getArgOperand(0));
5852     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
5853     return nullptr;
5854   case Intrinsic::get_dynamic_area_offset: {
5855     SDValue Op = getRoot();
5856     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5857     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
5858     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
5859     // target.
5860     if (PtrTy != ResTy)
5861       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
5862                          " intrinsic!");
5863     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
5864                       Op);
5865     DAG.setRoot(Op);
5866     setValue(&I, Res);
5867     return nullptr;
5868   }
5869   case Intrinsic::stackguard: {
5870     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5871     MachineFunction &MF = DAG.getMachineFunction();
5872     const Module &M = *MF.getFunction().getParent();
5873     SDValue Chain = getRoot();
5874     if (TLI.useLoadStackGuardNode()) {
5875       Res = getLoadStackGuard(DAG, sdl, Chain);
5876     } else {
5877       const Value *Global = TLI.getSDagStackGuard(M);
5878       unsigned Align = DL->getPrefTypeAlignment(Global->getType());
5879       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
5880                         MachinePointerInfo(Global, 0), Align,
5881                         MachineMemOperand::MOVolatile);
5882     }
5883     if (TLI.useStackGuardXorFP())
5884       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
5885     DAG.setRoot(Chain);
5886     setValue(&I, Res);
5887     return nullptr;
5888   }
5889   case Intrinsic::stackprotector: {
5890     // Emit code into the DAG to store the stack guard onto the stack.
5891     MachineFunction &MF = DAG.getMachineFunction();
5892     MachineFrameInfo &MFI = MF.getFrameInfo();
5893     EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
5894     SDValue Src, Chain = getRoot();
5895 
5896     if (TLI.useLoadStackGuardNode())
5897       Src = getLoadStackGuard(DAG, sdl, Chain);
5898     else
5899       Src = getValue(I.getArgOperand(0));   // The guard's value.
5900 
5901     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
5902 
5903     int FI = FuncInfo.StaticAllocaMap[Slot];
5904     MFI.setStackProtectorIndex(FI);
5905 
5906     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5907 
5908     // Store the stack protector onto the stack.
5909     Res = DAG.getStore(Chain, sdl, Src, FIN, MachinePointerInfo::getFixedStack(
5910                                                  DAG.getMachineFunction(), FI),
5911                        /* Alignment = */ 0, MachineMemOperand::MOVolatile);
5912     setValue(&I, Res);
5913     DAG.setRoot(Res);
5914     return nullptr;
5915   }
5916   case Intrinsic::objectsize: {
5917     // If we don't know by now, we're never going to know.
5918     ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
5919 
5920     assert(CI && "Non-constant type in __builtin_object_size?");
5921 
5922     SDValue Arg = getValue(I.getCalledValue());
5923     EVT Ty = Arg.getValueType();
5924 
5925     if (CI->isZero())
5926       Res = DAG.getConstant(-1ULL, sdl, Ty);
5927     else
5928       Res = DAG.getConstant(0, sdl, Ty);
5929 
5930     setValue(&I, Res);
5931     return nullptr;
5932   }
5933 
5934   case Intrinsic::is_constant:
5935     // If this wasn't constant-folded away by now, then it's not a
5936     // constant.
5937     setValue(&I, DAG.getConstant(0, sdl, MVT::i1));
5938     return nullptr;
5939 
5940   case Intrinsic::annotation:
5941   case Intrinsic::ptr_annotation:
5942   case Intrinsic::launder_invariant_group:
5943   case Intrinsic::strip_invariant_group:
5944     // Drop the intrinsic, but forward the value
5945     setValue(&I, getValue(I.getOperand(0)));
5946     return nullptr;
5947   case Intrinsic::assume:
5948   case Intrinsic::var_annotation:
5949   case Intrinsic::sideeffect:
5950     // Discard annotate attributes, assumptions, and artificial side-effects.
5951     return nullptr;
5952 
5953   case Intrinsic::codeview_annotation: {
5954     // Emit a label associated with this metadata.
5955     MachineFunction &MF = DAG.getMachineFunction();
5956     MCSymbol *Label =
5957         MF.getMMI().getContext().createTempSymbol("annotation", true);
5958     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
5959     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
5960     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
5961     DAG.setRoot(Res);
5962     return nullptr;
5963   }
5964 
5965   case Intrinsic::init_trampoline: {
5966     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
5967 
5968     SDValue Ops[6];
5969     Ops[0] = getRoot();
5970     Ops[1] = getValue(I.getArgOperand(0));
5971     Ops[2] = getValue(I.getArgOperand(1));
5972     Ops[3] = getValue(I.getArgOperand(2));
5973     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
5974     Ops[5] = DAG.getSrcValue(F);
5975 
5976     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
5977 
5978     DAG.setRoot(Res);
5979     return nullptr;
5980   }
5981   case Intrinsic::adjust_trampoline:
5982     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
5983                              TLI.getPointerTy(DAG.getDataLayout()),
5984                              getValue(I.getArgOperand(0))));
5985     return nullptr;
5986   case Intrinsic::gcroot: {
5987     assert(DAG.getMachineFunction().getFunction().hasGC() &&
5988            "only valid in functions with gc specified, enforced by Verifier");
5989     assert(GFI && "implied by previous");
5990     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
5991     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
5992 
5993     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5994     GFI->addStackRoot(FI->getIndex(), TypeMap);
5995     return nullptr;
5996   }
5997   case Intrinsic::gcread:
5998   case Intrinsic::gcwrite:
5999     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
6000   case Intrinsic::flt_rounds:
6001     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, sdl, MVT::i32));
6002     return nullptr;
6003 
6004   case Intrinsic::expect:
6005     // Just replace __builtin_expect(exp, c) with EXP.
6006     setValue(&I, getValue(I.getArgOperand(0)));
6007     return nullptr;
6008 
6009   case Intrinsic::debugtrap:
6010   case Intrinsic::trap: {
6011     StringRef TrapFuncName =
6012         I.getAttributes()
6013             .getAttribute(AttributeList::FunctionIndex, "trap-func-name")
6014             .getValueAsString();
6015     if (TrapFuncName.empty()) {
6016       ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
6017         ISD::TRAP : ISD::DEBUGTRAP;
6018       DAG.setRoot(DAG.getNode(Op, sdl,MVT::Other, getRoot()));
6019       return nullptr;
6020     }
6021     TargetLowering::ArgListTy Args;
6022 
6023     TargetLowering::CallLoweringInfo CLI(DAG);
6024     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
6025         CallingConv::C, I.getType(),
6026         DAG.getExternalSymbol(TrapFuncName.data(),
6027                               TLI.getPointerTy(DAG.getDataLayout())),
6028         std::move(Args));
6029 
6030     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6031     DAG.setRoot(Result.second);
6032     return nullptr;
6033   }
6034 
6035   case Intrinsic::uadd_with_overflow:
6036   case Intrinsic::sadd_with_overflow:
6037   case Intrinsic::usub_with_overflow:
6038   case Intrinsic::ssub_with_overflow:
6039   case Intrinsic::umul_with_overflow:
6040   case Intrinsic::smul_with_overflow: {
6041     ISD::NodeType Op;
6042     switch (Intrinsic) {
6043     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6044     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
6045     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
6046     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
6047     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
6048     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
6049     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
6050     }
6051     SDValue Op1 = getValue(I.getArgOperand(0));
6052     SDValue Op2 = getValue(I.getArgOperand(1));
6053 
6054     SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
6055     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
6056     return nullptr;
6057   }
6058   case Intrinsic::prefetch: {
6059     SDValue Ops[5];
6060     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
6061     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
6062     Ops[0] = DAG.getRoot();
6063     Ops[1] = getValue(I.getArgOperand(0));
6064     Ops[2] = getValue(I.getArgOperand(1));
6065     Ops[3] = getValue(I.getArgOperand(2));
6066     Ops[4] = getValue(I.getArgOperand(3));
6067     SDValue Result = DAG.getMemIntrinsicNode(ISD::PREFETCH, sdl,
6068                                              DAG.getVTList(MVT::Other), Ops,
6069                                              EVT::getIntegerVT(*Context, 8),
6070                                              MachinePointerInfo(I.getArgOperand(0)),
6071                                              0, /* align */
6072                                              Flags);
6073 
6074     // Chain the prefetch in parallell with any pending loads, to stay out of
6075     // the way of later optimizations.
6076     PendingLoads.push_back(Result);
6077     Result = getRoot();
6078     DAG.setRoot(Result);
6079     return nullptr;
6080   }
6081   case Intrinsic::lifetime_start:
6082   case Intrinsic::lifetime_end: {
6083     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
6084     // Stack coloring is not enabled in O0, discard region information.
6085     if (TM.getOptLevel() == CodeGenOpt::None)
6086       return nullptr;
6087 
6088     SmallVector<Value *, 4> Allocas;
6089     GetUnderlyingObjects(I.getArgOperand(1), Allocas, *DL);
6090 
6091     for (SmallVectorImpl<Value*>::iterator Object = Allocas.begin(),
6092            E = Allocas.end(); Object != E; ++Object) {
6093       AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
6094 
6095       // Could not find an Alloca.
6096       if (!LifetimeObject)
6097         continue;
6098 
6099       // First check that the Alloca is static, otherwise it won't have a
6100       // valid frame index.
6101       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
6102       if (SI == FuncInfo.StaticAllocaMap.end())
6103         return nullptr;
6104 
6105       int FI = SI->second;
6106 
6107       SDValue Ops[2];
6108       Ops[0] = getRoot();
6109       Ops[1] =
6110           DAG.getFrameIndex(FI, TLI.getFrameIndexTy(DAG.getDataLayout()), true);
6111       unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
6112 
6113       Res = DAG.getNode(Opcode, sdl, MVT::Other, Ops);
6114       DAG.setRoot(Res);
6115     }
6116     return nullptr;
6117   }
6118   case Intrinsic::invariant_start:
6119     // Discard region information.
6120     setValue(&I, DAG.getUNDEF(TLI.getPointerTy(DAG.getDataLayout())));
6121     return nullptr;
6122   case Intrinsic::invariant_end:
6123     // Discard region information.
6124     return nullptr;
6125   case Intrinsic::clear_cache:
6126     return TLI.getClearCacheBuiltinName();
6127   case Intrinsic::donothing:
6128     // ignore
6129     return nullptr;
6130   case Intrinsic::experimental_stackmap:
6131     visitStackmap(I);
6132     return nullptr;
6133   case Intrinsic::experimental_patchpoint_void:
6134   case Intrinsic::experimental_patchpoint_i64:
6135     visitPatchpoint(&I);
6136     return nullptr;
6137   case Intrinsic::experimental_gc_statepoint:
6138     LowerStatepoint(ImmutableStatepoint(&I));
6139     return nullptr;
6140   case Intrinsic::experimental_gc_result:
6141     visitGCResult(cast<GCResultInst>(I));
6142     return nullptr;
6143   case Intrinsic::experimental_gc_relocate:
6144     visitGCRelocate(cast<GCRelocateInst>(I));
6145     return nullptr;
6146   case Intrinsic::instrprof_increment:
6147     llvm_unreachable("instrprof failed to lower an increment");
6148   case Intrinsic::instrprof_value_profile:
6149     llvm_unreachable("instrprof failed to lower a value profiling call");
6150   case Intrinsic::localescape: {
6151     MachineFunction &MF = DAG.getMachineFunction();
6152     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6153 
6154     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
6155     // is the same on all targets.
6156     for (unsigned Idx = 0, E = I.getNumArgOperands(); Idx < E; ++Idx) {
6157       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
6158       if (isa<ConstantPointerNull>(Arg))
6159         continue; // Skip null pointers. They represent a hole in index space.
6160       AllocaInst *Slot = cast<AllocaInst>(Arg);
6161       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
6162              "can only escape static allocas");
6163       int FI = FuncInfo.StaticAllocaMap[Slot];
6164       MCSymbol *FrameAllocSym =
6165           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6166               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
6167       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
6168               TII->get(TargetOpcode::LOCAL_ESCAPE))
6169           .addSym(FrameAllocSym)
6170           .addFrameIndex(FI);
6171     }
6172 
6173     MF.setHasLocalEscape(true);
6174 
6175     return nullptr;
6176   }
6177 
6178   case Intrinsic::localrecover: {
6179     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
6180     MachineFunction &MF = DAG.getMachineFunction();
6181     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout(), 0);
6182 
6183     // Get the symbol that defines the frame offset.
6184     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
6185     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
6186     unsigned IdxVal =
6187         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
6188     MCSymbol *FrameAllocSym =
6189         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
6190             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
6191 
6192     // Create a MCSymbol for the label to avoid any target lowering
6193     // that would make this PC relative.
6194     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
6195     SDValue OffsetVal =
6196         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
6197 
6198     // Add the offset to the FP.
6199     Value *FP = I.getArgOperand(1);
6200     SDValue FPVal = getValue(FP);
6201     SDValue Add = DAG.getNode(ISD::ADD, sdl, PtrVT, FPVal, OffsetVal);
6202     setValue(&I, Add);
6203 
6204     return nullptr;
6205   }
6206 
6207   case Intrinsic::eh_exceptionpointer:
6208   case Intrinsic::eh_exceptioncode: {
6209     // Get the exception pointer vreg, copy from it, and resize it to fit.
6210     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
6211     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
6212     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
6213     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
6214     SDValue N =
6215         DAG.getCopyFromReg(DAG.getEntryNode(), getCurSDLoc(), VReg, PtrVT);
6216     if (Intrinsic == Intrinsic::eh_exceptioncode)
6217       N = DAG.getZExtOrTrunc(N, getCurSDLoc(), MVT::i32);
6218     setValue(&I, N);
6219     return nullptr;
6220   }
6221   case Intrinsic::xray_customevent: {
6222     // Here we want to make sure that the intrinsic behaves as if it has a
6223     // specific calling convention, and only for x86_64.
6224     // FIXME: Support other platforms later.
6225     const auto &Triple = DAG.getTarget().getTargetTriple();
6226     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6227       return nullptr;
6228 
6229     SDLoc DL = getCurSDLoc();
6230     SmallVector<SDValue, 8> Ops;
6231 
6232     // We want to say that we always want the arguments in registers.
6233     SDValue LogEntryVal = getValue(I.getArgOperand(0));
6234     SDValue StrSizeVal = getValue(I.getArgOperand(1));
6235     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6236     SDValue Chain = getRoot();
6237     Ops.push_back(LogEntryVal);
6238     Ops.push_back(StrSizeVal);
6239     Ops.push_back(Chain);
6240 
6241     // We need to enforce the calling convention for the callsite, so that
6242     // argument ordering is enforced correctly, and that register allocation can
6243     // see that some registers may be assumed clobbered and have to preserve
6244     // them across calls to the intrinsic.
6245     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
6246                                            DL, NodeTys, Ops);
6247     SDValue patchableNode = SDValue(MN, 0);
6248     DAG.setRoot(patchableNode);
6249     setValue(&I, patchableNode);
6250     return nullptr;
6251   }
6252   case Intrinsic::xray_typedevent: {
6253     // Here we want to make sure that the intrinsic behaves as if it has a
6254     // specific calling convention, and only for x86_64.
6255     // FIXME: Support other platforms later.
6256     const auto &Triple = DAG.getTarget().getTargetTriple();
6257     if (Triple.getArch() != Triple::x86_64 || !Triple.isOSLinux())
6258       return nullptr;
6259 
6260     SDLoc DL = getCurSDLoc();
6261     SmallVector<SDValue, 8> Ops;
6262 
6263     // We want to say that we always want the arguments in registers.
6264     // It's unclear to me how manipulating the selection DAG here forces callers
6265     // to provide arguments in registers instead of on the stack.
6266     SDValue LogTypeId = getValue(I.getArgOperand(0));
6267     SDValue LogEntryVal = getValue(I.getArgOperand(1));
6268     SDValue StrSizeVal = getValue(I.getArgOperand(2));
6269     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
6270     SDValue Chain = getRoot();
6271     Ops.push_back(LogTypeId);
6272     Ops.push_back(LogEntryVal);
6273     Ops.push_back(StrSizeVal);
6274     Ops.push_back(Chain);
6275 
6276     // We need to enforce the calling convention for the callsite, so that
6277     // argument ordering is enforced correctly, and that register allocation can
6278     // see that some registers may be assumed clobbered and have to preserve
6279     // them across calls to the intrinsic.
6280     MachineSDNode *MN = DAG.getMachineNode(
6281         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, DL, NodeTys, Ops);
6282     SDValue patchableNode = SDValue(MN, 0);
6283     DAG.setRoot(patchableNode);
6284     setValue(&I, patchableNode);
6285     return nullptr;
6286   }
6287   case Intrinsic::experimental_deoptimize:
6288     LowerDeoptimizeCall(&I);
6289     return nullptr;
6290 
6291   case Intrinsic::experimental_vector_reduce_fadd:
6292   case Intrinsic::experimental_vector_reduce_fmul:
6293   case Intrinsic::experimental_vector_reduce_add:
6294   case Intrinsic::experimental_vector_reduce_mul:
6295   case Intrinsic::experimental_vector_reduce_and:
6296   case Intrinsic::experimental_vector_reduce_or:
6297   case Intrinsic::experimental_vector_reduce_xor:
6298   case Intrinsic::experimental_vector_reduce_smax:
6299   case Intrinsic::experimental_vector_reduce_smin:
6300   case Intrinsic::experimental_vector_reduce_umax:
6301   case Intrinsic::experimental_vector_reduce_umin:
6302   case Intrinsic::experimental_vector_reduce_fmax:
6303   case Intrinsic::experimental_vector_reduce_fmin:
6304     visitVectorReduce(I, Intrinsic);
6305     return nullptr;
6306 
6307   case Intrinsic::icall_branch_funnel: {
6308     SmallVector<SDValue, 16> Ops;
6309     Ops.push_back(DAG.getRoot());
6310     Ops.push_back(getValue(I.getArgOperand(0)));
6311 
6312     int64_t Offset;
6313     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6314         I.getArgOperand(1), Offset, DAG.getDataLayout()));
6315     if (!Base)
6316       report_fatal_error(
6317           "llvm.icall.branch.funnel operand must be a GlobalValue");
6318     Ops.push_back(DAG.getTargetGlobalAddress(Base, getCurSDLoc(), MVT::i64, 0));
6319 
6320     struct BranchFunnelTarget {
6321       int64_t Offset;
6322       SDValue Target;
6323     };
6324     SmallVector<BranchFunnelTarget, 8> Targets;
6325 
6326     for (unsigned Op = 1, N = I.getNumArgOperands(); Op != N; Op += 2) {
6327       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
6328           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
6329       if (ElemBase != Base)
6330         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
6331                            "to the same GlobalValue");
6332 
6333       SDValue Val = getValue(I.getArgOperand(Op + 1));
6334       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
6335       if (!GA)
6336         report_fatal_error(
6337             "llvm.icall.branch.funnel operand must be a GlobalValue");
6338       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
6339                                      GA->getGlobal(), getCurSDLoc(),
6340                                      Val.getValueType(), GA->getOffset())});
6341     }
6342     llvm::sort(Targets,
6343                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
6344                  return T1.Offset < T2.Offset;
6345                });
6346 
6347     for (auto &T : Targets) {
6348       Ops.push_back(DAG.getTargetConstant(T.Offset, getCurSDLoc(), MVT::i32));
6349       Ops.push_back(T.Target);
6350     }
6351 
6352     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL,
6353                                  getCurSDLoc(), MVT::Other, Ops),
6354               0);
6355     DAG.setRoot(N);
6356     setValue(&I, N);
6357     HasTailCall = true;
6358     return nullptr;
6359   }
6360 
6361   case Intrinsic::wasm_landingpad_index:
6362     // Information this intrinsic contained has been transferred to
6363     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
6364     // delete it now.
6365     return nullptr;
6366   }
6367 }
6368 
6369 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
6370     const ConstrainedFPIntrinsic &FPI) {
6371   SDLoc sdl = getCurSDLoc();
6372   unsigned Opcode;
6373   switch (FPI.getIntrinsicID()) {
6374   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6375   case Intrinsic::experimental_constrained_fadd:
6376     Opcode = ISD::STRICT_FADD;
6377     break;
6378   case Intrinsic::experimental_constrained_fsub:
6379     Opcode = ISD::STRICT_FSUB;
6380     break;
6381   case Intrinsic::experimental_constrained_fmul:
6382     Opcode = ISD::STRICT_FMUL;
6383     break;
6384   case Intrinsic::experimental_constrained_fdiv:
6385     Opcode = ISD::STRICT_FDIV;
6386     break;
6387   case Intrinsic::experimental_constrained_frem:
6388     Opcode = ISD::STRICT_FREM;
6389     break;
6390   case Intrinsic::experimental_constrained_fma:
6391     Opcode = ISD::STRICT_FMA;
6392     break;
6393   case Intrinsic::experimental_constrained_sqrt:
6394     Opcode = ISD::STRICT_FSQRT;
6395     break;
6396   case Intrinsic::experimental_constrained_pow:
6397     Opcode = ISD::STRICT_FPOW;
6398     break;
6399   case Intrinsic::experimental_constrained_powi:
6400     Opcode = ISD::STRICT_FPOWI;
6401     break;
6402   case Intrinsic::experimental_constrained_sin:
6403     Opcode = ISD::STRICT_FSIN;
6404     break;
6405   case Intrinsic::experimental_constrained_cos:
6406     Opcode = ISD::STRICT_FCOS;
6407     break;
6408   case Intrinsic::experimental_constrained_exp:
6409     Opcode = ISD::STRICT_FEXP;
6410     break;
6411   case Intrinsic::experimental_constrained_exp2:
6412     Opcode = ISD::STRICT_FEXP2;
6413     break;
6414   case Intrinsic::experimental_constrained_log:
6415     Opcode = ISD::STRICT_FLOG;
6416     break;
6417   case Intrinsic::experimental_constrained_log10:
6418     Opcode = ISD::STRICT_FLOG10;
6419     break;
6420   case Intrinsic::experimental_constrained_log2:
6421     Opcode = ISD::STRICT_FLOG2;
6422     break;
6423   case Intrinsic::experimental_constrained_rint:
6424     Opcode = ISD::STRICT_FRINT;
6425     break;
6426   case Intrinsic::experimental_constrained_nearbyint:
6427     Opcode = ISD::STRICT_FNEARBYINT;
6428     break;
6429   case Intrinsic::experimental_constrained_maxnum:
6430     Opcode = ISD::STRICT_FMAXNUM;
6431     break;
6432   case Intrinsic::experimental_constrained_minnum:
6433     Opcode = ISD::STRICT_FMINNUM;
6434     break;
6435   case Intrinsic::experimental_constrained_ceil:
6436     Opcode = ISD::STRICT_FCEIL;
6437     break;
6438   case Intrinsic::experimental_constrained_floor:
6439     Opcode = ISD::STRICT_FFLOOR;
6440     break;
6441   case Intrinsic::experimental_constrained_round:
6442     Opcode = ISD::STRICT_FROUND;
6443     break;
6444   case Intrinsic::experimental_constrained_trunc:
6445     Opcode = ISD::STRICT_FTRUNC;
6446     break;
6447   }
6448   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6449   SDValue Chain = getRoot();
6450   SmallVector<EVT, 4> ValueVTs;
6451   ComputeValueVTs(TLI, DAG.getDataLayout(), FPI.getType(), ValueVTs);
6452   ValueVTs.push_back(MVT::Other); // Out chain
6453 
6454   SDVTList VTs = DAG.getVTList(ValueVTs);
6455   SDValue Result;
6456   if (FPI.isUnaryOp())
6457     Result = DAG.getNode(Opcode, sdl, VTs,
6458                          { Chain, getValue(FPI.getArgOperand(0)) });
6459   else if (FPI.isTernaryOp())
6460     Result = DAG.getNode(Opcode, sdl, VTs,
6461                          { Chain, getValue(FPI.getArgOperand(0)),
6462                                   getValue(FPI.getArgOperand(1)),
6463                                   getValue(FPI.getArgOperand(2)) });
6464   else
6465     Result = DAG.getNode(Opcode, sdl, VTs,
6466                          { Chain, getValue(FPI.getArgOperand(0)),
6467                            getValue(FPI.getArgOperand(1))  });
6468 
6469   assert(Result.getNode()->getNumValues() == 2);
6470   SDValue OutChain = Result.getValue(1);
6471   DAG.setRoot(OutChain);
6472   SDValue FPResult = Result.getValue(0);
6473   setValue(&FPI, FPResult);
6474 }
6475 
6476 std::pair<SDValue, SDValue>
6477 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
6478                                     const BasicBlock *EHPadBB) {
6479   MachineFunction &MF = DAG.getMachineFunction();
6480   MachineModuleInfo &MMI = MF.getMMI();
6481   MCSymbol *BeginLabel = nullptr;
6482 
6483   if (EHPadBB) {
6484     // Insert a label before the invoke call to mark the try range.  This can be
6485     // used to detect deletion of the invoke via the MachineModuleInfo.
6486     BeginLabel = MMI.getContext().createTempSymbol();
6487 
6488     // For SjLj, keep track of which landing pads go with which invokes
6489     // so as to maintain the ordering of pads in the LSDA.
6490     unsigned CallSiteIndex = MMI.getCurrentCallSite();
6491     if (CallSiteIndex) {
6492       MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
6493       LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
6494 
6495       // Now that the call site is handled, stop tracking it.
6496       MMI.setCurrentCallSite(0);
6497     }
6498 
6499     // Both PendingLoads and PendingExports must be flushed here;
6500     // this call might not return.
6501     (void)getRoot();
6502     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getControlRoot(), BeginLabel));
6503 
6504     CLI.setChain(getRoot());
6505   }
6506   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6507   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
6508 
6509   assert((CLI.IsTailCall || Result.second.getNode()) &&
6510          "Non-null chain expected with non-tail call!");
6511   assert((Result.second.getNode() || !Result.first.getNode()) &&
6512          "Null value expected with tail call!");
6513 
6514   if (!Result.second.getNode()) {
6515     // As a special case, a null chain means that a tail call has been emitted
6516     // and the DAG root is already updated.
6517     HasTailCall = true;
6518 
6519     // Since there's no actual continuation from this block, nothing can be
6520     // relying on us setting vregs for them.
6521     PendingExports.clear();
6522   } else {
6523     DAG.setRoot(Result.second);
6524   }
6525 
6526   if (EHPadBB) {
6527     // Insert a label at the end of the invoke call to mark the try range.  This
6528     // can be used to detect deletion of the invoke via the MachineModuleInfo.
6529     MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
6530     DAG.setRoot(DAG.getEHLabel(getCurSDLoc(), getRoot(), EndLabel));
6531 
6532     // Inform MachineModuleInfo of range.
6533     auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
6534     // There is a platform (e.g. wasm) that uses funclet style IR but does not
6535     // actually use outlined funclets and their LSDA info style.
6536     if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
6537       assert(CLI.CS);
6538       WinEHFuncInfo *EHInfo = DAG.getMachineFunction().getWinEHFuncInfo();
6539       EHInfo->addIPToStateRange(cast<InvokeInst>(CLI.CS.getInstruction()),
6540                                 BeginLabel, EndLabel);
6541     } else if (!isScopedEHPersonality(Pers)) {
6542       MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
6543     }
6544   }
6545 
6546   return Result;
6547 }
6548 
6549 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
6550                                       bool isTailCall,
6551                                       const BasicBlock *EHPadBB) {
6552   auto &DL = DAG.getDataLayout();
6553   FunctionType *FTy = CS.getFunctionType();
6554   Type *RetTy = CS.getType();
6555 
6556   TargetLowering::ArgListTy Args;
6557   Args.reserve(CS.arg_size());
6558 
6559   const Value *SwiftErrorVal = nullptr;
6560   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6561 
6562   // We can't tail call inside a function with a swifterror argument. Lowering
6563   // does not support this yet. It would have to move into the swifterror
6564   // register before the call.
6565   auto *Caller = CS.getInstruction()->getParent()->getParent();
6566   if (TLI.supportSwiftError() &&
6567       Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
6568     isTailCall = false;
6569 
6570   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
6571        i != e; ++i) {
6572     TargetLowering::ArgListEntry Entry;
6573     const Value *V = *i;
6574 
6575     // Skip empty types
6576     if (V->getType()->isEmptyTy())
6577       continue;
6578 
6579     SDValue ArgNode = getValue(V);
6580     Entry.Node = ArgNode; Entry.Ty = V->getType();
6581 
6582     Entry.setAttributes(&CS, i - CS.arg_begin());
6583 
6584     // Use swifterror virtual register as input to the call.
6585     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
6586       SwiftErrorVal = V;
6587       // We find the virtual register for the actual swifterror argument.
6588       // Instead of using the Value, we use the virtual register instead.
6589       Entry.Node = DAG.getRegister(FuncInfo
6590                                        .getOrCreateSwiftErrorVRegUseAt(
6591                                            CS.getInstruction(), FuncInfo.MBB, V)
6592                                        .first,
6593                                    EVT(TLI.getPointerTy(DL)));
6594     }
6595 
6596     Args.push_back(Entry);
6597 
6598     // If we have an explicit sret argument that is an Instruction, (i.e., it
6599     // might point to function-local memory), we can't meaningfully tail-call.
6600     if (Entry.IsSRet && isa<Instruction>(V))
6601       isTailCall = false;
6602   }
6603 
6604   // Check if target-independent constraints permit a tail call here.
6605   // Target-dependent constraints are checked within TLI->LowerCallTo.
6606   if (isTailCall && !isInTailCallPosition(CS, DAG.getTarget()))
6607     isTailCall = false;
6608 
6609   // Disable tail calls if there is an swifterror argument. Targets have not
6610   // been updated to support tail calls.
6611   if (TLI.supportSwiftError() && SwiftErrorVal)
6612     isTailCall = false;
6613 
6614   TargetLowering::CallLoweringInfo CLI(DAG);
6615   CLI.setDebugLoc(getCurSDLoc())
6616       .setChain(getRoot())
6617       .setCallee(RetTy, FTy, Callee, std::move(Args), CS)
6618       .setTailCall(isTailCall)
6619       .setConvergent(CS.isConvergent());
6620   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
6621 
6622   if (Result.first.getNode()) {
6623     const Instruction *Inst = CS.getInstruction();
6624     Result.first = lowerRangeToAssertZExt(DAG, *Inst, Result.first);
6625     setValue(Inst, Result.first);
6626   }
6627 
6628   // The last element of CLI.InVals has the SDValue for swifterror return.
6629   // Here we copy it to a virtual register and update SwiftErrorMap for
6630   // book-keeping.
6631   if (SwiftErrorVal && TLI.supportSwiftError()) {
6632     // Get the last element of InVals.
6633     SDValue Src = CLI.InVals.back();
6634     unsigned VReg; bool CreatedVReg;
6635     std::tie(VReg, CreatedVReg) =
6636         FuncInfo.getOrCreateSwiftErrorVRegDefAt(CS.getInstruction());
6637     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
6638     // We update the virtual register for the actual swifterror argument.
6639     if (CreatedVReg)
6640       FuncInfo.setCurrentSwiftErrorVReg(FuncInfo.MBB, SwiftErrorVal, VReg);
6641     DAG.setRoot(CopyNode);
6642   }
6643 }
6644 
6645 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
6646                              SelectionDAGBuilder &Builder) {
6647   // Check to see if this load can be trivially constant folded, e.g. if the
6648   // input is from a string literal.
6649   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
6650     // Cast pointer to the type we really want to load.
6651     Type *LoadTy =
6652         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
6653     if (LoadVT.isVector())
6654       LoadTy = VectorType::get(LoadTy, LoadVT.getVectorNumElements());
6655 
6656     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
6657                                          PointerType::getUnqual(LoadTy));
6658 
6659     if (const Constant *LoadCst = ConstantFoldLoadFromConstPtr(
6660             const_cast<Constant *>(LoadInput), LoadTy, *Builder.DL))
6661       return Builder.getValue(LoadCst);
6662   }
6663 
6664   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
6665   // still constant memory, the input chain can be the entry node.
6666   SDValue Root;
6667   bool ConstantMemory = false;
6668 
6669   // Do not serialize (non-volatile) loads of constant memory with anything.
6670   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
6671     Root = Builder.DAG.getEntryNode();
6672     ConstantMemory = true;
6673   } else {
6674     // Do not serialize non-volatile loads against each other.
6675     Root = Builder.DAG.getRoot();
6676   }
6677 
6678   SDValue Ptr = Builder.getValue(PtrVal);
6679   SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root,
6680                                         Ptr, MachinePointerInfo(PtrVal),
6681                                         /* Alignment = */ 1);
6682 
6683   if (!ConstantMemory)
6684     Builder.PendingLoads.push_back(LoadVal.getValue(1));
6685   return LoadVal;
6686 }
6687 
6688 /// Record the value for an instruction that produces an integer result,
6689 /// converting the type where necessary.
6690 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
6691                                                   SDValue Value,
6692                                                   bool IsSigned) {
6693   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6694                                                     I.getType(), true);
6695   if (IsSigned)
6696     Value = DAG.getSExtOrTrunc(Value, getCurSDLoc(), VT);
6697   else
6698     Value = DAG.getZExtOrTrunc(Value, getCurSDLoc(), VT);
6699   setValue(&I, Value);
6700 }
6701 
6702 /// See if we can lower a memcmp call into an optimized form. If so, return
6703 /// true and lower it. Otherwise return false, and it will be lowered like a
6704 /// normal call.
6705 /// The caller already checked that \p I calls the appropriate LibFunc with a
6706 /// correct prototype.
6707 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
6708   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
6709   const Value *Size = I.getArgOperand(2);
6710   const ConstantInt *CSize = dyn_cast<ConstantInt>(Size);
6711   if (CSize && CSize->getZExtValue() == 0) {
6712     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
6713                                                           I.getType(), true);
6714     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
6715     return true;
6716   }
6717 
6718   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6719   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
6720       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
6721       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
6722   if (Res.first.getNode()) {
6723     processIntegerCallValue(I, Res.first, true);
6724     PendingLoads.push_back(Res.second);
6725     return true;
6726   }
6727 
6728   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
6729   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
6730   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
6731     return false;
6732 
6733   // If the target has a fast compare for the given size, it will return a
6734   // preferred load type for that size. Require that the load VT is legal and
6735   // that the target supports unaligned loads of that type. Otherwise, return
6736   // INVALID.
6737   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
6738     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6739     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
6740     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
6741       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
6742       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
6743       // TODO: Check alignment of src and dest ptrs.
6744       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
6745       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
6746       if (!TLI.isTypeLegal(LVT) ||
6747           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
6748           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
6749         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
6750     }
6751 
6752     return LVT;
6753   };
6754 
6755   // This turns into unaligned loads. We only do this if the target natively
6756   // supports the MVT we'll be loading or if it is small enough (<= 4) that
6757   // we'll only produce a small number of byte loads.
6758   MVT LoadVT;
6759   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
6760   switch (NumBitsToCompare) {
6761   default:
6762     return false;
6763   case 16:
6764     LoadVT = MVT::i16;
6765     break;
6766   case 32:
6767     LoadVT = MVT::i32;
6768     break;
6769   case 64:
6770   case 128:
6771   case 256:
6772     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
6773     break;
6774   }
6775 
6776   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
6777     return false;
6778 
6779   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
6780   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
6781 
6782   // Bitcast to a wide integer type if the loads are vectors.
6783   if (LoadVT.isVector()) {
6784     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
6785     LoadL = DAG.getBitcast(CmpVT, LoadL);
6786     LoadR = DAG.getBitcast(CmpVT, LoadR);
6787   }
6788 
6789   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
6790   processIntegerCallValue(I, Cmp, false);
6791   return true;
6792 }
6793 
6794 /// See if we can lower a memchr call into an optimized form. If so, return
6795 /// true and lower it. Otherwise return false, and it will be lowered like a
6796 /// normal call.
6797 /// The caller already checked that \p I calls the appropriate LibFunc with a
6798 /// correct prototype.
6799 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
6800   const Value *Src = I.getArgOperand(0);
6801   const Value *Char = I.getArgOperand(1);
6802   const Value *Length = I.getArgOperand(2);
6803 
6804   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6805   std::pair<SDValue, SDValue> Res =
6806     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
6807                                 getValue(Src), getValue(Char), getValue(Length),
6808                                 MachinePointerInfo(Src));
6809   if (Res.first.getNode()) {
6810     setValue(&I, Res.first);
6811     PendingLoads.push_back(Res.second);
6812     return true;
6813   }
6814 
6815   return false;
6816 }
6817 
6818 /// See if we can lower a mempcpy call into an optimized form. If so, return
6819 /// true and lower it. Otherwise return false, and it will be lowered like a
6820 /// normal call.
6821 /// The caller already checked that \p I calls the appropriate LibFunc with a
6822 /// correct prototype.
6823 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
6824   SDValue Dst = getValue(I.getArgOperand(0));
6825   SDValue Src = getValue(I.getArgOperand(1));
6826   SDValue Size = getValue(I.getArgOperand(2));
6827 
6828   unsigned DstAlign = DAG.InferPtrAlignment(Dst);
6829   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
6830   unsigned Align = std::min(DstAlign, SrcAlign);
6831   if (Align == 0) // Alignment of one or both could not be inferred.
6832     Align = 1; // 0 and 1 both specify no alignment, but 0 is reserved.
6833 
6834   bool isVol = false;
6835   SDLoc sdl = getCurSDLoc();
6836 
6837   // In the mempcpy context we need to pass in a false value for isTailCall
6838   // because the return pointer needs to be adjusted by the size of
6839   // the copied memory.
6840   SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Align, isVol,
6841                              false, /*isTailCall=*/false,
6842                              MachinePointerInfo(I.getArgOperand(0)),
6843                              MachinePointerInfo(I.getArgOperand(1)));
6844   assert(MC.getNode() != nullptr &&
6845          "** memcpy should not be lowered as TailCall in mempcpy context **");
6846   DAG.setRoot(MC);
6847 
6848   // Check if Size needs to be truncated or extended.
6849   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
6850 
6851   // Adjust return pointer to point just past the last dst byte.
6852   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
6853                                     Dst, Size);
6854   setValue(&I, DstPlusSize);
6855   return true;
6856 }
6857 
6858 /// See if we can lower a strcpy call into an optimized form.  If so, return
6859 /// true and lower it, otherwise return false and it will be lowered like a
6860 /// normal call.
6861 /// The caller already checked that \p I calls the appropriate LibFunc with a
6862 /// correct prototype.
6863 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
6864   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6865 
6866   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6867   std::pair<SDValue, SDValue> Res =
6868     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
6869                                 getValue(Arg0), getValue(Arg1),
6870                                 MachinePointerInfo(Arg0),
6871                                 MachinePointerInfo(Arg1), isStpcpy);
6872   if (Res.first.getNode()) {
6873     setValue(&I, Res.first);
6874     DAG.setRoot(Res.second);
6875     return true;
6876   }
6877 
6878   return false;
6879 }
6880 
6881 /// See if we can lower a strcmp call into an optimized form.  If so, return
6882 /// true and lower it, otherwise return false and it will be lowered like a
6883 /// normal call.
6884 /// The caller already checked that \p I calls the appropriate LibFunc with a
6885 /// correct prototype.
6886 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
6887   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6888 
6889   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6890   std::pair<SDValue, SDValue> Res =
6891     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
6892                                 getValue(Arg0), getValue(Arg1),
6893                                 MachinePointerInfo(Arg0),
6894                                 MachinePointerInfo(Arg1));
6895   if (Res.first.getNode()) {
6896     processIntegerCallValue(I, Res.first, true);
6897     PendingLoads.push_back(Res.second);
6898     return true;
6899   }
6900 
6901   return false;
6902 }
6903 
6904 /// See if we can lower a strlen call into an optimized form.  If so, return
6905 /// true and lower it, otherwise return false and it will be lowered like a
6906 /// normal call.
6907 /// The caller already checked that \p I calls the appropriate LibFunc with a
6908 /// correct prototype.
6909 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
6910   const Value *Arg0 = I.getArgOperand(0);
6911 
6912   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6913   std::pair<SDValue, SDValue> Res =
6914     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
6915                                 getValue(Arg0), MachinePointerInfo(Arg0));
6916   if (Res.first.getNode()) {
6917     processIntegerCallValue(I, Res.first, false);
6918     PendingLoads.push_back(Res.second);
6919     return true;
6920   }
6921 
6922   return false;
6923 }
6924 
6925 /// See if we can lower a strnlen call into an optimized form.  If so, return
6926 /// true and lower it, otherwise return false and it will be lowered like a
6927 /// normal call.
6928 /// The caller already checked that \p I calls the appropriate LibFunc with a
6929 /// correct prototype.
6930 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
6931   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
6932 
6933   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
6934   std::pair<SDValue, SDValue> Res =
6935     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
6936                                  getValue(Arg0), getValue(Arg1),
6937                                  MachinePointerInfo(Arg0));
6938   if (Res.first.getNode()) {
6939     processIntegerCallValue(I, Res.first, false);
6940     PendingLoads.push_back(Res.second);
6941     return true;
6942   }
6943 
6944   return false;
6945 }
6946 
6947 /// See if we can lower a unary floating-point operation into an SDNode with
6948 /// the specified Opcode.  If so, return true and lower it, otherwise return
6949 /// false and it will be lowered like a normal call.
6950 /// The caller already checked that \p I calls the appropriate LibFunc with a
6951 /// correct prototype.
6952 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
6953                                               unsigned Opcode) {
6954   // We already checked this call's prototype; verify it doesn't modify errno.
6955   if (!I.onlyReadsMemory())
6956     return false;
6957 
6958   SDValue Tmp = getValue(I.getArgOperand(0));
6959   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp));
6960   return true;
6961 }
6962 
6963 /// See if we can lower a binary floating-point operation into an SDNode with
6964 /// the specified Opcode. If so, return true and lower it. Otherwise return
6965 /// false, and it will be lowered like a normal call.
6966 /// The caller already checked that \p I calls the appropriate LibFunc with a
6967 /// correct prototype.
6968 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
6969                                                unsigned Opcode) {
6970   // We already checked this call's prototype; verify it doesn't modify errno.
6971   if (!I.onlyReadsMemory())
6972     return false;
6973 
6974   SDValue Tmp0 = getValue(I.getArgOperand(0));
6975   SDValue Tmp1 = getValue(I.getArgOperand(1));
6976   EVT VT = Tmp0.getValueType();
6977   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1));
6978   return true;
6979 }
6980 
6981 void SelectionDAGBuilder::visitCall(const CallInst &I) {
6982   // Handle inline assembly differently.
6983   if (isa<InlineAsm>(I.getCalledValue())) {
6984     visitInlineAsm(&I);
6985     return;
6986   }
6987 
6988   MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6989   computeUsesVAFloatArgument(I, MMI);
6990 
6991   const char *RenameFn = nullptr;
6992   if (Function *F = I.getCalledFunction()) {
6993     if (F->isDeclaration()) {
6994       // Is this an LLVM intrinsic or a target-specific intrinsic?
6995       unsigned IID = F->getIntrinsicID();
6996       if (!IID)
6997         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
6998           IID = II->getIntrinsicID(F);
6999 
7000       if (IID) {
7001         RenameFn = visitIntrinsicCall(I, IID);
7002         if (!RenameFn)
7003           return;
7004       }
7005     }
7006 
7007     // Check for well-known libc/libm calls.  If the function is internal, it
7008     // can't be a library call.  Don't do the check if marked as nobuiltin for
7009     // some reason or the call site requires strict floating point semantics.
7010     LibFunc Func;
7011     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
7012         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
7013         LibInfo->hasOptimizedCodeGen(Func)) {
7014       switch (Func) {
7015       default: break;
7016       case LibFunc_copysign:
7017       case LibFunc_copysignf:
7018       case LibFunc_copysignl:
7019         // We already checked this call's prototype; verify it doesn't modify
7020         // errno.
7021         if (I.onlyReadsMemory()) {
7022           SDValue LHS = getValue(I.getArgOperand(0));
7023           SDValue RHS = getValue(I.getArgOperand(1));
7024           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
7025                                    LHS.getValueType(), LHS, RHS));
7026           return;
7027         }
7028         break;
7029       case LibFunc_fabs:
7030       case LibFunc_fabsf:
7031       case LibFunc_fabsl:
7032         if (visitUnaryFloatCall(I, ISD::FABS))
7033           return;
7034         break;
7035       case LibFunc_fmin:
7036       case LibFunc_fminf:
7037       case LibFunc_fminl:
7038         if (visitBinaryFloatCall(I, ISD::FMINNUM))
7039           return;
7040         break;
7041       case LibFunc_fmax:
7042       case LibFunc_fmaxf:
7043       case LibFunc_fmaxl:
7044         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
7045           return;
7046         break;
7047       case LibFunc_sin:
7048       case LibFunc_sinf:
7049       case LibFunc_sinl:
7050         if (visitUnaryFloatCall(I, ISD::FSIN))
7051           return;
7052         break;
7053       case LibFunc_cos:
7054       case LibFunc_cosf:
7055       case LibFunc_cosl:
7056         if (visitUnaryFloatCall(I, ISD::FCOS))
7057           return;
7058         break;
7059       case LibFunc_sqrt:
7060       case LibFunc_sqrtf:
7061       case LibFunc_sqrtl:
7062       case LibFunc_sqrt_finite:
7063       case LibFunc_sqrtf_finite:
7064       case LibFunc_sqrtl_finite:
7065         if (visitUnaryFloatCall(I, ISD::FSQRT))
7066           return;
7067         break;
7068       case LibFunc_floor:
7069       case LibFunc_floorf:
7070       case LibFunc_floorl:
7071         if (visitUnaryFloatCall(I, ISD::FFLOOR))
7072           return;
7073         break;
7074       case LibFunc_nearbyint:
7075       case LibFunc_nearbyintf:
7076       case LibFunc_nearbyintl:
7077         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
7078           return;
7079         break;
7080       case LibFunc_ceil:
7081       case LibFunc_ceilf:
7082       case LibFunc_ceill:
7083         if (visitUnaryFloatCall(I, ISD::FCEIL))
7084           return;
7085         break;
7086       case LibFunc_rint:
7087       case LibFunc_rintf:
7088       case LibFunc_rintl:
7089         if (visitUnaryFloatCall(I, ISD::FRINT))
7090           return;
7091         break;
7092       case LibFunc_round:
7093       case LibFunc_roundf:
7094       case LibFunc_roundl:
7095         if (visitUnaryFloatCall(I, ISD::FROUND))
7096           return;
7097         break;
7098       case LibFunc_trunc:
7099       case LibFunc_truncf:
7100       case LibFunc_truncl:
7101         if (visitUnaryFloatCall(I, ISD::FTRUNC))
7102           return;
7103         break;
7104       case LibFunc_log2:
7105       case LibFunc_log2f:
7106       case LibFunc_log2l:
7107         if (visitUnaryFloatCall(I, ISD::FLOG2))
7108           return;
7109         break;
7110       case LibFunc_exp2:
7111       case LibFunc_exp2f:
7112       case LibFunc_exp2l:
7113         if (visitUnaryFloatCall(I, ISD::FEXP2))
7114           return;
7115         break;
7116       case LibFunc_memcmp:
7117         if (visitMemCmpCall(I))
7118           return;
7119         break;
7120       case LibFunc_mempcpy:
7121         if (visitMemPCpyCall(I))
7122           return;
7123         break;
7124       case LibFunc_memchr:
7125         if (visitMemChrCall(I))
7126           return;
7127         break;
7128       case LibFunc_strcpy:
7129         if (visitStrCpyCall(I, false))
7130           return;
7131         break;
7132       case LibFunc_stpcpy:
7133         if (visitStrCpyCall(I, true))
7134           return;
7135         break;
7136       case LibFunc_strcmp:
7137         if (visitStrCmpCall(I))
7138           return;
7139         break;
7140       case LibFunc_strlen:
7141         if (visitStrLenCall(I))
7142           return;
7143         break;
7144       case LibFunc_strnlen:
7145         if (visitStrNLenCall(I))
7146           return;
7147         break;
7148       }
7149     }
7150   }
7151 
7152   SDValue Callee;
7153   if (!RenameFn)
7154     Callee = getValue(I.getCalledValue());
7155   else
7156     Callee = DAG.getExternalSymbol(
7157         RenameFn,
7158         DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
7159 
7160   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
7161   // have to do anything here to lower funclet bundles.
7162   assert(!I.hasOperandBundlesOtherThan(
7163              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
7164          "Cannot lower calls with arbitrary operand bundles!");
7165 
7166   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
7167     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
7168   else
7169     // Check if we can potentially perform a tail call. More detailed checking
7170     // is be done within LowerCallTo, after more information about the call is
7171     // known.
7172     LowerCallTo(&I, Callee, I.isTailCall());
7173 }
7174 
7175 namespace {
7176 
7177 /// AsmOperandInfo - This contains information for each constraint that we are
7178 /// lowering.
7179 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
7180 public:
7181   /// CallOperand - If this is the result output operand or a clobber
7182   /// this is null, otherwise it is the incoming operand to the CallInst.
7183   /// This gets modified as the asm is processed.
7184   SDValue CallOperand;
7185 
7186   /// AssignedRegs - If this is a register or register class operand, this
7187   /// contains the set of register corresponding to the operand.
7188   RegsForValue AssignedRegs;
7189 
7190   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
7191     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
7192   }
7193 
7194   /// Whether or not this operand accesses memory
7195   bool hasMemory(const TargetLowering &TLI) const {
7196     // Indirect operand accesses access memory.
7197     if (isIndirect)
7198       return true;
7199 
7200     for (const auto &Code : Codes)
7201       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
7202         return true;
7203 
7204     return false;
7205   }
7206 
7207   /// getCallOperandValEVT - Return the EVT of the Value* that this operand
7208   /// corresponds to.  If there is no Value* for this operand, it returns
7209   /// MVT::Other.
7210   EVT getCallOperandValEVT(LLVMContext &Context, const TargetLowering &TLI,
7211                            const DataLayout &DL) const {
7212     if (!CallOperandVal) return MVT::Other;
7213 
7214     if (isa<BasicBlock>(CallOperandVal))
7215       return TLI.getPointerTy(DL);
7216 
7217     llvm::Type *OpTy = CallOperandVal->getType();
7218 
7219     // FIXME: code duplicated from TargetLowering::ParseConstraints().
7220     // If this is an indirect operand, the operand is a pointer to the
7221     // accessed type.
7222     if (isIndirect) {
7223       PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
7224       if (!PtrTy)
7225         report_fatal_error("Indirect operand for inline asm not a pointer!");
7226       OpTy = PtrTy->getElementType();
7227     }
7228 
7229     // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
7230     if (StructType *STy = dyn_cast<StructType>(OpTy))
7231       if (STy->getNumElements() == 1)
7232         OpTy = STy->getElementType(0);
7233 
7234     // If OpTy is not a single value, it may be a struct/union that we
7235     // can tile with integers.
7236     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
7237       unsigned BitSize = DL.getTypeSizeInBits(OpTy);
7238       switch (BitSize) {
7239       default: break;
7240       case 1:
7241       case 8:
7242       case 16:
7243       case 32:
7244       case 64:
7245       case 128:
7246         OpTy = IntegerType::get(Context, BitSize);
7247         break;
7248       }
7249     }
7250 
7251     return TLI.getValueType(DL, OpTy, true);
7252   }
7253 };
7254 
7255 using SDISelAsmOperandInfoVector = SmallVector<SDISelAsmOperandInfo, 16>;
7256 
7257 } // end anonymous namespace
7258 
7259 /// Make sure that the output operand \p OpInfo and its corresponding input
7260 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
7261 /// out).
7262 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
7263                                SDISelAsmOperandInfo &MatchingOpInfo,
7264                                SelectionDAG &DAG) {
7265   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
7266     return;
7267 
7268   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
7269   const auto &TLI = DAG.getTargetLoweringInfo();
7270 
7271   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
7272       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
7273                                        OpInfo.ConstraintVT);
7274   std::pair<unsigned, const TargetRegisterClass *> InputRC =
7275       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
7276                                        MatchingOpInfo.ConstraintVT);
7277   if ((OpInfo.ConstraintVT.isInteger() !=
7278        MatchingOpInfo.ConstraintVT.isInteger()) ||
7279       (MatchRC.second != InputRC.second)) {
7280     // FIXME: error out in a more elegant fashion
7281     report_fatal_error("Unsupported asm: input constraint"
7282                        " with a matching output constraint of"
7283                        " incompatible type!");
7284   }
7285   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
7286 }
7287 
7288 /// Get a direct memory input to behave well as an indirect operand.
7289 /// This may introduce stores, hence the need for a \p Chain.
7290 /// \return The (possibly updated) chain.
7291 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
7292                                         SDISelAsmOperandInfo &OpInfo,
7293                                         SelectionDAG &DAG) {
7294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7295 
7296   // If we don't have an indirect input, put it in the constpool if we can,
7297   // otherwise spill it to a stack slot.
7298   // TODO: This isn't quite right. We need to handle these according to
7299   // the addressing mode that the constraint wants. Also, this may take
7300   // an additional register for the computation and we don't want that
7301   // either.
7302 
7303   // If the operand is a float, integer, or vector constant, spill to a
7304   // constant pool entry to get its address.
7305   const Value *OpVal = OpInfo.CallOperandVal;
7306   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
7307       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
7308     OpInfo.CallOperand = DAG.getConstantPool(
7309         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
7310     return Chain;
7311   }
7312 
7313   // Otherwise, create a stack slot and emit a store to it before the asm.
7314   Type *Ty = OpVal->getType();
7315   auto &DL = DAG.getDataLayout();
7316   uint64_t TySize = DL.getTypeAllocSize(Ty);
7317   unsigned Align = DL.getPrefTypeAlignment(Ty);
7318   MachineFunction &MF = DAG.getMachineFunction();
7319   int SSFI = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
7320   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
7321   Chain = DAG.getStore(Chain, Location, OpInfo.CallOperand, StackSlot,
7322                        MachinePointerInfo::getFixedStack(MF, SSFI));
7323   OpInfo.CallOperand = StackSlot;
7324 
7325   return Chain;
7326 }
7327 
7328 /// GetRegistersForValue - Assign registers (virtual or physical) for the
7329 /// specified operand.  We prefer to assign virtual registers, to allow the
7330 /// register allocator to handle the assignment process.  However, if the asm
7331 /// uses features that we can't model on machineinstrs, we have SDISel do the
7332 /// allocation.  This produces generally horrible, but correct, code.
7333 ///
7334 ///   OpInfo describes the operand
7335 ///   RefOpInfo describes the matching operand if any, the operand otherwise
7336 static void GetRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
7337                                  SDISelAsmOperandInfo &OpInfo,
7338                                  SDISelAsmOperandInfo &RefOpInfo) {
7339   LLVMContext &Context = *DAG.getContext();
7340   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7341 
7342   MachineFunction &MF = DAG.getMachineFunction();
7343   SmallVector<unsigned, 4> Regs;
7344   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
7345 
7346   // If this is a constraint for a single physreg, or a constraint for a
7347   // register class, find it.
7348   unsigned AssignedReg;
7349   const TargetRegisterClass *RC;
7350   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
7351       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
7352   // RC is unset only on failure. Return immediately.
7353   if (!RC)
7354     return;
7355 
7356   // Get the actual register value type.  This is important, because the user
7357   // may have asked for (e.g.) the AX register in i32 type.  We need to
7358   // remember that AX is actually i16 to get the right extension.
7359   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
7360 
7361   if (OpInfo.ConstraintVT != MVT::Other) {
7362     // If this is an FP operand in an integer register (or visa versa), or more
7363     // generally if the operand value disagrees with the register class we plan
7364     // to stick it in, fix the operand type.
7365     //
7366     // If this is an input value, the bitcast to the new type is done now.
7367     // Bitcast for output value is done at the end of visitInlineAsm().
7368     if ((OpInfo.Type == InlineAsm::isOutput ||
7369          OpInfo.Type == InlineAsm::isInput) &&
7370         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
7371       // Try to convert to the first EVT that the reg class contains.  If the
7372       // types are identical size, use a bitcast to convert (e.g. two differing
7373       // vector types).  Note: output bitcast is done at the end of
7374       // visitInlineAsm().
7375       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
7376         // Exclude indirect inputs while they are unsupported because the code
7377         // to perform the load is missing and thus OpInfo.CallOperand still
7378         // refers to the input address rather than the pointed-to value.
7379         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
7380           OpInfo.CallOperand =
7381               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
7382         OpInfo.ConstraintVT = RegVT;
7383         // If the operand is an FP value and we want it in integer registers,
7384         // use the corresponding integer type. This turns an f64 value into
7385         // i64, which can be passed with two i32 values on a 32-bit machine.
7386       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
7387         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
7388         if (OpInfo.Type == InlineAsm::isInput)
7389           OpInfo.CallOperand =
7390               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
7391         OpInfo.ConstraintVT = VT;
7392       }
7393     }
7394   }
7395 
7396   // No need to allocate a matching input constraint since the constraint it's
7397   // matching to has already been allocated.
7398   if (OpInfo.isMatchingInputConstraint())
7399     return;
7400 
7401   EVT ValueVT = OpInfo.ConstraintVT;
7402   if (OpInfo.ConstraintVT == MVT::Other)
7403     ValueVT = RegVT;
7404 
7405   // Initialize NumRegs.
7406   unsigned NumRegs = 1;
7407   if (OpInfo.ConstraintVT != MVT::Other)
7408     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
7409 
7410   // If this is a constraint for a specific physical register, like {r17},
7411   // assign it now.
7412 
7413   // If this associated to a specific register, initialize iterator to correct
7414   // place. If virtual, make sure we have enough registers
7415 
7416   // Initialize iterator if necessary
7417   TargetRegisterClass::iterator I = RC->begin();
7418   MachineRegisterInfo &RegInfo = MF.getRegInfo();
7419 
7420   // Do not check for single registers.
7421   if (AssignedReg) {
7422       for (; *I != AssignedReg; ++I)
7423         assert(I != RC->end() && "AssignedReg should be member of RC");
7424   }
7425 
7426   for (; NumRegs; --NumRegs, ++I) {
7427     assert(I != RC->end() && "Ran out of registers to allocate!");
7428     auto R = (AssignedReg) ? *I : RegInfo.createVirtualRegister(RC);
7429     Regs.push_back(R);
7430   }
7431 
7432   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
7433 }
7434 
7435 static unsigned
7436 findMatchingInlineAsmOperand(unsigned OperandNo,
7437                              const std::vector<SDValue> &AsmNodeOperands) {
7438   // Scan until we find the definition we already emitted of this operand.
7439   unsigned CurOp = InlineAsm::Op_FirstOperand;
7440   for (; OperandNo; --OperandNo) {
7441     // Advance to the next operand.
7442     unsigned OpFlag =
7443         cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7444     assert((InlineAsm::isRegDefKind(OpFlag) ||
7445             InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
7446             InlineAsm::isMemKind(OpFlag)) &&
7447            "Skipped past definitions?");
7448     CurOp += InlineAsm::getNumOperandRegisters(OpFlag) + 1;
7449   }
7450   return CurOp;
7451 }
7452 
7453 namespace {
7454 
7455 class ExtraFlags {
7456   unsigned Flags = 0;
7457 
7458 public:
7459   explicit ExtraFlags(ImmutableCallSite CS) {
7460     const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7461     if (IA->hasSideEffects())
7462       Flags |= InlineAsm::Extra_HasSideEffects;
7463     if (IA->isAlignStack())
7464       Flags |= InlineAsm::Extra_IsAlignStack;
7465     if (CS.isConvergent())
7466       Flags |= InlineAsm::Extra_IsConvergent;
7467     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
7468   }
7469 
7470   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
7471     // Ideally, we would only check against memory constraints.  However, the
7472     // meaning of an Other constraint can be target-specific and we can't easily
7473     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
7474     // for Other constraints as well.
7475     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
7476         OpInfo.ConstraintType == TargetLowering::C_Other) {
7477       if (OpInfo.Type == InlineAsm::isInput)
7478         Flags |= InlineAsm::Extra_MayLoad;
7479       else if (OpInfo.Type == InlineAsm::isOutput)
7480         Flags |= InlineAsm::Extra_MayStore;
7481       else if (OpInfo.Type == InlineAsm::isClobber)
7482         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
7483     }
7484   }
7485 
7486   unsigned get() const { return Flags; }
7487 };
7488 
7489 } // end anonymous namespace
7490 
7491 /// visitInlineAsm - Handle a call to an InlineAsm object.
7492 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
7493   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
7494 
7495   /// ConstraintOperands - Information about all of the constraints.
7496   SDISelAsmOperandInfoVector ConstraintOperands;
7497 
7498   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7499   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
7500       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), CS);
7501 
7502   bool hasMemory = false;
7503 
7504   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7505   ExtraFlags ExtraInfo(CS);
7506 
7507   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
7508   unsigned ResNo = 0;   // ResNo - The result number of the next output.
7509   for (auto &T : TargetConstraints) {
7510     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
7511     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
7512 
7513     // Compute the value type for each operand.
7514     if (OpInfo.Type == InlineAsm::isInput ||
7515         (OpInfo.Type == InlineAsm::isOutput && OpInfo.isIndirect)) {
7516       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
7517 
7518       // Process the call argument. BasicBlocks are labels, currently appearing
7519       // only in asm's.
7520       if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
7521         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
7522       } else {
7523         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
7524       }
7525 
7526       OpInfo.ConstraintVT =
7527           OpInfo
7528               .getCallOperandValEVT(*DAG.getContext(), TLI, DAG.getDataLayout())
7529               .getSimpleVT();
7530     } else if (OpInfo.Type == InlineAsm::isOutput && !OpInfo.isIndirect) {
7531       // The return value of the call is this value.  As such, there is no
7532       // corresponding argument.
7533       assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7534       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
7535         OpInfo.ConstraintVT = TLI.getSimpleValueType(
7536             DAG.getDataLayout(), STy->getElementType(ResNo));
7537       } else {
7538         assert(ResNo == 0 && "Asm only has one result!");
7539         OpInfo.ConstraintVT =
7540             TLI.getSimpleValueType(DAG.getDataLayout(), CS.getType());
7541       }
7542       ++ResNo;
7543     } else {
7544       OpInfo.ConstraintVT = MVT::Other;
7545     }
7546 
7547     if (!hasMemory)
7548       hasMemory = OpInfo.hasMemory(TLI);
7549 
7550     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
7551     // FIXME: Could we compute this on OpInfo rather than T?
7552 
7553     // Compute the constraint code and ConstraintType to use.
7554     TLI.ComputeConstraintToUse(T, SDValue());
7555 
7556     ExtraInfo.update(T);
7557   }
7558 
7559   SDValue Chain, Flag;
7560 
7561   // We won't need to flush pending loads if this asm doesn't touch
7562   // memory and is nonvolatile.
7563   if (hasMemory || IA->hasSideEffects())
7564     Chain = getRoot();
7565   else
7566     Chain = DAG.getRoot();
7567 
7568   // Second pass over the constraints: compute which constraint option to use
7569   // and assign registers to constraints that want a specific physreg.
7570   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7571     // If this is an output operand with a matching input operand, look up the
7572     // matching input. If their types mismatch, e.g. one is an integer, the
7573     // other is floating point, or their sizes are different, flag it as an
7574     // error.
7575     if (OpInfo.hasMatchingInput()) {
7576       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
7577       patchMatchingInput(OpInfo, Input, DAG);
7578     }
7579 
7580     // Compute the constraint code and ConstraintType to use.
7581     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
7582 
7583     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7584         OpInfo.Type == InlineAsm::isClobber)
7585       continue;
7586 
7587     // If this is a memory input, and if the operand is not indirect, do what we
7588     // need to provide an address for the memory input.
7589     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
7590         !OpInfo.isIndirect) {
7591       assert((OpInfo.isMultipleAlternative ||
7592               (OpInfo.Type == InlineAsm::isInput)) &&
7593              "Can only indirectify direct input operands!");
7594 
7595       // Memory operands really want the address of the value.
7596       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
7597 
7598       // There is no longer a Value* corresponding to this operand.
7599       OpInfo.CallOperandVal = nullptr;
7600 
7601       // It is now an indirect operand.
7602       OpInfo.isIndirect = true;
7603     }
7604 
7605     // If this constraint is for a specific register, allocate it before
7606     // anything else.
7607     SDISelAsmOperandInfo &RefOpInfo =
7608         OpInfo.isMatchingInputConstraint()
7609             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7610             : OpInfo;
7611     if (RefOpInfo.ConstraintType == TargetLowering::C_Register)
7612       GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
7613   }
7614 
7615   // Third pass - Loop over all of the operands, assigning virtual or physregs
7616   // to register class operands.
7617   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7618     SDISelAsmOperandInfo &RefOpInfo =
7619         OpInfo.isMatchingInputConstraint()
7620             ? ConstraintOperands[OpInfo.getMatchedOperand()]
7621             : OpInfo;
7622 
7623     // C_Register operands have already been allocated, Other/Memory don't need
7624     // to be.
7625     if (RefOpInfo.ConstraintType == TargetLowering::C_RegisterClass)
7626       GetRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
7627   }
7628 
7629   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
7630   std::vector<SDValue> AsmNodeOperands;
7631   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
7632   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
7633       IA->getAsmString().c_str(), TLI.getPointerTy(DAG.getDataLayout())));
7634 
7635   // If we have a !srcloc metadata node associated with it, we want to attach
7636   // this to the ultimately generated inline asm machineinstr.  To do this, we
7637   // pass in the third operand as this (potentially null) inline asm MDNode.
7638   const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
7639   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
7640 
7641   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
7642   // bits as operand 3.
7643   AsmNodeOperands.push_back(DAG.getTargetConstant(
7644       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7645 
7646   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7647     switch (OpInfo.Type) {
7648     case InlineAsm::isOutput:
7649       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
7650           OpInfo.ConstraintType != TargetLowering::C_Register) {
7651         // Memory output, or 'other' output (e.g. 'X' constraint).
7652         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
7653 
7654         unsigned ConstraintID =
7655             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7656         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7657                "Failed to convert memory constraint code to constraint id.");
7658 
7659         // Add information to the INLINEASM node to know about this output.
7660         unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7661         OpFlags = InlineAsm::getFlagWordForMem(OpFlags, ConstraintID);
7662         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
7663                                                         MVT::i32));
7664         AsmNodeOperands.push_back(OpInfo.CallOperand);
7665         break;
7666       } else if (OpInfo.ConstraintType == TargetLowering::C_Register ||
7667                  OpInfo.ConstraintType == TargetLowering::C_RegisterClass) {
7668         // Otherwise, this is a register or register class output.
7669 
7670         // Copy the output from the appropriate register.  Find a register that
7671         // we can use.
7672         if (OpInfo.AssignedRegs.Regs.empty()) {
7673           emitInlineAsmError(
7674               CS, "couldn't allocate output register for constraint '" +
7675                       Twine(OpInfo.ConstraintCode) + "'");
7676           return;
7677         }
7678 
7679         // Add information to the INLINEASM node to know that this register is
7680         // set.
7681         OpInfo.AssignedRegs.AddInlineAsmOperands(
7682             OpInfo.isEarlyClobber ? InlineAsm::Kind_RegDefEarlyClobber
7683                                   : InlineAsm::Kind_RegDef,
7684             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
7685       }
7686       break;
7687 
7688     case InlineAsm::isInput: {
7689       SDValue InOperandVal = OpInfo.CallOperand;
7690 
7691       if (OpInfo.isMatchingInputConstraint()) {
7692         // If this is required to match an output register we have already set,
7693         // just use its register.
7694         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
7695                                                   AsmNodeOperands);
7696         unsigned OpFlag =
7697           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
7698         if (InlineAsm::isRegDefKind(OpFlag) ||
7699             InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
7700           // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
7701           if (OpInfo.isIndirect) {
7702             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
7703             emitInlineAsmError(CS, "inline asm not supported yet:"
7704                                    " don't know how to handle tied "
7705                                    "indirect register inputs");
7706             return;
7707           }
7708 
7709           MVT RegVT = AsmNodeOperands[CurOp+1].getSimpleValueType();
7710           SmallVector<unsigned, 4> Regs;
7711 
7712           if (const TargetRegisterClass *RC = TLI.getRegClassFor(RegVT)) {
7713             unsigned NumRegs = InlineAsm::getNumOperandRegisters(OpFlag);
7714             MachineRegisterInfo &RegInfo =
7715                 DAG.getMachineFunction().getRegInfo();
7716             for (unsigned i = 0; i != NumRegs; ++i)
7717               Regs.push_back(RegInfo.createVirtualRegister(RC));
7718           } else {
7719             emitInlineAsmError(CS, "inline asm error: This value type register "
7720                                    "class is not natively supported!");
7721             return;
7722           }
7723 
7724           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
7725 
7726           SDLoc dl = getCurSDLoc();
7727           // Use the produced MatchedRegs object to
7728           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Flag,
7729                                     CS.getInstruction());
7730           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
7731                                            true, OpInfo.getMatchedOperand(), dl,
7732                                            DAG, AsmNodeOperands);
7733           break;
7734         }
7735 
7736         assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
7737         assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
7738                "Unexpected number of operands");
7739         // Add information to the INLINEASM node to know about this input.
7740         // See InlineAsm.h isUseOperandTiedToDef.
7741         OpFlag = InlineAsm::convertMemFlagWordToMatchingFlagWord(OpFlag);
7742         OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
7743                                                     OpInfo.getMatchedOperand());
7744         AsmNodeOperands.push_back(DAG.getTargetConstant(
7745             OpFlag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7746         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
7747         break;
7748       }
7749 
7750       // Treat indirect 'X' constraint as memory.
7751       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
7752           OpInfo.isIndirect)
7753         OpInfo.ConstraintType = TargetLowering::C_Memory;
7754 
7755       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
7756         std::vector<SDValue> Ops;
7757         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
7758                                           Ops, DAG);
7759         if (Ops.empty()) {
7760           emitInlineAsmError(CS, "invalid operand for inline asm constraint '" +
7761                                      Twine(OpInfo.ConstraintCode) + "'");
7762           return;
7763         }
7764 
7765         // Add information to the INLINEASM node to know about this input.
7766         unsigned ResOpType =
7767           InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
7768         AsmNodeOperands.push_back(DAG.getTargetConstant(
7769             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
7770         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
7771         break;
7772       }
7773 
7774       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
7775         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
7776         assert(InOperandVal.getValueType() ==
7777                    TLI.getPointerTy(DAG.getDataLayout()) &&
7778                "Memory operands expect pointer values");
7779 
7780         unsigned ConstraintID =
7781             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
7782         assert(ConstraintID != InlineAsm::Constraint_Unknown &&
7783                "Failed to convert memory constraint code to constraint id.");
7784 
7785         // Add information to the INLINEASM node to know about this input.
7786         unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
7787         ResOpType = InlineAsm::getFlagWordForMem(ResOpType, ConstraintID);
7788         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
7789                                                         getCurSDLoc(),
7790                                                         MVT::i32));
7791         AsmNodeOperands.push_back(InOperandVal);
7792         break;
7793       }
7794 
7795       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
7796               OpInfo.ConstraintType == TargetLowering::C_Register) &&
7797              "Unknown constraint type!");
7798 
7799       // TODO: Support this.
7800       if (OpInfo.isIndirect) {
7801         emitInlineAsmError(
7802             CS, "Don't know how to handle indirect register inputs yet "
7803                 "for constraint '" +
7804                     Twine(OpInfo.ConstraintCode) + "'");
7805         return;
7806       }
7807 
7808       // Copy the input into the appropriate registers.
7809       if (OpInfo.AssignedRegs.Regs.empty()) {
7810         emitInlineAsmError(CS, "couldn't allocate input reg for constraint '" +
7811                                    Twine(OpInfo.ConstraintCode) + "'");
7812         return;
7813       }
7814 
7815       SDLoc dl = getCurSDLoc();
7816 
7817       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl,
7818                                         Chain, &Flag, CS.getInstruction());
7819 
7820       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
7821                                                dl, DAG, AsmNodeOperands);
7822       break;
7823     }
7824     case InlineAsm::isClobber:
7825       // Add the clobbered value to the operand list, so that the register
7826       // allocator is aware that the physreg got clobbered.
7827       if (!OpInfo.AssignedRegs.Regs.empty())
7828         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
7829                                                  false, 0, getCurSDLoc(), DAG,
7830                                                  AsmNodeOperands);
7831       break;
7832     }
7833   }
7834 
7835   // Finish up input operands.  Set the input chain and add the flag last.
7836   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
7837   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
7838 
7839   Chain = DAG.getNode(ISD::INLINEASM, getCurSDLoc(),
7840                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
7841   Flag = Chain.getValue(1);
7842 
7843   // Do additional work to generate outputs.
7844 
7845   SmallVector<EVT, 1> ResultVTs;
7846   SmallVector<SDValue, 1> ResultValues;
7847   SmallVector<SDValue, 8> OutChains;
7848 
7849   llvm::Type *CSResultType = CS.getType();
7850   unsigned NumReturns = 0;
7851   ArrayRef<Type *> ResultTypes;
7852   if (StructType *StructResult = dyn_cast<StructType>(CSResultType)) {
7853     NumReturns = StructResult->getNumElements();
7854     ResultTypes = StructResult->elements();
7855   } else if (!CSResultType->isVoidTy()) {
7856     NumReturns = 1;
7857     ResultTypes = makeArrayRef(CSResultType);
7858   }
7859 
7860   auto CurResultType = ResultTypes.begin();
7861   auto handleRegAssign = [&](SDValue V) {
7862     assert(CurResultType != ResultTypes.end() && "Unexpected value");
7863     assert((*CurResultType)->isSized() && "Unexpected unsized type");
7864     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
7865     ++CurResultType;
7866     // If the type of the inline asm call site return value is different but has
7867     // same size as the type of the asm output bitcast it.  One example of this
7868     // is for vectors with different width / number of elements.  This can
7869     // happen for register classes that can contain multiple different value
7870     // types.  The preg or vreg allocated may not have the same VT as was
7871     // expected.
7872     //
7873     // This can also happen for a return value that disagrees with the register
7874     // class it is put in, eg. a double in a general-purpose register on a
7875     // 32-bit machine.
7876     if (ResultVT != V.getValueType() &&
7877         ResultVT.getSizeInBits() == V.getValueSizeInBits())
7878       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
7879     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
7880              V.getValueType().isInteger()) {
7881       // If a result value was tied to an input value, the computed result
7882       // may have a wider width than the expected result.  Extract the
7883       // relevant portion.
7884       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
7885     }
7886     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
7887     ResultVTs.push_back(ResultVT);
7888     ResultValues.push_back(V);
7889   };
7890 
7891   // Deal with assembly output fixups.
7892   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
7893     if (OpInfo.Type == InlineAsm::isOutput &&
7894         (OpInfo.ConstraintType == TargetLowering::C_Register ||
7895          OpInfo.ConstraintType == TargetLowering::C_RegisterClass)) {
7896       if (OpInfo.isIndirect) {
7897         // Register indirect are manifest as stores.
7898         const RegsForValue &OutRegs = OpInfo.AssignedRegs;
7899         const Value *Ptr = OpInfo.CallOperandVal;
7900         SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
7901                                                  Chain, &Flag, IA);
7902         SDValue Val = DAG.getStore(Chain, getCurSDLoc(), OutVal, getValue(Ptr),
7903                                    MachinePointerInfo(Ptr));
7904         OutChains.push_back(Val);
7905       } else {
7906         // generate CopyFromRegs to associated registers.
7907         assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
7908         SDValue Val = OpInfo.AssignedRegs.getCopyFromRegs(
7909             DAG, FuncInfo, getCurSDLoc(), Chain, &Flag, CS.getInstruction());
7910         if (Val.getOpcode() == ISD::MERGE_VALUES) {
7911           for (const SDValue &V : Val->op_values())
7912             handleRegAssign(V);
7913         } else
7914           handleRegAssign(Val);
7915       }
7916     }
7917   }
7918 
7919   // Set results.
7920   if (!ResultValues.empty()) {
7921     assert(CurResultType == ResultTypes.end() &&
7922            "Mismatch in number of ResultTypes");
7923     assert(ResultValues.size() == NumReturns &&
7924            "Mismatch in number of output operands in asm result");
7925 
7926     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
7927                             DAG.getVTList(ResultVTs), ResultValues);
7928     setValue(CS.getInstruction(), V);
7929   }
7930 
7931   // Collect store chains.
7932   if (!OutChains.empty())
7933     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
7934 
7935   // Only Update Root if inline assembly has a memory effect.
7936   if (ResultValues.empty() || IA->hasSideEffects() || hasMemory ||
7937       !OutChains.empty())
7938     DAG.setRoot(Chain);
7939 }
7940 
7941 void SelectionDAGBuilder::emitInlineAsmError(ImmutableCallSite CS,
7942                                              const Twine &Message) {
7943   LLVMContext &Ctx = *DAG.getContext();
7944   Ctx.emitError(CS.getInstruction(), Message);
7945 
7946   // Make sure we leave the DAG in a valid state
7947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7948   SmallVector<EVT, 1> ValueVTs;
7949   ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
7950 
7951   if (ValueVTs.empty())
7952     return;
7953 
7954   SmallVector<SDValue, 1> Ops;
7955   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
7956     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
7957 
7958   setValue(CS.getInstruction(), DAG.getMergeValues(Ops, getCurSDLoc()));
7959 }
7960 
7961 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
7962   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
7963                           MVT::Other, getRoot(),
7964                           getValue(I.getArgOperand(0)),
7965                           DAG.getSrcValue(I.getArgOperand(0))));
7966 }
7967 
7968 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
7969   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7970   const DataLayout &DL = DAG.getDataLayout();
7971   SDValue V = DAG.getVAArg(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7972                            getCurSDLoc(), getRoot(), getValue(I.getOperand(0)),
7973                            DAG.getSrcValue(I.getOperand(0)),
7974                            DL.getABITypeAlignment(I.getType()));
7975   setValue(&I, V);
7976   DAG.setRoot(V.getValue(1));
7977 }
7978 
7979 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
7980   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
7981                           MVT::Other, getRoot(),
7982                           getValue(I.getArgOperand(0)),
7983                           DAG.getSrcValue(I.getArgOperand(0))));
7984 }
7985 
7986 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
7987   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
7988                           MVT::Other, getRoot(),
7989                           getValue(I.getArgOperand(0)),
7990                           getValue(I.getArgOperand(1)),
7991                           DAG.getSrcValue(I.getArgOperand(0)),
7992                           DAG.getSrcValue(I.getArgOperand(1))));
7993 }
7994 
7995 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
7996                                                     const Instruction &I,
7997                                                     SDValue Op) {
7998   const MDNode *Range = I.getMetadata(LLVMContext::MD_range);
7999   if (!Range)
8000     return Op;
8001 
8002   ConstantRange CR = getConstantRangeFromMetadata(*Range);
8003   if (CR.isFullSet() || CR.isEmptySet() || CR.isWrappedSet())
8004     return Op;
8005 
8006   APInt Lo = CR.getUnsignedMin();
8007   if (!Lo.isMinValue())
8008     return Op;
8009 
8010   APInt Hi = CR.getUnsignedMax();
8011   unsigned Bits = std::max(Hi.getActiveBits(),
8012                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
8013 
8014   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8015 
8016   SDLoc SL = getCurSDLoc();
8017 
8018   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
8019                              DAG.getValueType(SmallVT));
8020   unsigned NumVals = Op.getNode()->getNumValues();
8021   if (NumVals == 1)
8022     return ZExt;
8023 
8024   SmallVector<SDValue, 4> Ops;
8025 
8026   Ops.push_back(ZExt);
8027   for (unsigned I = 1; I != NumVals; ++I)
8028     Ops.push_back(Op.getValue(I));
8029 
8030   return DAG.getMergeValues(Ops, SL);
8031 }
8032 
8033 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
8034 /// the call being lowered.
8035 ///
8036 /// This is a helper for lowering intrinsics that follow a target calling
8037 /// convention or require stack pointer adjustment. Only a subset of the
8038 /// intrinsic's operands need to participate in the calling convention.
8039 void SelectionDAGBuilder::populateCallLoweringInfo(
8040     TargetLowering::CallLoweringInfo &CLI, ImmutableCallSite CS,
8041     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
8042     bool IsPatchPoint) {
8043   TargetLowering::ArgListTy Args;
8044   Args.reserve(NumArgs);
8045 
8046   // Populate the argument list.
8047   // Attributes for args start at offset 1, after the return attribute.
8048   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
8049        ArgI != ArgE; ++ArgI) {
8050     const Value *V = CS->getOperand(ArgI);
8051 
8052     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
8053 
8054     TargetLowering::ArgListEntry Entry;
8055     Entry.Node = getValue(V);
8056     Entry.Ty = V->getType();
8057     Entry.setAttributes(&CS, ArgI);
8058     Args.push_back(Entry);
8059   }
8060 
8061   CLI.setDebugLoc(getCurSDLoc())
8062       .setChain(getRoot())
8063       .setCallee(CS.getCallingConv(), ReturnTy, Callee, std::move(Args))
8064       .setDiscardResult(CS->use_empty())
8065       .setIsPatchPoint(IsPatchPoint);
8066 }
8067 
8068 /// Add a stack map intrinsic call's live variable operands to a stackmap
8069 /// or patchpoint target node's operand list.
8070 ///
8071 /// Constants are converted to TargetConstants purely as an optimization to
8072 /// avoid constant materialization and register allocation.
8073 ///
8074 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
8075 /// generate addess computation nodes, and so ExpandISelPseudo can convert the
8076 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
8077 /// address materialization and register allocation, but may also be required
8078 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
8079 /// alloca in the entry block, then the runtime may assume that the alloca's
8080 /// StackMap location can be read immediately after compilation and that the
8081 /// location is valid at any point during execution (this is similar to the
8082 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
8083 /// only available in a register, then the runtime would need to trap when
8084 /// execution reaches the StackMap in order to read the alloca's location.
8085 static void addStackMapLiveVars(ImmutableCallSite CS, unsigned StartIdx,
8086                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
8087                                 SelectionDAGBuilder &Builder) {
8088   for (unsigned i = StartIdx, e = CS.arg_size(); i != e; ++i) {
8089     SDValue OpVal = Builder.getValue(CS.getArgument(i));
8090     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(OpVal)) {
8091       Ops.push_back(
8092         Builder.DAG.getTargetConstant(StackMaps::ConstantOp, DL, MVT::i64));
8093       Ops.push_back(
8094         Builder.DAG.getTargetConstant(C->getSExtValue(), DL, MVT::i64));
8095     } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(OpVal)) {
8096       const TargetLowering &TLI = Builder.DAG.getTargetLoweringInfo();
8097       Ops.push_back(Builder.DAG.getTargetFrameIndex(
8098           FI->getIndex(), TLI.getFrameIndexTy(Builder.DAG.getDataLayout())));
8099     } else
8100       Ops.push_back(OpVal);
8101   }
8102 }
8103 
8104 /// Lower llvm.experimental.stackmap directly to its target opcode.
8105 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
8106   // void @llvm.experimental.stackmap(i32 <id>, i32 <numShadowBytes>,
8107   //                                  [live variables...])
8108 
8109   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
8110 
8111   SDValue Chain, InFlag, Callee, NullPtr;
8112   SmallVector<SDValue, 32> Ops;
8113 
8114   SDLoc DL = getCurSDLoc();
8115   Callee = getValue(CI.getCalledValue());
8116   NullPtr = DAG.getIntPtrConstant(0, DL, true);
8117 
8118   // The stackmap intrinsic only records the live variables (the arguemnts
8119   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
8120   // intrinsic, this won't be lowered to a function call. This means we don't
8121   // have to worry about calling conventions and target specific lowering code.
8122   // Instead we perform the call lowering right here.
8123   //
8124   // chain, flag = CALLSEQ_START(chain, 0, 0)
8125   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
8126   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
8127   //
8128   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
8129   InFlag = Chain.getValue(1);
8130 
8131   // Add the <id> and <numBytes> constants.
8132   SDValue IDVal = getValue(CI.getOperand(PatchPointOpers::IDPos));
8133   Ops.push_back(DAG.getTargetConstant(
8134                   cast<ConstantSDNode>(IDVal)->getZExtValue(), DL, MVT::i64));
8135   SDValue NBytesVal = getValue(CI.getOperand(PatchPointOpers::NBytesPos));
8136   Ops.push_back(DAG.getTargetConstant(
8137                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), DL,
8138                   MVT::i32));
8139 
8140   // Push live variables for the stack map.
8141   addStackMapLiveVars(&CI, 2, DL, Ops, *this);
8142 
8143   // We are not pushing any register mask info here on the operands list,
8144   // because the stackmap doesn't clobber anything.
8145 
8146   // Push the chain and the glue flag.
8147   Ops.push_back(Chain);
8148   Ops.push_back(InFlag);
8149 
8150   // Create the STACKMAP node.
8151   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8152   SDNode *SM = DAG.getMachineNode(TargetOpcode::STACKMAP, DL, NodeTys, Ops);
8153   Chain = SDValue(SM, 0);
8154   InFlag = Chain.getValue(1);
8155 
8156   Chain = DAG.getCALLSEQ_END(Chain, NullPtr, NullPtr, InFlag, DL);
8157 
8158   // Stackmaps don't generate values, so nothing goes into the NodeMap.
8159 
8160   // Set the root to the target-lowered call chain.
8161   DAG.setRoot(Chain);
8162 
8163   // Inform the Frame Information that we have a stackmap in this function.
8164   FuncInfo.MF->getFrameInfo().setHasStackMap();
8165 }
8166 
8167 /// Lower llvm.experimental.patchpoint directly to its target opcode.
8168 void SelectionDAGBuilder::visitPatchpoint(ImmutableCallSite CS,
8169                                           const BasicBlock *EHPadBB) {
8170   // void|i64 @llvm.experimental.patchpoint.void|i64(i64 <id>,
8171   //                                                 i32 <numBytes>,
8172   //                                                 i8* <target>,
8173   //                                                 i32 <numArgs>,
8174   //                                                 [Args...],
8175   //                                                 [live variables...])
8176 
8177   CallingConv::ID CC = CS.getCallingConv();
8178   bool IsAnyRegCC = CC == CallingConv::AnyReg;
8179   bool HasDef = !CS->getType()->isVoidTy();
8180   SDLoc dl = getCurSDLoc();
8181   SDValue Callee = getValue(CS->getOperand(PatchPointOpers::TargetPos));
8182 
8183   // Handle immediate and symbolic callees.
8184   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
8185     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
8186                                    /*isTarget=*/true);
8187   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
8188     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
8189                                          SDLoc(SymbolicCallee),
8190                                          SymbolicCallee->getValueType(0));
8191 
8192   // Get the real number of arguments participating in the call <numArgs>
8193   SDValue NArgVal = getValue(CS.getArgument(PatchPointOpers::NArgPos));
8194   unsigned NumArgs = cast<ConstantSDNode>(NArgVal)->getZExtValue();
8195 
8196   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
8197   // Intrinsics include all meta-operands up to but not including CC.
8198   unsigned NumMetaOpers = PatchPointOpers::CCPos;
8199   assert(CS.arg_size() >= NumMetaOpers + NumArgs &&
8200          "Not enough arguments provided to the patchpoint intrinsic");
8201 
8202   // For AnyRegCC the arguments are lowered later on manually.
8203   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
8204   Type *ReturnTy =
8205     IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CS->getType();
8206 
8207   TargetLowering::CallLoweringInfo CLI(DAG);
8208   populateCallLoweringInfo(CLI, CS, NumMetaOpers, NumCallArgs, Callee, ReturnTy,
8209                            true);
8210   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8211 
8212   SDNode *CallEnd = Result.second.getNode();
8213   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
8214     CallEnd = CallEnd->getOperand(0).getNode();
8215 
8216   /// Get a call instruction from the call sequence chain.
8217   /// Tail calls are not allowed.
8218   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
8219          "Expected a callseq node.");
8220   SDNode *Call = CallEnd->getOperand(0).getNode();
8221   bool HasGlue = Call->getGluedNode();
8222 
8223   // Replace the target specific call node with the patchable intrinsic.
8224   SmallVector<SDValue, 8> Ops;
8225 
8226   // Add the <id> and <numBytes> constants.
8227   SDValue IDVal = getValue(CS->getOperand(PatchPointOpers::IDPos));
8228   Ops.push_back(DAG.getTargetConstant(
8229                   cast<ConstantSDNode>(IDVal)->getZExtValue(), dl, MVT::i64));
8230   SDValue NBytesVal = getValue(CS->getOperand(PatchPointOpers::NBytesPos));
8231   Ops.push_back(DAG.getTargetConstant(
8232                   cast<ConstantSDNode>(NBytesVal)->getZExtValue(), dl,
8233                   MVT::i32));
8234 
8235   // Add the callee.
8236   Ops.push_back(Callee);
8237 
8238   // Adjust <numArgs> to account for any arguments that have been passed on the
8239   // stack instead.
8240   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
8241   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
8242   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
8243   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
8244 
8245   // Add the calling convention
8246   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
8247 
8248   // Add the arguments we omitted previously. The register allocator should
8249   // place these in any free register.
8250   if (IsAnyRegCC)
8251     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
8252       Ops.push_back(getValue(CS.getArgument(i)));
8253 
8254   // Push the arguments from the call instruction up to the register mask.
8255   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
8256   Ops.append(Call->op_begin() + 2, e);
8257 
8258   // Push live variables for the stack map.
8259   addStackMapLiveVars(CS, NumMetaOpers + NumArgs, dl, Ops, *this);
8260 
8261   // Push the register mask info.
8262   if (HasGlue)
8263     Ops.push_back(*(Call->op_end()-2));
8264   else
8265     Ops.push_back(*(Call->op_end()-1));
8266 
8267   // Push the chain (this is originally the first operand of the call, but
8268   // becomes now the last or second to last operand).
8269   Ops.push_back(*(Call->op_begin()));
8270 
8271   // Push the glue flag (last operand).
8272   if (HasGlue)
8273     Ops.push_back(*(Call->op_end()-1));
8274 
8275   SDVTList NodeTys;
8276   if (IsAnyRegCC && HasDef) {
8277     // Create the return types based on the intrinsic definition
8278     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8279     SmallVector<EVT, 3> ValueVTs;
8280     ComputeValueVTs(TLI, DAG.getDataLayout(), CS->getType(), ValueVTs);
8281     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
8282 
8283     // There is always a chain and a glue type at the end
8284     ValueVTs.push_back(MVT::Other);
8285     ValueVTs.push_back(MVT::Glue);
8286     NodeTys = DAG.getVTList(ValueVTs);
8287   } else
8288     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8289 
8290   // Replace the target specific call node with a PATCHPOINT node.
8291   MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHPOINT,
8292                                          dl, NodeTys, Ops);
8293 
8294   // Update the NodeMap.
8295   if (HasDef) {
8296     if (IsAnyRegCC)
8297       setValue(CS.getInstruction(), SDValue(MN, 0));
8298     else
8299       setValue(CS.getInstruction(), Result.first);
8300   }
8301 
8302   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
8303   // call sequence. Furthermore the location of the chain and glue can change
8304   // when the AnyReg calling convention is used and the intrinsic returns a
8305   // value.
8306   if (IsAnyRegCC && HasDef) {
8307     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
8308     SDValue To[] = {SDValue(MN, 1), SDValue(MN, 2)};
8309     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8310   } else
8311     DAG.ReplaceAllUsesWith(Call, MN);
8312   DAG.DeleteNode(Call);
8313 
8314   // Inform the Frame Information that we have a patchpoint in this function.
8315   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
8316 }
8317 
8318 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
8319                                             unsigned Intrinsic) {
8320   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8321   SDValue Op1 = getValue(I.getArgOperand(0));
8322   SDValue Op2;
8323   if (I.getNumArgOperands() > 1)
8324     Op2 = getValue(I.getArgOperand(1));
8325   SDLoc dl = getCurSDLoc();
8326   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8327   SDValue Res;
8328   FastMathFlags FMF;
8329   if (isa<FPMathOperator>(I))
8330     FMF = I.getFastMathFlags();
8331 
8332   switch (Intrinsic) {
8333   case Intrinsic::experimental_vector_reduce_fadd:
8334     if (FMF.isFast())
8335       Res = DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2);
8336     else
8337       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FADD, dl, VT, Op1, Op2);
8338     break;
8339   case Intrinsic::experimental_vector_reduce_fmul:
8340     if (FMF.isFast())
8341       Res = DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2);
8342     else
8343       Res = DAG.getNode(ISD::VECREDUCE_STRICT_FMUL, dl, VT, Op1, Op2);
8344     break;
8345   case Intrinsic::experimental_vector_reduce_add:
8346     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
8347     break;
8348   case Intrinsic::experimental_vector_reduce_mul:
8349     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
8350     break;
8351   case Intrinsic::experimental_vector_reduce_and:
8352     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
8353     break;
8354   case Intrinsic::experimental_vector_reduce_or:
8355     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
8356     break;
8357   case Intrinsic::experimental_vector_reduce_xor:
8358     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
8359     break;
8360   case Intrinsic::experimental_vector_reduce_smax:
8361     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
8362     break;
8363   case Intrinsic::experimental_vector_reduce_smin:
8364     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
8365     break;
8366   case Intrinsic::experimental_vector_reduce_umax:
8367     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
8368     break;
8369   case Intrinsic::experimental_vector_reduce_umin:
8370     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
8371     break;
8372   case Intrinsic::experimental_vector_reduce_fmax:
8373     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1);
8374     break;
8375   case Intrinsic::experimental_vector_reduce_fmin:
8376     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1);
8377     break;
8378   default:
8379     llvm_unreachable("Unhandled vector reduce intrinsic");
8380   }
8381   setValue(&I, Res);
8382 }
8383 
8384 /// Returns an AttributeList representing the attributes applied to the return
8385 /// value of the given call.
8386 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
8387   SmallVector<Attribute::AttrKind, 2> Attrs;
8388   if (CLI.RetSExt)
8389     Attrs.push_back(Attribute::SExt);
8390   if (CLI.RetZExt)
8391     Attrs.push_back(Attribute::ZExt);
8392   if (CLI.IsInReg)
8393     Attrs.push_back(Attribute::InReg);
8394 
8395   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
8396                             Attrs);
8397 }
8398 
8399 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
8400 /// implementation, which just calls LowerCall.
8401 /// FIXME: When all targets are
8402 /// migrated to using LowerCall, this hook should be integrated into SDISel.
8403 std::pair<SDValue, SDValue>
8404 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
8405   // Handle the incoming return values from the call.
8406   CLI.Ins.clear();
8407   Type *OrigRetTy = CLI.RetTy;
8408   SmallVector<EVT, 4> RetTys;
8409   SmallVector<uint64_t, 4> Offsets;
8410   auto &DL = CLI.DAG.getDataLayout();
8411   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
8412 
8413   if (CLI.IsPostTypeLegalization) {
8414     // If we are lowering a libcall after legalization, split the return type.
8415     SmallVector<EVT, 4> OldRetTys = std::move(RetTys);
8416     SmallVector<uint64_t, 4> OldOffsets = std::move(Offsets);
8417     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
8418       EVT RetVT = OldRetTys[i];
8419       uint64_t Offset = OldOffsets[i];
8420       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
8421       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
8422       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
8423       RetTys.append(NumRegs, RegisterVT);
8424       for (unsigned j = 0; j != NumRegs; ++j)
8425         Offsets.push_back(Offset + j * RegisterVTByteSZ);
8426     }
8427   }
8428 
8429   SmallVector<ISD::OutputArg, 4> Outs;
8430   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
8431 
8432   bool CanLowerReturn =
8433       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
8434                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
8435 
8436   SDValue DemoteStackSlot;
8437   int DemoteStackIdx = -100;
8438   if (!CanLowerReturn) {
8439     // FIXME: equivalent assert?
8440     // assert(!CS.hasInAllocaArgument() &&
8441     //        "sret demotion is incompatible with inalloca");
8442     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
8443     unsigned Align = DL.getPrefTypeAlignment(CLI.RetTy);
8444     MachineFunction &MF = CLI.DAG.getMachineFunction();
8445     DemoteStackIdx = MF.getFrameInfo().CreateStackObject(TySize, Align, false);
8446     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
8447                                               DL.getAllocaAddrSpace());
8448 
8449     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
8450     ArgListEntry Entry;
8451     Entry.Node = DemoteStackSlot;
8452     Entry.Ty = StackSlotPtrType;
8453     Entry.IsSExt = false;
8454     Entry.IsZExt = false;
8455     Entry.IsInReg = false;
8456     Entry.IsSRet = true;
8457     Entry.IsNest = false;
8458     Entry.IsByVal = false;
8459     Entry.IsReturned = false;
8460     Entry.IsSwiftSelf = false;
8461     Entry.IsSwiftError = false;
8462     Entry.Alignment = Align;
8463     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
8464     CLI.NumFixedArgs += 1;
8465     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
8466 
8467     // sret demotion isn't compatible with tail-calls, since the sret argument
8468     // points into the callers stack frame.
8469     CLI.IsTailCall = false;
8470   } else {
8471     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8472       EVT VT = RetTys[I];
8473       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8474                                                      CLI.CallConv, VT);
8475       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8476                                                        CLI.CallConv, VT);
8477       for (unsigned i = 0; i != NumRegs; ++i) {
8478         ISD::InputArg MyFlags;
8479         MyFlags.VT = RegisterVT;
8480         MyFlags.ArgVT = VT;
8481         MyFlags.Used = CLI.IsReturnValueUsed;
8482         if (CLI.RetSExt)
8483           MyFlags.Flags.setSExt();
8484         if (CLI.RetZExt)
8485           MyFlags.Flags.setZExt();
8486         if (CLI.IsInReg)
8487           MyFlags.Flags.setInReg();
8488         CLI.Ins.push_back(MyFlags);
8489       }
8490     }
8491   }
8492 
8493   // We push in swifterror return as the last element of CLI.Ins.
8494   ArgListTy &Args = CLI.getArgs();
8495   if (supportSwiftError()) {
8496     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8497       if (Args[i].IsSwiftError) {
8498         ISD::InputArg MyFlags;
8499         MyFlags.VT = getPointerTy(DL);
8500         MyFlags.ArgVT = EVT(getPointerTy(DL));
8501         MyFlags.Flags.setSwiftError();
8502         CLI.Ins.push_back(MyFlags);
8503       }
8504     }
8505   }
8506 
8507   // Handle all of the outgoing arguments.
8508   CLI.Outs.clear();
8509   CLI.OutVals.clear();
8510   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
8511     SmallVector<EVT, 4> ValueVTs;
8512     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
8513     // FIXME: Split arguments if CLI.IsPostTypeLegalization
8514     Type *FinalType = Args[i].Ty;
8515     if (Args[i].IsByVal)
8516       FinalType = cast<PointerType>(Args[i].Ty)->getElementType();
8517     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
8518         FinalType, CLI.CallConv, CLI.IsVarArg);
8519     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
8520          ++Value) {
8521       EVT VT = ValueVTs[Value];
8522       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
8523       SDValue Op = SDValue(Args[i].Node.getNode(),
8524                            Args[i].Node.getResNo() + Value);
8525       ISD::ArgFlagsTy Flags;
8526 
8527       // Certain targets (such as MIPS), may have a different ABI alignment
8528       // for a type depending on the context. Give the target a chance to
8529       // specify the alignment it wants.
8530       unsigned OriginalAlignment = getABIAlignmentForCallingConv(ArgTy, DL);
8531 
8532       if (Args[i].IsZExt)
8533         Flags.setZExt();
8534       if (Args[i].IsSExt)
8535         Flags.setSExt();
8536       if (Args[i].IsInReg) {
8537         // If we are using vectorcall calling convention, a structure that is
8538         // passed InReg - is surely an HVA
8539         if (CLI.CallConv == CallingConv::X86_VectorCall &&
8540             isa<StructType>(FinalType)) {
8541           // The first value of a structure is marked
8542           if (0 == Value)
8543             Flags.setHvaStart();
8544           Flags.setHva();
8545         }
8546         // Set InReg Flag
8547         Flags.setInReg();
8548       }
8549       if (Args[i].IsSRet)
8550         Flags.setSRet();
8551       if (Args[i].IsSwiftSelf)
8552         Flags.setSwiftSelf();
8553       if (Args[i].IsSwiftError)
8554         Flags.setSwiftError();
8555       if (Args[i].IsByVal)
8556         Flags.setByVal();
8557       if (Args[i].IsInAlloca) {
8558         Flags.setInAlloca();
8559         // Set the byval flag for CCAssignFn callbacks that don't know about
8560         // inalloca.  This way we can know how many bytes we should've allocated
8561         // and how many bytes a callee cleanup function will pop.  If we port
8562         // inalloca to more targets, we'll have to add custom inalloca handling
8563         // in the various CC lowering callbacks.
8564         Flags.setByVal();
8565       }
8566       if (Args[i].IsByVal || Args[i].IsInAlloca) {
8567         PointerType *Ty = cast<PointerType>(Args[i].Ty);
8568         Type *ElementTy = Ty->getElementType();
8569         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
8570         // For ByVal, alignment should come from FE.  BE will guess if this
8571         // info is not there but there are cases it cannot get right.
8572         unsigned FrameAlign;
8573         if (Args[i].Alignment)
8574           FrameAlign = Args[i].Alignment;
8575         else
8576           FrameAlign = getByValTypeAlignment(ElementTy, DL);
8577         Flags.setByValAlign(FrameAlign);
8578       }
8579       if (Args[i].IsNest)
8580         Flags.setNest();
8581       if (NeedsRegBlock)
8582         Flags.setInConsecutiveRegs();
8583       Flags.setOrigAlign(OriginalAlignment);
8584 
8585       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8586                                                  CLI.CallConv, VT);
8587       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8588                                                         CLI.CallConv, VT);
8589       SmallVector<SDValue, 4> Parts(NumParts);
8590       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
8591 
8592       if (Args[i].IsSExt)
8593         ExtendKind = ISD::SIGN_EXTEND;
8594       else if (Args[i].IsZExt)
8595         ExtendKind = ISD::ZERO_EXTEND;
8596 
8597       // Conservatively only handle 'returned' on non-vectors that can be lowered,
8598       // for now.
8599       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
8600           CanLowerReturn) {
8601         assert(CLI.RetTy == Args[i].Ty && RetTys.size() == NumValues &&
8602                "unexpected use of 'returned'");
8603         // Before passing 'returned' to the target lowering code, ensure that
8604         // either the register MVT and the actual EVT are the same size or that
8605         // the return value and argument are extended in the same way; in these
8606         // cases it's safe to pass the argument register value unchanged as the
8607         // return register value (although it's at the target's option whether
8608         // to do so)
8609         // TODO: allow code generation to take advantage of partially preserved
8610         // registers rather than clobbering the entire register when the
8611         // parameter extension method is not compatible with the return
8612         // extension method
8613         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
8614             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
8615              CLI.RetZExt == Args[i].IsZExt))
8616           Flags.setReturned();
8617       }
8618 
8619       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT,
8620                      CLI.CS.getInstruction(), CLI.CallConv, ExtendKind);
8621 
8622       for (unsigned j = 0; j != NumParts; ++j) {
8623         // if it isn't first piece, alignment must be 1
8624         ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(), VT,
8625                                i < CLI.NumFixedArgs,
8626                                i, j*Parts[j].getValueType().getStoreSize());
8627         if (NumParts > 1 && j == 0)
8628           MyFlags.Flags.setSplit();
8629         else if (j != 0) {
8630           MyFlags.Flags.setOrigAlign(1);
8631           if (j == NumParts - 1)
8632             MyFlags.Flags.setSplitEnd();
8633         }
8634 
8635         CLI.Outs.push_back(MyFlags);
8636         CLI.OutVals.push_back(Parts[j]);
8637       }
8638 
8639       if (NeedsRegBlock && Value == NumValues - 1)
8640         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
8641     }
8642   }
8643 
8644   SmallVector<SDValue, 4> InVals;
8645   CLI.Chain = LowerCall(CLI, InVals);
8646 
8647   // Update CLI.InVals to use outside of this function.
8648   CLI.InVals = InVals;
8649 
8650   // Verify that the target's LowerCall behaved as expected.
8651   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
8652          "LowerCall didn't return a valid chain!");
8653   assert((!CLI.IsTailCall || InVals.empty()) &&
8654          "LowerCall emitted a return value for a tail call!");
8655   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
8656          "LowerCall didn't emit the correct number of values!");
8657 
8658   // For a tail call, the return value is merely live-out and there aren't
8659   // any nodes in the DAG representing it. Return a special value to
8660   // indicate that a tail call has been emitted and no more Instructions
8661   // should be processed in the current block.
8662   if (CLI.IsTailCall) {
8663     CLI.DAG.setRoot(CLI.Chain);
8664     return std::make_pair(SDValue(), SDValue());
8665   }
8666 
8667 #ifndef NDEBUG
8668   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
8669     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
8670     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
8671            "LowerCall emitted a value with the wrong type!");
8672   }
8673 #endif
8674 
8675   SmallVector<SDValue, 4> ReturnValues;
8676   if (!CanLowerReturn) {
8677     // The instruction result is the result of loading from the
8678     // hidden sret parameter.
8679     SmallVector<EVT, 1> PVTs;
8680     Type *PtrRetTy = OrigRetTy->getPointerTo(DL.getAllocaAddrSpace());
8681 
8682     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
8683     assert(PVTs.size() == 1 && "Pointers should fit in one register");
8684     EVT PtrVT = PVTs[0];
8685 
8686     unsigned NumValues = RetTys.size();
8687     ReturnValues.resize(NumValues);
8688     SmallVector<SDValue, 4> Chains(NumValues);
8689 
8690     // An aggregate return value cannot wrap around the address space, so
8691     // offsets to its parts don't wrap either.
8692     SDNodeFlags Flags;
8693     Flags.setNoUnsignedWrap(true);
8694 
8695     for (unsigned i = 0; i < NumValues; ++i) {
8696       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
8697                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
8698                                                         PtrVT), Flags);
8699       SDValue L = CLI.DAG.getLoad(
8700           RetTys[i], CLI.DL, CLI.Chain, Add,
8701           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
8702                                             DemoteStackIdx, Offsets[i]),
8703           /* Alignment = */ 1);
8704       ReturnValues[i] = L;
8705       Chains[i] = L.getValue(1);
8706     }
8707 
8708     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
8709   } else {
8710     // Collect the legal value parts into potentially illegal values
8711     // that correspond to the original function's return values.
8712     Optional<ISD::NodeType> AssertOp;
8713     if (CLI.RetSExt)
8714       AssertOp = ISD::AssertSext;
8715     else if (CLI.RetZExt)
8716       AssertOp = ISD::AssertZext;
8717     unsigned CurReg = 0;
8718     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
8719       EVT VT = RetTys[I];
8720       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
8721                                                      CLI.CallConv, VT);
8722       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
8723                                                        CLI.CallConv, VT);
8724 
8725       ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
8726                                               NumRegs, RegisterVT, VT, nullptr,
8727                                               CLI.CallConv, AssertOp));
8728       CurReg += NumRegs;
8729     }
8730 
8731     // For a function returning void, there is no return value. We can't create
8732     // such a node, so we just return a null return value in that case. In
8733     // that case, nothing will actually look at the value.
8734     if (ReturnValues.empty())
8735       return std::make_pair(SDValue(), CLI.Chain);
8736   }
8737 
8738   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
8739                                 CLI.DAG.getVTList(RetTys), ReturnValues);
8740   return std::make_pair(Res, CLI.Chain);
8741 }
8742 
8743 void TargetLowering::LowerOperationWrapper(SDNode *N,
8744                                            SmallVectorImpl<SDValue> &Results,
8745                                            SelectionDAG &DAG) const {
8746   if (SDValue Res = LowerOperation(SDValue(N, 0), DAG))
8747     Results.push_back(Res);
8748 }
8749 
8750 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8751   llvm_unreachable("LowerOperation not implemented for this target!");
8752 }
8753 
8754 void
8755 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
8756   SDValue Op = getNonRegisterValue(V);
8757   assert((Op.getOpcode() != ISD::CopyFromReg ||
8758           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
8759          "Copy from a reg to the same reg!");
8760   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
8761 
8762   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8763   // If this is an InlineAsm we have to match the registers required, not the
8764   // notional registers required by the type.
8765 
8766   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
8767                    None); // This is not an ABI copy.
8768   SDValue Chain = DAG.getEntryNode();
8769 
8770   ISD::NodeType ExtendType = (FuncInfo.PreferredExtendType.find(V) ==
8771                               FuncInfo.PreferredExtendType.end())
8772                                  ? ISD::ANY_EXTEND
8773                                  : FuncInfo.PreferredExtendType[V];
8774   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
8775   PendingExports.push_back(Chain);
8776 }
8777 
8778 #include "llvm/CodeGen/SelectionDAGISel.h"
8779 
8780 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
8781 /// entry block, return true.  This includes arguments used by switches, since
8782 /// the switch may expand into multiple basic blocks.
8783 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
8784   // With FastISel active, we may be splitting blocks, so force creation
8785   // of virtual registers for all non-dead arguments.
8786   if (FastISel)
8787     return A->use_empty();
8788 
8789   const BasicBlock &Entry = A->getParent()->front();
8790   for (const User *U : A->users())
8791     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
8792       return false;  // Use not in entry block.
8793 
8794   return true;
8795 }
8796 
8797 using ArgCopyElisionMapTy =
8798     DenseMap<const Argument *,
8799              std::pair<const AllocaInst *, const StoreInst *>>;
8800 
8801 /// Scan the entry block of the function in FuncInfo for arguments that look
8802 /// like copies into a local alloca. Record any copied arguments in
8803 /// ArgCopyElisionCandidates.
8804 static void
8805 findArgumentCopyElisionCandidates(const DataLayout &DL,
8806                                   FunctionLoweringInfo *FuncInfo,
8807                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
8808   // Record the state of every static alloca used in the entry block. Argument
8809   // allocas are all used in the entry block, so we need approximately as many
8810   // entries as we have arguments.
8811   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
8812   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
8813   unsigned NumArgs = FuncInfo->Fn->arg_size();
8814   StaticAllocas.reserve(NumArgs * 2);
8815 
8816   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
8817     if (!V)
8818       return nullptr;
8819     V = V->stripPointerCasts();
8820     const auto *AI = dyn_cast<AllocaInst>(V);
8821     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
8822       return nullptr;
8823     auto Iter = StaticAllocas.insert({AI, Unknown});
8824     return &Iter.first->second;
8825   };
8826 
8827   // Look for stores of arguments to static allocas. Look through bitcasts and
8828   // GEPs to handle type coercions, as long as the alloca is fully initialized
8829   // by the store. Any non-store use of an alloca escapes it and any subsequent
8830   // unanalyzed store might write it.
8831   // FIXME: Handle structs initialized with multiple stores.
8832   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
8833     // Look for stores, and handle non-store uses conservatively.
8834     const auto *SI = dyn_cast<StoreInst>(&I);
8835     if (!SI) {
8836       // We will look through cast uses, so ignore them completely.
8837       if (I.isCast())
8838         continue;
8839       // Ignore debug info intrinsics, they don't escape or store to allocas.
8840       if (isa<DbgInfoIntrinsic>(I))
8841         continue;
8842       // This is an unknown instruction. Assume it escapes or writes to all
8843       // static alloca operands.
8844       for (const Use &U : I.operands()) {
8845         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
8846           *Info = StaticAllocaInfo::Clobbered;
8847       }
8848       continue;
8849     }
8850 
8851     // If the stored value is a static alloca, mark it as escaped.
8852     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
8853       *Info = StaticAllocaInfo::Clobbered;
8854 
8855     // Check if the destination is a static alloca.
8856     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
8857     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
8858     if (!Info)
8859       continue;
8860     const AllocaInst *AI = cast<AllocaInst>(Dst);
8861 
8862     // Skip allocas that have been initialized or clobbered.
8863     if (*Info != StaticAllocaInfo::Unknown)
8864       continue;
8865 
8866     // Check if the stored value is an argument, and that this store fully
8867     // initializes the alloca. Don't elide copies from the same argument twice.
8868     const Value *Val = SI->getValueOperand()->stripPointerCasts();
8869     const auto *Arg = dyn_cast<Argument>(Val);
8870     if (!Arg || Arg->hasInAllocaAttr() || Arg->hasByValAttr() ||
8871         Arg->getType()->isEmptyTy() ||
8872         DL.getTypeStoreSize(Arg->getType()) !=
8873             DL.getTypeAllocSize(AI->getAllocatedType()) ||
8874         ArgCopyElisionCandidates.count(Arg)) {
8875       *Info = StaticAllocaInfo::Clobbered;
8876       continue;
8877     }
8878 
8879     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
8880                       << '\n');
8881 
8882     // Mark this alloca and store for argument copy elision.
8883     *Info = StaticAllocaInfo::Elidable;
8884     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
8885 
8886     // Stop scanning if we've seen all arguments. This will happen early in -O0
8887     // builds, which is useful, because -O0 builds have large entry blocks and
8888     // many allocas.
8889     if (ArgCopyElisionCandidates.size() == NumArgs)
8890       break;
8891   }
8892 }
8893 
8894 /// Try to elide argument copies from memory into a local alloca. Succeeds if
8895 /// ArgVal is a load from a suitable fixed stack object.
8896 static void tryToElideArgumentCopy(
8897     FunctionLoweringInfo *FuncInfo, SmallVectorImpl<SDValue> &Chains,
8898     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
8899     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
8900     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
8901     SDValue ArgVal, bool &ArgHasUses) {
8902   // Check if this is a load from a fixed stack object.
8903   auto *LNode = dyn_cast<LoadSDNode>(ArgVal);
8904   if (!LNode)
8905     return;
8906   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
8907   if (!FINode)
8908     return;
8909 
8910   // Check that the fixed stack object is the right size and alignment.
8911   // Look at the alignment that the user wrote on the alloca instead of looking
8912   // at the stack object.
8913   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
8914   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
8915   const AllocaInst *AI = ArgCopyIter->second.first;
8916   int FixedIndex = FINode->getIndex();
8917   int &AllocaIndex = FuncInfo->StaticAllocaMap[AI];
8918   int OldIndex = AllocaIndex;
8919   MachineFrameInfo &MFI = FuncInfo->MF->getFrameInfo();
8920   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
8921     LLVM_DEBUG(
8922         dbgs() << "  argument copy elision failed due to bad fixed stack "
8923                   "object size\n");
8924     return;
8925   }
8926   unsigned RequiredAlignment = AI->getAlignment();
8927   if (!RequiredAlignment) {
8928     RequiredAlignment = FuncInfo->MF->getDataLayout().getABITypeAlignment(
8929         AI->getAllocatedType());
8930   }
8931   if (MFI.getObjectAlignment(FixedIndex) < RequiredAlignment) {
8932     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
8933                          "greater than stack argument alignment ("
8934                       << RequiredAlignment << " vs "
8935                       << MFI.getObjectAlignment(FixedIndex) << ")\n");
8936     return;
8937   }
8938 
8939   // Perform the elision. Delete the old stack object and replace its only use
8940   // in the variable info map. Mark the stack object as mutable.
8941   LLVM_DEBUG({
8942     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
8943            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
8944            << '\n';
8945   });
8946   MFI.RemoveStackObject(OldIndex);
8947   MFI.setIsImmutableObjectIndex(FixedIndex, false);
8948   AllocaIndex = FixedIndex;
8949   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
8950   Chains.push_back(ArgVal.getValue(1));
8951 
8952   // Avoid emitting code for the store implementing the copy.
8953   const StoreInst *SI = ArgCopyIter->second.second;
8954   ElidedArgCopyInstrs.insert(SI);
8955 
8956   // Check for uses of the argument again so that we can avoid exporting ArgVal
8957   // if it is't used by anything other than the store.
8958   for (const Value *U : Arg.users()) {
8959     if (U != SI) {
8960       ArgHasUses = true;
8961       break;
8962     }
8963   }
8964 }
8965 
8966 void SelectionDAGISel::LowerArguments(const Function &F) {
8967   SelectionDAG &DAG = SDB->DAG;
8968   SDLoc dl = SDB->getCurSDLoc();
8969   const DataLayout &DL = DAG.getDataLayout();
8970   SmallVector<ISD::InputArg, 16> Ins;
8971 
8972   if (!FuncInfo->CanLowerReturn) {
8973     // Put in an sret pointer parameter before all the other parameters.
8974     SmallVector<EVT, 1> ValueVTs;
8975     ComputeValueVTs(*TLI, DAG.getDataLayout(),
8976                     F.getReturnType()->getPointerTo(
8977                         DAG.getDataLayout().getAllocaAddrSpace()),
8978                     ValueVTs);
8979 
8980     // NOTE: Assuming that a pointer will never break down to more than one VT
8981     // or one register.
8982     ISD::ArgFlagsTy Flags;
8983     Flags.setSRet();
8984     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
8985     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
8986                          ISD::InputArg::NoArgIndex, 0);
8987     Ins.push_back(RetArg);
8988   }
8989 
8990   // Look for stores of arguments to static allocas. Mark such arguments with a
8991   // flag to ask the target to give us the memory location of that argument if
8992   // available.
8993   ArgCopyElisionMapTy ArgCopyElisionCandidates;
8994   findArgumentCopyElisionCandidates(DL, FuncInfo, ArgCopyElisionCandidates);
8995 
8996   // Set up the incoming argument description vector.
8997   for (const Argument &Arg : F.args()) {
8998     unsigned ArgNo = Arg.getArgNo();
8999     SmallVector<EVT, 4> ValueVTs;
9000     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9001     bool isArgValueUsed = !Arg.use_empty();
9002     unsigned PartBase = 0;
9003     Type *FinalType = Arg.getType();
9004     if (Arg.hasAttribute(Attribute::ByVal))
9005       FinalType = cast<PointerType>(FinalType)->getElementType();
9006     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
9007         FinalType, F.getCallingConv(), F.isVarArg());
9008     for (unsigned Value = 0, NumValues = ValueVTs.size();
9009          Value != NumValues; ++Value) {
9010       EVT VT = ValueVTs[Value];
9011       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
9012       ISD::ArgFlagsTy Flags;
9013 
9014       // Certain targets (such as MIPS), may have a different ABI alignment
9015       // for a type depending on the context. Give the target a chance to
9016       // specify the alignment it wants.
9017       unsigned OriginalAlignment =
9018           TLI->getABIAlignmentForCallingConv(ArgTy, DL);
9019 
9020       if (Arg.hasAttribute(Attribute::ZExt))
9021         Flags.setZExt();
9022       if (Arg.hasAttribute(Attribute::SExt))
9023         Flags.setSExt();
9024       if (Arg.hasAttribute(Attribute::InReg)) {
9025         // If we are using vectorcall calling convention, a structure that is
9026         // passed InReg - is surely an HVA
9027         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
9028             isa<StructType>(Arg.getType())) {
9029           // The first value of a structure is marked
9030           if (0 == Value)
9031             Flags.setHvaStart();
9032           Flags.setHva();
9033         }
9034         // Set InReg Flag
9035         Flags.setInReg();
9036       }
9037       if (Arg.hasAttribute(Attribute::StructRet))
9038         Flags.setSRet();
9039       if (Arg.hasAttribute(Attribute::SwiftSelf))
9040         Flags.setSwiftSelf();
9041       if (Arg.hasAttribute(Attribute::SwiftError))
9042         Flags.setSwiftError();
9043       if (Arg.hasAttribute(Attribute::ByVal))
9044         Flags.setByVal();
9045       if (Arg.hasAttribute(Attribute::InAlloca)) {
9046         Flags.setInAlloca();
9047         // Set the byval flag for CCAssignFn callbacks that don't know about
9048         // inalloca.  This way we can know how many bytes we should've allocated
9049         // and how many bytes a callee cleanup function will pop.  If we port
9050         // inalloca to more targets, we'll have to add custom inalloca handling
9051         // in the various CC lowering callbacks.
9052         Flags.setByVal();
9053       }
9054       if (F.getCallingConv() == CallingConv::X86_INTR) {
9055         // IA Interrupt passes frame (1st parameter) by value in the stack.
9056         if (ArgNo == 0)
9057           Flags.setByVal();
9058       }
9059       if (Flags.isByVal() || Flags.isInAlloca()) {
9060         PointerType *Ty = cast<PointerType>(Arg.getType());
9061         Type *ElementTy = Ty->getElementType();
9062         Flags.setByValSize(DL.getTypeAllocSize(ElementTy));
9063         // For ByVal, alignment should be passed from FE.  BE will guess if
9064         // this info is not there but there are cases it cannot get right.
9065         unsigned FrameAlign;
9066         if (Arg.getParamAlignment())
9067           FrameAlign = Arg.getParamAlignment();
9068         else
9069           FrameAlign = TLI->getByValTypeAlignment(ElementTy, DL);
9070         Flags.setByValAlign(FrameAlign);
9071       }
9072       if (Arg.hasAttribute(Attribute::Nest))
9073         Flags.setNest();
9074       if (NeedsRegBlock)
9075         Flags.setInConsecutiveRegs();
9076       Flags.setOrigAlign(OriginalAlignment);
9077       if (ArgCopyElisionCandidates.count(&Arg))
9078         Flags.setCopyElisionCandidate();
9079 
9080       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
9081           *CurDAG->getContext(), F.getCallingConv(), VT);
9082       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
9083           *CurDAG->getContext(), F.getCallingConv(), VT);
9084       for (unsigned i = 0; i != NumRegs; ++i) {
9085         ISD::InputArg MyFlags(Flags, RegisterVT, VT, isArgValueUsed,
9086                               ArgNo, PartBase+i*RegisterVT.getStoreSize());
9087         if (NumRegs > 1 && i == 0)
9088           MyFlags.Flags.setSplit();
9089         // if it isn't first piece, alignment must be 1
9090         else if (i > 0) {
9091           MyFlags.Flags.setOrigAlign(1);
9092           if (i == NumRegs - 1)
9093             MyFlags.Flags.setSplitEnd();
9094         }
9095         Ins.push_back(MyFlags);
9096       }
9097       if (NeedsRegBlock && Value == NumValues - 1)
9098         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
9099       PartBase += VT.getStoreSize();
9100     }
9101   }
9102 
9103   // Call the target to set up the argument values.
9104   SmallVector<SDValue, 8> InVals;
9105   SDValue NewRoot = TLI->LowerFormalArguments(
9106       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
9107 
9108   // Verify that the target's LowerFormalArguments behaved as expected.
9109   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
9110          "LowerFormalArguments didn't return a valid chain!");
9111   assert(InVals.size() == Ins.size() &&
9112          "LowerFormalArguments didn't emit the correct number of values!");
9113   LLVM_DEBUG({
9114     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
9115       assert(InVals[i].getNode() &&
9116              "LowerFormalArguments emitted a null value!");
9117       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
9118              "LowerFormalArguments emitted a value with the wrong type!");
9119     }
9120   });
9121 
9122   // Update the DAG with the new chain value resulting from argument lowering.
9123   DAG.setRoot(NewRoot);
9124 
9125   // Set up the argument values.
9126   unsigned i = 0;
9127   if (!FuncInfo->CanLowerReturn) {
9128     // Create a virtual register for the sret pointer, and put in a copy
9129     // from the sret argument into it.
9130     SmallVector<EVT, 1> ValueVTs;
9131     ComputeValueVTs(*TLI, DAG.getDataLayout(),
9132                     F.getReturnType()->getPointerTo(
9133                         DAG.getDataLayout().getAllocaAddrSpace()),
9134                     ValueVTs);
9135     MVT VT = ValueVTs[0].getSimpleVT();
9136     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
9137     Optional<ISD::NodeType> AssertOp = None;
9138     SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT,
9139                                         nullptr, F.getCallingConv(), AssertOp);
9140 
9141     MachineFunction& MF = SDB->DAG.getMachineFunction();
9142     MachineRegisterInfo& RegInfo = MF.getRegInfo();
9143     unsigned SRetReg = RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
9144     FuncInfo->DemoteRegister = SRetReg;
9145     NewRoot =
9146         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
9147     DAG.setRoot(NewRoot);
9148 
9149     // i indexes lowered arguments.  Bump it past the hidden sret argument.
9150     ++i;
9151   }
9152 
9153   SmallVector<SDValue, 4> Chains;
9154   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
9155   for (const Argument &Arg : F.args()) {
9156     SmallVector<SDValue, 4> ArgValues;
9157     SmallVector<EVT, 4> ValueVTs;
9158     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
9159     unsigned NumValues = ValueVTs.size();
9160     if (NumValues == 0)
9161       continue;
9162 
9163     bool ArgHasUses = !Arg.use_empty();
9164 
9165     // Elide the copying store if the target loaded this argument from a
9166     // suitable fixed stack object.
9167     if (Ins[i].Flags.isCopyElisionCandidate()) {
9168       tryToElideArgumentCopy(FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
9169                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
9170                              InVals[i], ArgHasUses);
9171     }
9172 
9173     // If this argument is unused then remember its value. It is used to generate
9174     // debugging information.
9175     bool isSwiftErrorArg =
9176         TLI->supportSwiftError() &&
9177         Arg.hasAttribute(Attribute::SwiftError);
9178     if (!ArgHasUses && !isSwiftErrorArg) {
9179       SDB->setUnusedArgValue(&Arg, InVals[i]);
9180 
9181       // Also remember any frame index for use in FastISel.
9182       if (FrameIndexSDNode *FI =
9183           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
9184         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9185     }
9186 
9187     for (unsigned Val = 0; Val != NumValues; ++Val) {
9188       EVT VT = ValueVTs[Val];
9189       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
9190                                                       F.getCallingConv(), VT);
9191       unsigned NumParts = TLI->getNumRegistersForCallingConv(
9192           *CurDAG->getContext(), F.getCallingConv(), VT);
9193 
9194       // Even an apparant 'unused' swifterror argument needs to be returned. So
9195       // we do generate a copy for it that can be used on return from the
9196       // function.
9197       if (ArgHasUses || isSwiftErrorArg) {
9198         Optional<ISD::NodeType> AssertOp;
9199         if (Arg.hasAttribute(Attribute::SExt))
9200           AssertOp = ISD::AssertSext;
9201         else if (Arg.hasAttribute(Attribute::ZExt))
9202           AssertOp = ISD::AssertZext;
9203 
9204         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
9205                                              PartVT, VT, nullptr,
9206                                              F.getCallingConv(), AssertOp));
9207       }
9208 
9209       i += NumParts;
9210     }
9211 
9212     // We don't need to do anything else for unused arguments.
9213     if (ArgValues.empty())
9214       continue;
9215 
9216     // Note down frame index.
9217     if (FrameIndexSDNode *FI =
9218         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
9219       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9220 
9221     SDValue Res = DAG.getMergeValues(makeArrayRef(ArgValues.data(), NumValues),
9222                                      SDB->getCurSDLoc());
9223 
9224     SDB->setValue(&Arg, Res);
9225     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
9226       // We want to associate the argument with the frame index, among
9227       // involved operands, that correspond to the lowest address. The
9228       // getCopyFromParts function, called earlier, is swapping the order of
9229       // the operands to BUILD_PAIR depending on endianness. The result of
9230       // that swapping is that the least significant bits of the argument will
9231       // be in the first operand of the BUILD_PAIR node, and the most
9232       // significant bits will be in the second operand.
9233       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
9234       if (LoadSDNode *LNode =
9235           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
9236         if (FrameIndexSDNode *FI =
9237             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
9238           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
9239     }
9240 
9241     // Update the SwiftErrorVRegDefMap.
9242     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
9243       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9244       if (TargetRegisterInfo::isVirtualRegister(Reg))
9245         FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB,
9246                                            FuncInfo->SwiftErrorArg, Reg);
9247     }
9248 
9249     // If this argument is live outside of the entry block, insert a copy from
9250     // wherever we got it to the vreg that other BB's will reference it as.
9251     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
9252       // If we can, though, try to skip creating an unnecessary vreg.
9253       // FIXME: This isn't very clean... it would be nice to make this more
9254       // general.  It's also subtly incompatible with the hacks FastISel
9255       // uses with vregs.
9256       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
9257       if (TargetRegisterInfo::isVirtualRegister(Reg)) {
9258         FuncInfo->ValueMap[&Arg] = Reg;
9259         continue;
9260       }
9261     }
9262     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
9263       FuncInfo->InitializeRegForValue(&Arg);
9264       SDB->CopyToExportRegsIfNeeded(&Arg);
9265     }
9266   }
9267 
9268   if (!Chains.empty()) {
9269     Chains.push_back(NewRoot);
9270     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
9271   }
9272 
9273   DAG.setRoot(NewRoot);
9274 
9275   assert(i == InVals.size() && "Argument register count mismatch!");
9276 
9277   // If any argument copy elisions occurred and we have debug info, update the
9278   // stale frame indices used in the dbg.declare variable info table.
9279   MachineFunction::VariableDbgInfoMapTy &DbgDeclareInfo = MF->getVariableDbgInfo();
9280   if (!DbgDeclareInfo.empty() && !ArgCopyElisionFrameIndexMap.empty()) {
9281     for (MachineFunction::VariableDbgInfo &VI : DbgDeclareInfo) {
9282       auto I = ArgCopyElisionFrameIndexMap.find(VI.Slot);
9283       if (I != ArgCopyElisionFrameIndexMap.end())
9284         VI.Slot = I->second;
9285     }
9286   }
9287 
9288   // Finally, if the target has anything special to do, allow it to do so.
9289   EmitFunctionEntryCode();
9290 }
9291 
9292 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
9293 /// ensure constants are generated when needed.  Remember the virtual registers
9294 /// that need to be added to the Machine PHI nodes as input.  We cannot just
9295 /// directly add them, because expansion might result in multiple MBB's for one
9296 /// BB.  As such, the start of the BB might correspond to a different MBB than
9297 /// the end.
9298 void
9299 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
9300   const Instruction *TI = LLVMBB->getTerminator();
9301 
9302   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
9303 
9304   // Check PHI nodes in successors that expect a value to be available from this
9305   // block.
9306   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
9307     const BasicBlock *SuccBB = TI->getSuccessor(succ);
9308     if (!isa<PHINode>(SuccBB->begin())) continue;
9309     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
9310 
9311     // If this terminator has multiple identical successors (common for
9312     // switches), only handle each succ once.
9313     if (!SuccsHandled.insert(SuccMBB).second)
9314       continue;
9315 
9316     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
9317 
9318     // At this point we know that there is a 1-1 correspondence between LLVM PHI
9319     // nodes and Machine PHI nodes, but the incoming operands have not been
9320     // emitted yet.
9321     for (const PHINode &PN : SuccBB->phis()) {
9322       // Ignore dead phi's.
9323       if (PN.use_empty())
9324         continue;
9325 
9326       // Skip empty types
9327       if (PN.getType()->isEmptyTy())
9328         continue;
9329 
9330       unsigned Reg;
9331       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
9332 
9333       if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
9334         unsigned &RegOut = ConstantsOut[C];
9335         if (RegOut == 0) {
9336           RegOut = FuncInfo.CreateRegs(C->getType());
9337           CopyValueToVirtualRegister(C, RegOut);
9338         }
9339         Reg = RegOut;
9340       } else {
9341         DenseMap<const Value *, unsigned>::iterator I =
9342           FuncInfo.ValueMap.find(PHIOp);
9343         if (I != FuncInfo.ValueMap.end())
9344           Reg = I->second;
9345         else {
9346           assert(isa<AllocaInst>(PHIOp) &&
9347                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
9348                  "Didn't codegen value into a register!??");
9349           Reg = FuncInfo.CreateRegs(PHIOp->getType());
9350           CopyValueToVirtualRegister(PHIOp, Reg);
9351         }
9352       }
9353 
9354       // Remember that this register needs to added to the machine PHI node as
9355       // the input for this MBB.
9356       SmallVector<EVT, 4> ValueVTs;
9357       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9358       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
9359       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
9360         EVT VT = ValueVTs[vti];
9361         unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
9362         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
9363           FuncInfo.PHINodesToUpdate.push_back(
9364               std::make_pair(&*MBBI++, Reg + i));
9365         Reg += NumRegisters;
9366       }
9367     }
9368   }
9369 
9370   ConstantsOut.clear();
9371 }
9372 
9373 /// Add a successor MBB to ParentMBB< creating a new MachineBB for BB if SuccMBB
9374 /// is 0.
9375 MachineBasicBlock *
9376 SelectionDAGBuilder::StackProtectorDescriptor::
9377 AddSuccessorMBB(const BasicBlock *BB,
9378                 MachineBasicBlock *ParentMBB,
9379                 bool IsLikely,
9380                 MachineBasicBlock *SuccMBB) {
9381   // If SuccBB has not been created yet, create it.
9382   if (!SuccMBB) {
9383     MachineFunction *MF = ParentMBB->getParent();
9384     MachineFunction::iterator BBI(ParentMBB);
9385     SuccMBB = MF->CreateMachineBasicBlock(BB);
9386     MF->insert(++BBI, SuccMBB);
9387   }
9388   // Add it as a successor of ParentMBB.
9389   ParentMBB->addSuccessor(
9390       SuccMBB, BranchProbabilityInfo::getBranchProbStackProtector(IsLikely));
9391   return SuccMBB;
9392 }
9393 
9394 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
9395   MachineFunction::iterator I(MBB);
9396   if (++I == FuncInfo.MF->end())
9397     return nullptr;
9398   return &*I;
9399 }
9400 
9401 /// During lowering new call nodes can be created (such as memset, etc.).
9402 /// Those will become new roots of the current DAG, but complications arise
9403 /// when they are tail calls. In such cases, the call lowering will update
9404 /// the root, but the builder still needs to know that a tail call has been
9405 /// lowered in order to avoid generating an additional return.
9406 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
9407   // If the node is null, we do have a tail call.
9408   if (MaybeTC.getNode() != nullptr)
9409     DAG.setRoot(MaybeTC);
9410   else
9411     HasTailCall = true;
9412 }
9413 
9414 uint64_t
9415 SelectionDAGBuilder::getJumpTableRange(const CaseClusterVector &Clusters,
9416                                        unsigned First, unsigned Last) const {
9417   assert(Last >= First);
9418   const APInt &LowCase = Clusters[First].Low->getValue();
9419   const APInt &HighCase = Clusters[Last].High->getValue();
9420   assert(LowCase.getBitWidth() == HighCase.getBitWidth());
9421 
9422   // FIXME: A range of consecutive cases has 100% density, but only requires one
9423   // comparison to lower. We should discriminate against such consecutive ranges
9424   // in jump tables.
9425 
9426   return (HighCase - LowCase).getLimitedValue((UINT64_MAX - 1) / 100) + 1;
9427 }
9428 
9429 uint64_t SelectionDAGBuilder::getJumpTableNumCases(
9430     const SmallVectorImpl<unsigned> &TotalCases, unsigned First,
9431     unsigned Last) const {
9432   assert(Last >= First);
9433   assert(TotalCases[Last] >= TotalCases[First]);
9434   uint64_t NumCases =
9435       TotalCases[Last] - (First == 0 ? 0 : TotalCases[First - 1]);
9436   return NumCases;
9437 }
9438 
9439 bool SelectionDAGBuilder::buildJumpTable(const CaseClusterVector &Clusters,
9440                                          unsigned First, unsigned Last,
9441                                          const SwitchInst *SI,
9442                                          MachineBasicBlock *DefaultMBB,
9443                                          CaseCluster &JTCluster) {
9444   assert(First <= Last);
9445 
9446   auto Prob = BranchProbability::getZero();
9447   unsigned NumCmps = 0;
9448   std::vector<MachineBasicBlock*> Table;
9449   DenseMap<MachineBasicBlock*, BranchProbability> JTProbs;
9450 
9451   // Initialize probabilities in JTProbs.
9452   for (unsigned I = First; I <= Last; ++I)
9453     JTProbs[Clusters[I].MBB] = BranchProbability::getZero();
9454 
9455   for (unsigned I = First; I <= Last; ++I) {
9456     assert(Clusters[I].Kind == CC_Range);
9457     Prob += Clusters[I].Prob;
9458     const APInt &Low = Clusters[I].Low->getValue();
9459     const APInt &High = Clusters[I].High->getValue();
9460     NumCmps += (Low == High) ? 1 : 2;
9461     if (I != First) {
9462       // Fill the gap between this and the previous cluster.
9463       const APInt &PreviousHigh = Clusters[I - 1].High->getValue();
9464       assert(PreviousHigh.slt(Low));
9465       uint64_t Gap = (Low - PreviousHigh).getLimitedValue() - 1;
9466       for (uint64_t J = 0; J < Gap; J++)
9467         Table.push_back(DefaultMBB);
9468     }
9469     uint64_t ClusterSize = (High - Low).getLimitedValue() + 1;
9470     for (uint64_t J = 0; J < ClusterSize; ++J)
9471       Table.push_back(Clusters[I].MBB);
9472     JTProbs[Clusters[I].MBB] += Clusters[I].Prob;
9473   }
9474 
9475   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9476   unsigned NumDests = JTProbs.size();
9477   if (TLI.isSuitableForBitTests(
9478           NumDests, NumCmps, Clusters[First].Low->getValue(),
9479           Clusters[Last].High->getValue(), DAG.getDataLayout())) {
9480     // Clusters[First..Last] should be lowered as bit tests instead.
9481     return false;
9482   }
9483 
9484   // Create the MBB that will load from and jump through the table.
9485   // Note: We create it here, but it's not inserted into the function yet.
9486   MachineFunction *CurMF = FuncInfo.MF;
9487   MachineBasicBlock *JumpTableMBB =
9488       CurMF->CreateMachineBasicBlock(SI->getParent());
9489 
9490   // Add successors. Note: use table order for determinism.
9491   SmallPtrSet<MachineBasicBlock *, 8> Done;
9492   for (MachineBasicBlock *Succ : Table) {
9493     if (Done.count(Succ))
9494       continue;
9495     addSuccessorWithProb(JumpTableMBB, Succ, JTProbs[Succ]);
9496     Done.insert(Succ);
9497   }
9498   JumpTableMBB->normalizeSuccProbs();
9499 
9500   unsigned JTI = CurMF->getOrCreateJumpTableInfo(TLI.getJumpTableEncoding())
9501                      ->createJumpTableIndex(Table);
9502 
9503   // Set up the jump table info.
9504   JumpTable JT(-1U, JTI, JumpTableMBB, nullptr);
9505   JumpTableHeader JTH(Clusters[First].Low->getValue(),
9506                       Clusters[Last].High->getValue(), SI->getCondition(),
9507                       nullptr, false);
9508   JTCases.emplace_back(std::move(JTH), std::move(JT));
9509 
9510   JTCluster = CaseCluster::jumpTable(Clusters[First].Low, Clusters[Last].High,
9511                                      JTCases.size() - 1, Prob);
9512   return true;
9513 }
9514 
9515 void SelectionDAGBuilder::findJumpTables(CaseClusterVector &Clusters,
9516                                          const SwitchInst *SI,
9517                                          MachineBasicBlock *DefaultMBB) {
9518 #ifndef NDEBUG
9519   // Clusters must be non-empty, sorted, and only contain Range clusters.
9520   assert(!Clusters.empty());
9521   for (CaseCluster &C : Clusters)
9522     assert(C.Kind == CC_Range);
9523   for (unsigned i = 1, e = Clusters.size(); i < e; ++i)
9524     assert(Clusters[i - 1].High->getValue().slt(Clusters[i].Low->getValue()));
9525 #endif
9526 
9527   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9528   if (!TLI.areJTsAllowed(SI->getParent()->getParent()))
9529     return;
9530 
9531   const int64_t N = Clusters.size();
9532   const unsigned MinJumpTableEntries = TLI.getMinimumJumpTableEntries();
9533   const unsigned SmallNumberOfEntries = MinJumpTableEntries / 2;
9534 
9535   if (N < 2 || N < MinJumpTableEntries)
9536     return;
9537 
9538   // TotalCases[i]: Total nbr of cases in Clusters[0..i].
9539   SmallVector<unsigned, 8> TotalCases(N);
9540   for (unsigned i = 0; i < N; ++i) {
9541     const APInt &Hi = Clusters[i].High->getValue();
9542     const APInt &Lo = Clusters[i].Low->getValue();
9543     TotalCases[i] = (Hi - Lo).getLimitedValue() + 1;
9544     if (i != 0)
9545       TotalCases[i] += TotalCases[i - 1];
9546   }
9547 
9548   // Cheap case: the whole range may be suitable for jump table.
9549   uint64_t Range = getJumpTableRange(Clusters,0, N - 1);
9550   uint64_t NumCases = getJumpTableNumCases(TotalCases, 0, N - 1);
9551   assert(NumCases < UINT64_MAX / 100);
9552   assert(Range >= NumCases);
9553   if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9554     CaseCluster JTCluster;
9555     if (buildJumpTable(Clusters, 0, N - 1, SI, DefaultMBB, JTCluster)) {
9556       Clusters[0] = JTCluster;
9557       Clusters.resize(1);
9558       return;
9559     }
9560   }
9561 
9562   // The algorithm below is not suitable for -O0.
9563   if (TM.getOptLevel() == CodeGenOpt::None)
9564     return;
9565 
9566   // Split Clusters into minimum number of dense partitions. The algorithm uses
9567   // the same idea as Kannan & Proebsting "Correction to 'Producing Good Code
9568   // for the Case Statement'" (1994), but builds the MinPartitions array in
9569   // reverse order to make it easier to reconstruct the partitions in ascending
9570   // order. In the choice between two optimal partitionings, it picks the one
9571   // which yields more jump tables.
9572 
9573   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9574   SmallVector<unsigned, 8> MinPartitions(N);
9575   // LastElement[i] is the last element of the partition starting at i.
9576   SmallVector<unsigned, 8> LastElement(N);
9577   // PartitionsScore[i] is used to break ties when choosing between two
9578   // partitionings resulting in the same number of partitions.
9579   SmallVector<unsigned, 8> PartitionsScore(N);
9580   // For PartitionsScore, a small number of comparisons is considered as good as
9581   // a jump table and a single comparison is considered better than a jump
9582   // table.
9583   enum PartitionScores : unsigned {
9584     NoTable = 0,
9585     Table = 1,
9586     FewCases = 1,
9587     SingleCase = 2
9588   };
9589 
9590   // Base case: There is only one way to partition Clusters[N-1].
9591   MinPartitions[N - 1] = 1;
9592   LastElement[N - 1] = N - 1;
9593   PartitionsScore[N - 1] = PartitionScores::SingleCase;
9594 
9595   // Note: loop indexes are signed to avoid underflow.
9596   for (int64_t i = N - 2; i >= 0; i--) {
9597     // Find optimal partitioning of Clusters[i..N-1].
9598     // Baseline: Put Clusters[i] into a partition on its own.
9599     MinPartitions[i] = MinPartitions[i + 1] + 1;
9600     LastElement[i] = i;
9601     PartitionsScore[i] = PartitionsScore[i + 1] + PartitionScores::SingleCase;
9602 
9603     // Search for a solution that results in fewer partitions.
9604     for (int64_t j = N - 1; j > i; j--) {
9605       // Try building a partition from Clusters[i..j].
9606       uint64_t Range = getJumpTableRange(Clusters, i, j);
9607       uint64_t NumCases = getJumpTableNumCases(TotalCases, i, j);
9608       assert(NumCases < UINT64_MAX / 100);
9609       assert(Range >= NumCases);
9610       if (TLI.isSuitableForJumpTable(SI, NumCases, Range)) {
9611         unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9612         unsigned Score = j == N - 1 ? 0 : PartitionsScore[j + 1];
9613         int64_t NumEntries = j - i + 1;
9614 
9615         if (NumEntries == 1)
9616           Score += PartitionScores::SingleCase;
9617         else if (NumEntries <= SmallNumberOfEntries)
9618           Score += PartitionScores::FewCases;
9619         else if (NumEntries >= MinJumpTableEntries)
9620           Score += PartitionScores::Table;
9621 
9622         // If this leads to fewer partitions, or to the same number of
9623         // partitions with better score, it is a better partitioning.
9624         if (NumPartitions < MinPartitions[i] ||
9625             (NumPartitions == MinPartitions[i] && Score > PartitionsScore[i])) {
9626           MinPartitions[i] = NumPartitions;
9627           LastElement[i] = j;
9628           PartitionsScore[i] = Score;
9629         }
9630       }
9631     }
9632   }
9633 
9634   // Iterate over the partitions, replacing some with jump tables in-place.
9635   unsigned DstIndex = 0;
9636   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9637     Last = LastElement[First];
9638     assert(Last >= First);
9639     assert(DstIndex <= First);
9640     unsigned NumClusters = Last - First + 1;
9641 
9642     CaseCluster JTCluster;
9643     if (NumClusters >= MinJumpTableEntries &&
9644         buildJumpTable(Clusters, First, Last, SI, DefaultMBB, JTCluster)) {
9645       Clusters[DstIndex++] = JTCluster;
9646     } else {
9647       for (unsigned I = First; I <= Last; ++I)
9648         std::memmove(&Clusters[DstIndex++], &Clusters[I], sizeof(Clusters[I]));
9649     }
9650   }
9651   Clusters.resize(DstIndex);
9652 }
9653 
9654 bool SelectionDAGBuilder::buildBitTests(CaseClusterVector &Clusters,
9655                                         unsigned First, unsigned Last,
9656                                         const SwitchInst *SI,
9657                                         CaseCluster &BTCluster) {
9658   assert(First <= Last);
9659   if (First == Last)
9660     return false;
9661 
9662   BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9663   unsigned NumCmps = 0;
9664   for (int64_t I = First; I <= Last; ++I) {
9665     assert(Clusters[I].Kind == CC_Range);
9666     Dests.set(Clusters[I].MBB->getNumber());
9667     NumCmps += (Clusters[I].Low == Clusters[I].High) ? 1 : 2;
9668   }
9669   unsigned NumDests = Dests.count();
9670 
9671   APInt Low = Clusters[First].Low->getValue();
9672   APInt High = Clusters[Last].High->getValue();
9673   assert(Low.slt(High));
9674 
9675   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9676   const DataLayout &DL = DAG.getDataLayout();
9677   if (!TLI.isSuitableForBitTests(NumDests, NumCmps, Low, High, DL))
9678     return false;
9679 
9680   APInt LowBound;
9681   APInt CmpRange;
9682 
9683   const int BitWidth = TLI.getPointerTy(DL).getSizeInBits();
9684   assert(TLI.rangeFitsInWord(Low, High, DL) &&
9685          "Case range must fit in bit mask!");
9686 
9687   // Check if the clusters cover a contiguous range such that no value in the
9688   // range will jump to the default statement.
9689   bool ContiguousRange = true;
9690   for (int64_t I = First + 1; I <= Last; ++I) {
9691     if (Clusters[I].Low->getValue() != Clusters[I - 1].High->getValue() + 1) {
9692       ContiguousRange = false;
9693       break;
9694     }
9695   }
9696 
9697   if (Low.isStrictlyPositive() && High.slt(BitWidth)) {
9698     // Optimize the case where all the case values fit in a word without having
9699     // to subtract minValue. In this case, we can optimize away the subtraction.
9700     LowBound = APInt::getNullValue(Low.getBitWidth());
9701     CmpRange = High;
9702     ContiguousRange = false;
9703   } else {
9704     LowBound = Low;
9705     CmpRange = High - Low;
9706   }
9707 
9708   CaseBitsVector CBV;
9709   auto TotalProb = BranchProbability::getZero();
9710   for (unsigned i = First; i <= Last; ++i) {
9711     // Find the CaseBits for this destination.
9712     unsigned j;
9713     for (j = 0; j < CBV.size(); ++j)
9714       if (CBV[j].BB == Clusters[i].MBB)
9715         break;
9716     if (j == CBV.size())
9717       CBV.push_back(
9718           CaseBits(0, Clusters[i].MBB, 0, BranchProbability::getZero()));
9719     CaseBits *CB = &CBV[j];
9720 
9721     // Update Mask, Bits and ExtraProb.
9722     uint64_t Lo = (Clusters[i].Low->getValue() - LowBound).getZExtValue();
9723     uint64_t Hi = (Clusters[i].High->getValue() - LowBound).getZExtValue();
9724     assert(Hi >= Lo && Hi < 64 && "Invalid bit case!");
9725     CB->Mask |= (-1ULL >> (63 - (Hi - Lo))) << Lo;
9726     CB->Bits += Hi - Lo + 1;
9727     CB->ExtraProb += Clusters[i].Prob;
9728     TotalProb += Clusters[i].Prob;
9729   }
9730 
9731   BitTestInfo BTI;
9732   llvm::sort(CBV, [](const CaseBits &a, const CaseBits &b) {
9733     // Sort by probability first, number of bits second, bit mask third.
9734     if (a.ExtraProb != b.ExtraProb)
9735       return a.ExtraProb > b.ExtraProb;
9736     if (a.Bits != b.Bits)
9737       return a.Bits > b.Bits;
9738     return a.Mask < b.Mask;
9739   });
9740 
9741   for (auto &CB : CBV) {
9742     MachineBasicBlock *BitTestBB =
9743         FuncInfo.MF->CreateMachineBasicBlock(SI->getParent());
9744     BTI.push_back(BitTestCase(CB.Mask, BitTestBB, CB.BB, CB.ExtraProb));
9745   }
9746   BitTestCases.emplace_back(std::move(LowBound), std::move(CmpRange),
9747                             SI->getCondition(), -1U, MVT::Other, false,
9748                             ContiguousRange, nullptr, nullptr, std::move(BTI),
9749                             TotalProb);
9750 
9751   BTCluster = CaseCluster::bitTests(Clusters[First].Low, Clusters[Last].High,
9752                                     BitTestCases.size() - 1, TotalProb);
9753   return true;
9754 }
9755 
9756 void SelectionDAGBuilder::findBitTestClusters(CaseClusterVector &Clusters,
9757                                               const SwitchInst *SI) {
9758 // Partition Clusters into as few subsets as possible, where each subset has a
9759 // range that fits in a machine word and has <= 3 unique destinations.
9760 
9761 #ifndef NDEBUG
9762   // Clusters must be sorted and contain Range or JumpTable clusters.
9763   assert(!Clusters.empty());
9764   assert(Clusters[0].Kind == CC_Range || Clusters[0].Kind == CC_JumpTable);
9765   for (const CaseCluster &C : Clusters)
9766     assert(C.Kind == CC_Range || C.Kind == CC_JumpTable);
9767   for (unsigned i = 1; i < Clusters.size(); ++i)
9768     assert(Clusters[i-1].High->getValue().slt(Clusters[i].Low->getValue()));
9769 #endif
9770 
9771   // The algorithm below is not suitable for -O0.
9772   if (TM.getOptLevel() == CodeGenOpt::None)
9773     return;
9774 
9775   // If target does not have legal shift left, do not emit bit tests at all.
9776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9777   const DataLayout &DL = DAG.getDataLayout();
9778 
9779   EVT PTy = TLI.getPointerTy(DL);
9780   if (!TLI.isOperationLegal(ISD::SHL, PTy))
9781     return;
9782 
9783   int BitWidth = PTy.getSizeInBits();
9784   const int64_t N = Clusters.size();
9785 
9786   // MinPartitions[i] is the minimum nbr of partitions of Clusters[i..N-1].
9787   SmallVector<unsigned, 8> MinPartitions(N);
9788   // LastElement[i] is the last element of the partition starting at i.
9789   SmallVector<unsigned, 8> LastElement(N);
9790 
9791   // FIXME: This might not be the best algorithm for finding bit test clusters.
9792 
9793   // Base case: There is only one way to partition Clusters[N-1].
9794   MinPartitions[N - 1] = 1;
9795   LastElement[N - 1] = N - 1;
9796 
9797   // Note: loop indexes are signed to avoid underflow.
9798   for (int64_t i = N - 2; i >= 0; --i) {
9799     // Find optimal partitioning of Clusters[i..N-1].
9800     // Baseline: Put Clusters[i] into a partition on its own.
9801     MinPartitions[i] = MinPartitions[i + 1] + 1;
9802     LastElement[i] = i;
9803 
9804     // Search for a solution that results in fewer partitions.
9805     // Note: the search is limited by BitWidth, reducing time complexity.
9806     for (int64_t j = std::min(N - 1, i + BitWidth - 1); j > i; --j) {
9807       // Try building a partition from Clusters[i..j].
9808 
9809       // Check the range.
9810       if (!TLI.rangeFitsInWord(Clusters[i].Low->getValue(),
9811                                Clusters[j].High->getValue(), DL))
9812         continue;
9813 
9814       // Check nbr of destinations and cluster types.
9815       // FIXME: This works, but doesn't seem very efficient.
9816       bool RangesOnly = true;
9817       BitVector Dests(FuncInfo.MF->getNumBlockIDs());
9818       for (int64_t k = i; k <= j; k++) {
9819         if (Clusters[k].Kind != CC_Range) {
9820           RangesOnly = false;
9821           break;
9822         }
9823         Dests.set(Clusters[k].MBB->getNumber());
9824       }
9825       if (!RangesOnly || Dests.count() > 3)
9826         break;
9827 
9828       // Check if it's a better partition.
9829       unsigned NumPartitions = 1 + (j == N - 1 ? 0 : MinPartitions[j + 1]);
9830       if (NumPartitions < MinPartitions[i]) {
9831         // Found a better partition.
9832         MinPartitions[i] = NumPartitions;
9833         LastElement[i] = j;
9834       }
9835     }
9836   }
9837 
9838   // Iterate over the partitions, replacing with bit-test clusters in-place.
9839   unsigned DstIndex = 0;
9840   for (unsigned First = 0, Last; First < N; First = Last + 1) {
9841     Last = LastElement[First];
9842     assert(First <= Last);
9843     assert(DstIndex <= First);
9844 
9845     CaseCluster BitTestCluster;
9846     if (buildBitTests(Clusters, First, Last, SI, BitTestCluster)) {
9847       Clusters[DstIndex++] = BitTestCluster;
9848     } else {
9849       size_t NumClusters = Last - First + 1;
9850       std::memmove(&Clusters[DstIndex], &Clusters[First],
9851                    sizeof(Clusters[0]) * NumClusters);
9852       DstIndex += NumClusters;
9853     }
9854   }
9855   Clusters.resize(DstIndex);
9856 }
9857 
9858 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
9859                                         MachineBasicBlock *SwitchMBB,
9860                                         MachineBasicBlock *DefaultMBB) {
9861   MachineFunction *CurMF = FuncInfo.MF;
9862   MachineBasicBlock *NextMBB = nullptr;
9863   MachineFunction::iterator BBI(W.MBB);
9864   if (++BBI != FuncInfo.MF->end())
9865     NextMBB = &*BBI;
9866 
9867   unsigned Size = W.LastCluster - W.FirstCluster + 1;
9868 
9869   BranchProbabilityInfo *BPI = FuncInfo.BPI;
9870 
9871   if (Size == 2 && W.MBB == SwitchMBB) {
9872     // If any two of the cases has the same destination, and if one value
9873     // is the same as the other, but has one bit unset that the other has set,
9874     // use bit manipulation to do two compares at once.  For example:
9875     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
9876     // TODO: This could be extended to merge any 2 cases in switches with 3
9877     // cases.
9878     // TODO: Handle cases where W.CaseBB != SwitchBB.
9879     CaseCluster &Small = *W.FirstCluster;
9880     CaseCluster &Big = *W.LastCluster;
9881 
9882     if (Small.Low == Small.High && Big.Low == Big.High &&
9883         Small.MBB == Big.MBB) {
9884       const APInt &SmallValue = Small.Low->getValue();
9885       const APInt &BigValue = Big.Low->getValue();
9886 
9887       // Check that there is only one bit different.
9888       APInt CommonBit = BigValue ^ SmallValue;
9889       if (CommonBit.isPowerOf2()) {
9890         SDValue CondLHS = getValue(Cond);
9891         EVT VT = CondLHS.getValueType();
9892         SDLoc DL = getCurSDLoc();
9893 
9894         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
9895                                  DAG.getConstant(CommonBit, DL, VT));
9896         SDValue Cond = DAG.getSetCC(
9897             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
9898             ISD::SETEQ);
9899 
9900         // Update successor info.
9901         // Both Small and Big will jump to Small.BB, so we sum up the
9902         // probabilities.
9903         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
9904         if (BPI)
9905           addSuccessorWithProb(
9906               SwitchMBB, DefaultMBB,
9907               // The default destination is the first successor in IR.
9908               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
9909         else
9910           addSuccessorWithProb(SwitchMBB, DefaultMBB);
9911 
9912         // Insert the true branch.
9913         SDValue BrCond =
9914             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
9915                         DAG.getBasicBlock(Small.MBB));
9916         // Insert the false branch.
9917         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
9918                              DAG.getBasicBlock(DefaultMBB));
9919 
9920         DAG.setRoot(BrCond);
9921         return;
9922       }
9923     }
9924   }
9925 
9926   if (TM.getOptLevel() != CodeGenOpt::None) {
9927     // Here, we order cases by probability so the most likely case will be
9928     // checked first. However, two clusters can have the same probability in
9929     // which case their relative ordering is non-deterministic. So we use Low
9930     // as a tie-breaker as clusters are guaranteed to never overlap.
9931     llvm::sort(W.FirstCluster, W.LastCluster + 1,
9932                [](const CaseCluster &a, const CaseCluster &b) {
9933       return a.Prob != b.Prob ?
9934              a.Prob > b.Prob :
9935              a.Low->getValue().slt(b.Low->getValue());
9936     });
9937 
9938     // Rearrange the case blocks so that the last one falls through if possible
9939     // without changing the order of probabilities.
9940     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
9941       --I;
9942       if (I->Prob > W.LastCluster->Prob)
9943         break;
9944       if (I->Kind == CC_Range && I->MBB == NextMBB) {
9945         std::swap(*I, *W.LastCluster);
9946         break;
9947       }
9948     }
9949   }
9950 
9951   // Compute total probability.
9952   BranchProbability DefaultProb = W.DefaultProb;
9953   BranchProbability UnhandledProbs = DefaultProb;
9954   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
9955     UnhandledProbs += I->Prob;
9956 
9957   MachineBasicBlock *CurMBB = W.MBB;
9958   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
9959     MachineBasicBlock *Fallthrough;
9960     if (I == W.LastCluster) {
9961       // For the last cluster, fall through to the default destination.
9962       Fallthrough = DefaultMBB;
9963     } else {
9964       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
9965       CurMF->insert(BBI, Fallthrough);
9966       // Put Cond in a virtual register to make it available from the new blocks.
9967       ExportFromCurrentBlock(Cond);
9968     }
9969     UnhandledProbs -= I->Prob;
9970 
9971     switch (I->Kind) {
9972       case CC_JumpTable: {
9973         // FIXME: Optimize away range check based on pivot comparisons.
9974         JumpTableHeader *JTH = &JTCases[I->JTCasesIndex].first;
9975         JumpTable *JT = &JTCases[I->JTCasesIndex].second;
9976 
9977         // The jump block hasn't been inserted yet; insert it here.
9978         MachineBasicBlock *JumpMBB = JT->MBB;
9979         CurMF->insert(BBI, JumpMBB);
9980 
9981         auto JumpProb = I->Prob;
9982         auto FallthroughProb = UnhandledProbs;
9983 
9984         // If the default statement is a target of the jump table, we evenly
9985         // distribute the default probability to successors of CurMBB. Also
9986         // update the probability on the edge from JumpMBB to Fallthrough.
9987         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
9988                                               SE = JumpMBB->succ_end();
9989              SI != SE; ++SI) {
9990           if (*SI == DefaultMBB) {
9991             JumpProb += DefaultProb / 2;
9992             FallthroughProb -= DefaultProb / 2;
9993             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
9994             JumpMBB->normalizeSuccProbs();
9995             break;
9996           }
9997         }
9998 
9999         addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
10000         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
10001         CurMBB->normalizeSuccProbs();
10002 
10003         // The jump table header will be inserted in our current block, do the
10004         // range check, and fall through to our fallthrough block.
10005         JTH->HeaderBB = CurMBB;
10006         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
10007 
10008         // If we're in the right place, emit the jump table header right now.
10009         if (CurMBB == SwitchMBB) {
10010           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
10011           JTH->Emitted = true;
10012         }
10013         break;
10014       }
10015       case CC_BitTests: {
10016         // FIXME: Optimize away range check based on pivot comparisons.
10017         BitTestBlock *BTB = &BitTestCases[I->BTCasesIndex];
10018 
10019         // The bit test blocks haven't been inserted yet; insert them here.
10020         for (BitTestCase &BTC : BTB->Cases)
10021           CurMF->insert(BBI, BTC.ThisBB);
10022 
10023         // Fill in fields of the BitTestBlock.
10024         BTB->Parent = CurMBB;
10025         BTB->Default = Fallthrough;
10026 
10027         BTB->DefaultProb = UnhandledProbs;
10028         // If the cases in bit test don't form a contiguous range, we evenly
10029         // distribute the probability on the edge to Fallthrough to two
10030         // successors of CurMBB.
10031         if (!BTB->ContiguousRange) {
10032           BTB->Prob += DefaultProb / 2;
10033           BTB->DefaultProb -= DefaultProb / 2;
10034         }
10035 
10036         // If we're in the right place, emit the bit test header right now.
10037         if (CurMBB == SwitchMBB) {
10038           visitBitTestHeader(*BTB, SwitchMBB);
10039           BTB->Emitted = true;
10040         }
10041         break;
10042       }
10043       case CC_Range: {
10044         const Value *RHS, *LHS, *MHS;
10045         ISD::CondCode CC;
10046         if (I->Low == I->High) {
10047           // Check Cond == I->Low.
10048           CC = ISD::SETEQ;
10049           LHS = Cond;
10050           RHS=I->Low;
10051           MHS = nullptr;
10052         } else {
10053           // Check I->Low <= Cond <= I->High.
10054           CC = ISD::SETLE;
10055           LHS = I->Low;
10056           MHS = Cond;
10057           RHS = I->High;
10058         }
10059 
10060         // The false probability is the sum of all unhandled cases.
10061         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
10062                      getCurSDLoc(), I->Prob, UnhandledProbs);
10063 
10064         if (CurMBB == SwitchMBB)
10065           visitSwitchCase(CB, SwitchMBB);
10066         else
10067           SwitchCases.push_back(CB);
10068 
10069         break;
10070       }
10071     }
10072     CurMBB = Fallthrough;
10073   }
10074 }
10075 
10076 unsigned SelectionDAGBuilder::caseClusterRank(const CaseCluster &CC,
10077                                               CaseClusterIt First,
10078                                               CaseClusterIt Last) {
10079   return std::count_if(First, Last + 1, [&](const CaseCluster &X) {
10080     if (X.Prob != CC.Prob)
10081       return X.Prob > CC.Prob;
10082 
10083     // Ties are broken by comparing the case value.
10084     return X.Low->getValue().slt(CC.Low->getValue());
10085   });
10086 }
10087 
10088 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
10089                                         const SwitchWorkListItem &W,
10090                                         Value *Cond,
10091                                         MachineBasicBlock *SwitchMBB) {
10092   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
10093          "Clusters not sorted?");
10094 
10095   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
10096 
10097   // Balance the tree based on branch probabilities to create a near-optimal (in
10098   // terms of search time given key frequency) binary search tree. See e.g. Kurt
10099   // Mehlhorn "Nearly Optimal Binary Search Trees" (1975).
10100   CaseClusterIt LastLeft = W.FirstCluster;
10101   CaseClusterIt FirstRight = W.LastCluster;
10102   auto LeftProb = LastLeft->Prob + W.DefaultProb / 2;
10103   auto RightProb = FirstRight->Prob + W.DefaultProb / 2;
10104 
10105   // Move LastLeft and FirstRight towards each other from opposite directions to
10106   // find a partitioning of the clusters which balances the probability on both
10107   // sides. If LeftProb and RightProb are equal, alternate which side is
10108   // taken to ensure 0-probability nodes are distributed evenly.
10109   unsigned I = 0;
10110   while (LastLeft + 1 < FirstRight) {
10111     if (LeftProb < RightProb || (LeftProb == RightProb && (I & 1)))
10112       LeftProb += (++LastLeft)->Prob;
10113     else
10114       RightProb += (--FirstRight)->Prob;
10115     I++;
10116   }
10117 
10118   while (true) {
10119     // Our binary search tree differs from a typical BST in that ours can have up
10120     // to three values in each leaf. The pivot selection above doesn't take that
10121     // into account, which means the tree might require more nodes and be less
10122     // efficient. We compensate for this here.
10123 
10124     unsigned NumLeft = LastLeft - W.FirstCluster + 1;
10125     unsigned NumRight = W.LastCluster - FirstRight + 1;
10126 
10127     if (std::min(NumLeft, NumRight) < 3 && std::max(NumLeft, NumRight) > 3) {
10128       // If one side has less than 3 clusters, and the other has more than 3,
10129       // consider taking a cluster from the other side.
10130 
10131       if (NumLeft < NumRight) {
10132         // Consider moving the first cluster on the right to the left side.
10133         CaseCluster &CC = *FirstRight;
10134         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10135         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10136         if (LeftSideRank <= RightSideRank) {
10137           // Moving the cluster to the left does not demote it.
10138           ++LastLeft;
10139           ++FirstRight;
10140           continue;
10141         }
10142       } else {
10143         assert(NumRight < NumLeft);
10144         // Consider moving the last element on the left to the right side.
10145         CaseCluster &CC = *LastLeft;
10146         unsigned LeftSideRank = caseClusterRank(CC, W.FirstCluster, LastLeft);
10147         unsigned RightSideRank = caseClusterRank(CC, FirstRight, W.LastCluster);
10148         if (RightSideRank <= LeftSideRank) {
10149           // Moving the cluster to the right does not demot it.
10150           --LastLeft;
10151           --FirstRight;
10152           continue;
10153         }
10154       }
10155     }
10156     break;
10157   }
10158 
10159   assert(LastLeft + 1 == FirstRight);
10160   assert(LastLeft >= W.FirstCluster);
10161   assert(FirstRight <= W.LastCluster);
10162 
10163   // Use the first element on the right as pivot since we will make less-than
10164   // comparisons against it.
10165   CaseClusterIt PivotCluster = FirstRight;
10166   assert(PivotCluster > W.FirstCluster);
10167   assert(PivotCluster <= W.LastCluster);
10168 
10169   CaseClusterIt FirstLeft = W.FirstCluster;
10170   CaseClusterIt LastRight = W.LastCluster;
10171 
10172   const ConstantInt *Pivot = PivotCluster->Low;
10173 
10174   // New blocks will be inserted immediately after the current one.
10175   MachineFunction::iterator BBI(W.MBB);
10176   ++BBI;
10177 
10178   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
10179   // we can branch to its destination directly if it's squeezed exactly in
10180   // between the known lower bound and Pivot - 1.
10181   MachineBasicBlock *LeftMBB;
10182   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
10183       FirstLeft->Low == W.GE &&
10184       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
10185     LeftMBB = FirstLeft->MBB;
10186   } else {
10187     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10188     FuncInfo.MF->insert(BBI, LeftMBB);
10189     WorkList.push_back(
10190         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
10191     // Put Cond in a virtual register to make it available from the new blocks.
10192     ExportFromCurrentBlock(Cond);
10193   }
10194 
10195   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
10196   // single cluster, RHS.Low == Pivot, and we can branch to its destination
10197   // directly if RHS.High equals the current upper bound.
10198   MachineBasicBlock *RightMBB;
10199   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
10200       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
10201     RightMBB = FirstRight->MBB;
10202   } else {
10203     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
10204     FuncInfo.MF->insert(BBI, RightMBB);
10205     WorkList.push_back(
10206         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
10207     // Put Cond in a virtual register to make it available from the new blocks.
10208     ExportFromCurrentBlock(Cond);
10209   }
10210 
10211   // Create the CaseBlock record that will be used to lower the branch.
10212   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
10213                getCurSDLoc(), LeftProb, RightProb);
10214 
10215   if (W.MBB == SwitchMBB)
10216     visitSwitchCase(CB, SwitchMBB);
10217   else
10218     SwitchCases.push_back(CB);
10219 }
10220 
10221 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
10222 // from the swith statement.
10223 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
10224                                             BranchProbability PeeledCaseProb) {
10225   if (PeeledCaseProb == BranchProbability::getOne())
10226     return BranchProbability::getZero();
10227   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
10228 
10229   uint32_t Numerator = CaseProb.getNumerator();
10230   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
10231   return BranchProbability(Numerator, std::max(Numerator, Denominator));
10232 }
10233 
10234 // Try to peel the top probability case if it exceeds the threshold.
10235 // Return current MachineBasicBlock for the switch statement if the peeling
10236 // does not occur.
10237 // If the peeling is performed, return the newly created MachineBasicBlock
10238 // for the peeled switch statement. Also update Clusters to remove the peeled
10239 // case. PeeledCaseProb is the BranchProbability for the peeled case.
10240 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
10241     const SwitchInst &SI, CaseClusterVector &Clusters,
10242     BranchProbability &PeeledCaseProb) {
10243   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10244   // Don't perform if there is only one cluster or optimizing for size.
10245   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
10246       TM.getOptLevel() == CodeGenOpt::None ||
10247       SwitchMBB->getParent()->getFunction().optForMinSize())
10248     return SwitchMBB;
10249 
10250   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
10251   unsigned PeeledCaseIndex = 0;
10252   bool SwitchPeeled = false;
10253   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
10254     CaseCluster &CC = Clusters[Index];
10255     if (CC.Prob < TopCaseProb)
10256       continue;
10257     TopCaseProb = CC.Prob;
10258     PeeledCaseIndex = Index;
10259     SwitchPeeled = true;
10260   }
10261   if (!SwitchPeeled)
10262     return SwitchMBB;
10263 
10264   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
10265                     << TopCaseProb << "\n");
10266 
10267   // Record the MBB for the peeled switch statement.
10268   MachineFunction::iterator BBI(SwitchMBB);
10269   ++BBI;
10270   MachineBasicBlock *PeeledSwitchMBB =
10271       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
10272   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
10273 
10274   ExportFromCurrentBlock(SI.getCondition());
10275   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
10276   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
10277                           nullptr,   nullptr,      TopCaseProb.getCompl()};
10278   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
10279 
10280   Clusters.erase(PeeledCaseIt);
10281   for (CaseCluster &CC : Clusters) {
10282     LLVM_DEBUG(
10283         dbgs() << "Scale the probablity for one cluster, before scaling: "
10284                << CC.Prob << "\n");
10285     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
10286     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
10287   }
10288   PeeledCaseProb = TopCaseProb;
10289   return PeeledSwitchMBB;
10290 }
10291 
10292 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
10293   // Extract cases from the switch.
10294   BranchProbabilityInfo *BPI = FuncInfo.BPI;
10295   CaseClusterVector Clusters;
10296   Clusters.reserve(SI.getNumCases());
10297   for (auto I : SI.cases()) {
10298     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
10299     const ConstantInt *CaseVal = I.getCaseValue();
10300     BranchProbability Prob =
10301         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
10302             : BranchProbability(1, SI.getNumCases() + 1);
10303     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
10304   }
10305 
10306   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
10307 
10308   // Cluster adjacent cases with the same destination. We do this at all
10309   // optimization levels because it's cheap to do and will make codegen faster
10310   // if there are many clusters.
10311   sortAndRangeify(Clusters);
10312 
10313   if (TM.getOptLevel() != CodeGenOpt::None) {
10314     // Replace an unreachable default with the most popular destination.
10315     // FIXME: Exploit unreachable default more aggressively.
10316     bool UnreachableDefault =
10317         isa<UnreachableInst>(SI.getDefaultDest()->getFirstNonPHIOrDbg());
10318     if (UnreachableDefault && !Clusters.empty()) {
10319       DenseMap<const BasicBlock *, unsigned> Popularity;
10320       unsigned MaxPop = 0;
10321       const BasicBlock *MaxBB = nullptr;
10322       for (auto I : SI.cases()) {
10323         const BasicBlock *BB = I.getCaseSuccessor();
10324         if (++Popularity[BB] > MaxPop) {
10325           MaxPop = Popularity[BB];
10326           MaxBB = BB;
10327         }
10328       }
10329       // Set new default.
10330       assert(MaxPop > 0 && MaxBB);
10331       DefaultMBB = FuncInfo.MBBMap[MaxBB];
10332 
10333       // Remove cases that were pointing to the destination that is now the
10334       // default.
10335       CaseClusterVector New;
10336       New.reserve(Clusters.size());
10337       for (CaseCluster &CC : Clusters) {
10338         if (CC.MBB != DefaultMBB)
10339           New.push_back(CC);
10340       }
10341       Clusters = std::move(New);
10342     }
10343   }
10344 
10345   // The branch probablity of the peeled case.
10346   BranchProbability PeeledCaseProb = BranchProbability::getZero();
10347   MachineBasicBlock *PeeledSwitchMBB =
10348       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
10349 
10350   // If there is only the default destination, jump there directly.
10351   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
10352   if (Clusters.empty()) {
10353     assert(PeeledSwitchMBB == SwitchMBB);
10354     SwitchMBB->addSuccessor(DefaultMBB);
10355     if (DefaultMBB != NextBlock(SwitchMBB)) {
10356       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
10357                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
10358     }
10359     return;
10360   }
10361 
10362   findJumpTables(Clusters, &SI, DefaultMBB);
10363   findBitTestClusters(Clusters, &SI);
10364 
10365   LLVM_DEBUG({
10366     dbgs() << "Case clusters: ";
10367     for (const CaseCluster &C : Clusters) {
10368       if (C.Kind == CC_JumpTable)
10369         dbgs() << "JT:";
10370       if (C.Kind == CC_BitTests)
10371         dbgs() << "BT:";
10372 
10373       C.Low->getValue().print(dbgs(), true);
10374       if (C.Low != C.High) {
10375         dbgs() << '-';
10376         C.High->getValue().print(dbgs(), true);
10377       }
10378       dbgs() << ' ';
10379     }
10380     dbgs() << '\n';
10381   });
10382 
10383   assert(!Clusters.empty());
10384   SwitchWorkList WorkList;
10385   CaseClusterIt First = Clusters.begin();
10386   CaseClusterIt Last = Clusters.end() - 1;
10387   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
10388   // Scale the branchprobability for DefaultMBB if the peel occurs and
10389   // DefaultMBB is not replaced.
10390   if (PeeledCaseProb != BranchProbability::getZero() &&
10391       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
10392     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
10393   WorkList.push_back(
10394       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
10395 
10396   while (!WorkList.empty()) {
10397     SwitchWorkListItem W = WorkList.back();
10398     WorkList.pop_back();
10399     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
10400 
10401     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOpt::None &&
10402         !DefaultMBB->getParent()->getFunction().optForMinSize()) {
10403       // For optimized builds, lower large range as a balanced binary tree.
10404       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
10405       continue;
10406     }
10407 
10408     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
10409   }
10410 }
10411