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