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