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