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