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